Originally Posted by
Robert Kosek
Thanks much, Paul.
Quick question since I only skimmed your code. Does this, or can this, emulate properties too? And functions with variables, not just a single function with no variables or returns?
The only way I can think to simulate properties, is to create Get/Set methods in the TLuaClass descendent and use those :-)
To your other question, your TLuaClass methods MUST take 1 input parameter of type lua_State and return a result as Integer like so:
Function MyMethodName(L: lua_State): Integer;
but they can then quite happily receive any number of Lua input parameters via the lua_State's stack, and return any number of Lua variables back onto the lua_State's stack like so:
This one takes no input parameters and returns no results
Code:
Function TLuaClassCounter.IncCount(L: lua_State): Integer;
Begin
Inc(FCount);
Result := 0;
End;
This one takes no input parameters and returns 1 result (the number)
Code:
Function TLuaClassCounter.GetCount(L: lua_State): Integer;
Begin
lua_pushnumber(L,FCount);
Result := 1;
End;
Here is an example of a TLuaClass method that takes 2 numbers, and returns the Sum and the Difference of the 2 numbers as 2 separate results
Code:
Function TLuaClassTest.SumDiff(L: lua_State): Integer;
Var
a,b: Single;
sum,diff: Single;
Begin
// make sure that there are 2 inputs, and that they are numbers
a := luaL_checknumber(L,1);
b := luaL_checknumber(L,2);
sum := a + b;
diff := a - b;
// push both results onto the Lua stack
lua_pushnumber(L,sum);
lua_pushnumber(L,diff);
Result := 2;
End;
For example this may be called like so in a Lua script:
Code:
a,b = Test.SumDiff(5,10) -- assume it is created already
print(a,b)
This one calles the appropriate internal TLuaClass methods depending on the MethodIndex
Code:
Function TLuaClassCounter.CallLuaMethod(L: lua_State; MethodIndex: Integer): Integer;
Begin
Case MethodIndex Of
0 : Result := IncCount(L);
1 : Result := GetCount(L);
Else
lua_pushstring(L,PChar(Format(
'TLuaClassCounter.CallLuaMethod: MethodIndex "%d" out of bounds',
[MethodIndex])));
lua_error(L);
End;
End;
Bookmarks