Using C++ to call lua table methods
417
0
Advertisement
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:
And here's the source to call it:
Output:
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);'.)
Output:
Okay, here's are example script:
local OurTable = { name = "Donny"; }function OurTable:Speak() print("Hi my name is " .. self.name);endAnd 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 DonnyOk, 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);endlua_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?Advertisement
Advertisement
Advertisement
Discussion