lua-users home
lua-l archive

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


Hi Tim,

Got it! Thanks very much for your kind and detailed explanations!

Best Regards
Nan Xiao

On Fri, Jul 3, 2015 at 5:43 AM, Tim Hill <drtimhill@gmail.com> wrote:

On Jul 2, 2015, at 12:04 AM, Nan Xiao <xiaonan830818@gmail.com> wrote:

HI all,

I am a newbie of Lua. When reading the "stack" section in "Programming in Lua", I find the following words:  

" Whenever you want to ask for a value from Lua (such as the value of a global variable), you call Lua, which
pushes the required value on the stack. Whenever you want to pass a value to Lua, you first push the value 
on the stack, and then you call Lua (which will pop the value). "

I am very confused about the above words, and there is no example to explain how to "ask for" and "pass" values
between C and Lua.

Could anyone can give some examples or explain it a bit detailedly? Thanks very much in advance!

Best Regards
Nan Xiao

In outline…

All code in Lua is executed by calling a Lua function. This function must be on the Lua stack (it is a value of type “function”), and one way to do this is to use one of the Lua load APIs such as lua_load(), which compiles a chunk and leaves it on the stack as a function value. You can then call this function using lua_call() etc, but before doing so you need to get any function arguments onto the stack. Typically, you do this using the lua_pushXXX() family of APIs, which move C values onto the stack as Lua values (for example, converting a C integer to Lua number etc). Once you have done that, you use lua_call(), and Lua starts running the function, passing it the values you pushed as arguments. When the function returns, Lua will stop executing, and return from the lua_call() API, with any return values left on the Lua stack. You can access these values in C using the lua_toXXX() family of APIs.

There are lots of variants of this sequence, but this gives you the basic idea.

While Lua is running a function via lua_call(), it might well call a C function supplied by you. In this case, Lua calls the C function (supplied by you), with arguments to the function passed on the stack, which (again) you can access using lua_toXXX(). To return values back to Lua, you push them onto the Lua stack (using lua_pushXXX() APIs).

—Tim