LuaScript Xojo and Real Studio Plugin

LuaScript.RegisterFunction Method (console safe)

Registers a Xojo or Real Studio function that can be called from within Lua.

RegisterFunction(
   name as String,
   fuction as Ptr)

Parameters

name
The name of the function to be registered as Lua should know it by. This does not have to be the same as its REALbasic name.
fuction
The address of the REALbasic function.

Remarks

Note that the signature of the function always needs to be:
Function FunctionName(lua as Ptr) As Integer

Where function name can be anything you want, but the parameter must always be ua as Ptr and the return value a integer.
The REALbasic function must reside in a global module, not a class.

Registering a REALbasic function to Lua:

ls.RegisterFunction("calculatesomething", AddressOf REALbasicFunctionsForLua.CalculateSomething)


The REALbasic function:
Function CalculateSomething(lua as Ptr) As Integer
    Dim context as LuaScriptContext
    Dim result as Double
   
    context = new LuaScriptContext(lua)
   
    // Lua does not know how many parameters your function has so it will push all its got to the stack,
    // your responsible for making sure your get the correct amount of them
    if context.ParameterCount <> 2 then
       context.SetError("CalculateSomething expects two parameters")
       return 0
    end if
   
    // We fetch the two parameters and then we multiply them
    result = context.GetDouble(1,false) * context.GetDouble(2,false)
   
    // To return the calculated value we push it onto the stack
    context.Push(result)
   
    // We always return 1 here to tell Lua that all was good
    return 1
End Function


Note that this REALbasic function accepted two double parameters and returned one double parameter.

So lua would see the function as: x = calculatesomething(a,b)

See Also

LuaScript Class