Any interactions between c++ and lua are going through lua stack. Aware of the stack status may help for debugging. I always do that, will a peek of the current Lua stack not only helps me debug my codes but also helps me figure out the ways how I can pass table from c++ to Lua and vice versa.
I usually interested on knowing how many blocks in my stack had been occupied and also each block’s variable type, if they are string, number or bool, I would like to know the value as well.
The usage is simple, you will only needs to pass in your current Lua State pointer.
The print line output may look like this:
total in stack 2
string: '5A5B5C8855778899'
number: 89
calling c++ function from Lua, implement sleep function
Calling Lua function from c++ is very simple. Value passing between c++ and Lua goes through stack, Lua C API provides a convenience ways for you to call Lua function from C. To call Lua function, you need to specify:
1. Function Name.
2. Parameters of function call.
3. Return values expected ( Lua function support multiple results reture)
Let say my lua function name call f in last.lua, takes 2 parameters.
-- last.lua
function f (x, y)
return (x^2 * math.sin(y))/(1 - x)
end
I perform function call from c++ like this:
Compile it with g++ like this:
g++ -o last{,.cc} -llua -ldl
The results:
Result: -12.158958
Brief explanation of the C++ codes above:
First, I trigger lua_getglobal
to get the function name, then I push 2 parameters to stack. I make
lua_pcall by telling Lua I have 2 params and expect 1 value return.
Upon success, I retrieve the return value from the top of the stack.