lua-users home
lua-l archive

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

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:
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