lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


This is what i got to register a class to lua:

type
  tMyObject = class
  private
    FText : string;
  public
    procedure dosomething(t: string);
    property text : string read ftext write ftext;
  end;

var
  meta_methods, methods: array of PluaL_reg;

procedure tmyobject.dosomething(t: string);
begin
  ftext:=t;
  writeln('DELPHI: '+ftext); //show debug info
end;

function lua_myobject_create(L: Plua_state): Integer; cdecl;
begin
  writeln('lua called create');
  lua_boxpointer(L, Pointer(TMyObject.Create));
  lua_pushvalue(L, lua_upvalueindex(1));
  lua_setmetatable(L, -2);
  Result:= 1;
end;

// dosomething is a method receiving only 1 parameter of type String
function lua_myobject_dosomething(L: Plua_state): Integer; cdecl;
var
  o: TMyObject;
begin
  writeln('lua called test');
  o:= TMyObject(lua_touserdata(L, 1));
  o.DoSomething(lua_tostring(L, 2));
  Result:= 0; // no return values
end;

// delete __GC
function lua_myobject_delete(L: Plua_state): Integer; cdecl;
begin
  writeln('lua called __gc');
  result:= 0; // no return values
end;

procedure registerwithlua(L: Plua_State);
var
  methodtable, metatable: integer;
  reg: Plual_Reg;
begin
  SetLength(methods, 3);
  SetLength(meta_methods, 2);

  new(reg);
  reg^.name:='new';
  reg^.func:=lua_myobject_create;
  methods[0]:=reg;

  new(reg);
  reg^.name:='test';
  reg^.func:=lua_myobject_dosomething;
  methods[1]:=reg;

  new(reg);
  reg^.name:='n';
  reg^.func:=nil;
  methods[2]:=reg;

  new(reg);
  reg^.name:='__gc';
  reg^.func:=lua_myobject_delete;
  meta_methods[0]:=reg;

  new(reg);
  reg^.name:='n';
  reg^.func:=nil;
  meta_methods[1]:=reg;

  lua_pushliteral(L, 'tMyObject');   // name of Image table */
  lua_newtable(L);
  methodtable   := lua_gettop(L);    // myclass(object) methods table */
  lua_newtable(L);
  metatable := lua_gettop(L);        // myclass(object) metatable */
  lua_pushliteral(L, '__index');     // add index event to metatable */
  lua_pushvalue(L, methodtable);
  lua_settable(L, metatable);        // metatable.__index = methods */
  lua_pushliteral(L, '__metatable'); // hide metatable */
  lua_pushvalue(L, methodtable);
  lua_settable(L, metatable);        // metatable.__metatable = methods */
  luaL_openlib(L, 0, @meta_methods,  0); // fill metatable */
  luaL_openlib(L, 0, @methods, 1);   // fill myclass(object) methods table
*/
  lua_settable(L, LUA_GLOBALSINDEX); // add myclass(object) to globals */
end;

This is how i try to call it from lua:
obj = tMyObject.new()
obj.test('hello')

But it does not work. I get this by looking at c examples. But i must be
doing something wrong... Most likely my registerwithlua procedure is not
correct. As lua does not like even obj = tMyObject.new() .