Skip to main content
GameDev.net gamedev.net

PRO Tired of ads? Read GameDev.net ad-free and help keep the community independent with GameDev Pro — $3/month.

Using C++ to call lua table methods

Using C++ to call lua table methods

Programmer16
Beals Software · · 1 min read
417 0
I googled this shit for 4 hours last night and didn't find a damn thing. Eventually, I got it by myself so I figured I'd put it up here for anyone wondering.

Okay, here's are example script:
local OurTable = { name = "Donny"; }function OurTable:Speak()    print("Hi my name is " .. self.name);end


And here's the source to call it:
lua_getglobal(State, "OurTable");lua_pushstring(State, "Speak");lua_gettable(State, -2);lua_insert(State, -1);lua_insert(State, -2);lua_call(State, 1, 0);


Output:
Hi my name is Donny


Ok, so we get our global on the first line. The second line pushes the name of the function onto the stack for lua_gettable, which pushes the function onto the stack.

Then I use lua_insert to first push the function onto the stack, then to push the table onto the stack. We push the table onto the stack because lua table methods are like class methods in C++, the first parameter is 'hidden' and is passed by the system (so, we need to pass it.) So, now our stack looks like so:
OurTable
OurTable:Speak

Pretty simple actually, but I couldn't figure it out because I didn't have much knowledge of Lua and the C++ side of the library.

Btw, you can push any extra arguments for the function after the table is inserted (the line 'lua_insert(State, -2);'.)
local OurTable = { name = "Donny"; }function OurTable:Speak(text)    print(self.name .. ": " .. text);end


lua_getglobal(State, "OurTable");lua_pushstring(State, "Speak");lua_gettable(State, -2);lua_insert(State, -1);lua_insert(State, -2);lua_pushstring(State, "Where am I?");lua_call(State, 1, 0);lua_getglobal(State, "OurTable");lua_pushstring(State, "Speak");lua_gettable(State, -2);lua_insert(State, -1);lua_insert(State, -2);lua_pushstring(State, "What's going on?");lua_call(State, 1, 0);


Output:
Donny: Where am I?Donny: What's going on?

Discussion

Loading comments...