[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: returning a list of values
- From: Ben Kelly <ranavin@...>
- Date: Wed, 20 Aug 2008 12:55:40 -0400
Roger Durañona wrote:
> I need to make some scripts that returns a list of values to the host
> application. I think that I should use tables, but Im a bit confused
> about how to get them back in C code after the script ends execution.
> Can somebody clear my mind?
>
When lua code returns to C, any values it returns are on top of the
stack (subject to the /nresults/ limit, if specified; see the
documentation for lua_pcall). Thus, if you return a single table, that
table is on top of the stack (at index -1) and you can access it
normally using lua_gettable/lua_settable. For example:
lua_pcall(L, 0, 1, 0); // lua function at top: "return {10,20,30}"
lua_pushnumber(L, 2); lua_gettable(L, -2); // returns 20
You can also simply return multiple values directly, eg:
-- start lua code
return 10,20,30
-- end lua code
When this code returns, C will see three new values on the stack - 10,
20, and 30.
Recommended reading:
http://www.lua.org/manual/5.1/manual.html#lua_call
http://www.lua.org/manual/5.1/manual.html#lua_pcall
In practice you should use pcall (having actual error handling is nice),
but it's the documentation for call that tells you how these things
actually behave.
If you're unclear on how to manipulate tables from inside C, reading up
on lua_gettable, lua_settable, and lua_next is also recommended.
Ben Kelly