0

I want to make something like this:
1. Create object in Lua
2. Get this object to C++
3. Perform some method on this object passing it from C++


Now I have this in Lua:

Account = {balance = 0}

function Account.Create(name)
    local a = Account:new(nil, name);
    return a;
end

function Account:new (o, name)
  o = o or {name=name}
  setmetatable(o, self)
  self.__index = self
  return o
end

function Account:Info ()
  return self.name;
end

Code in C++

//get Lua object

lua_getglobal (L, "Account");
lua_pushstring(L, "Create");
lua_gettable(L, -2);
lua_pushstring(L, "SomeName");
lua_pcall(L, 1, 1, 0);
const void* pointer = lua_topointer(L, -1);
lua_pop(L, 3);

//then I want to perform some method on object

lua_getglobal (L, "Account");
lua_pushstring(L, "Info");
lua_gettable(L, -2);
lua_pushlightuserdata(L,(void*) pointer );
lua_pcall(L, 0, 1, 0);
//NOW I GET "attempt to index local 'self' (a userdata value)'
const char* str = lua_tostring(L, -1);
...etc...

Do you what I made wrong ? How can I get this Lua object to C++ ?

1 Answer 1

2
const void* pointer = lua_topointer(L, -1);

Lua tables are not C objects. They're not void*s. The lua_topointer documentation says that the function is mainly for debugging purposes. You're not debugging anything.

Lua tables can only be accessed through the Lua API. You can't just get a pointer to a Lua table or something. Instead, what you need to do is store the Lua table in a place, and then retrieve it from that location when you want to access it. The typical place for storing this sort of data is the Lua registry. It's inaccessible from Lua code; only the C-API can talk to it.

Generally, you'll have some table stored in the registry that contains all of the Lua values that you are currently holding. That way, your use of the registry won't bash someone else's use of it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.