[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Embedding lua - passing arrays, multidimensional arrays
- From: Sean Conner <sean@...>
- Date: Thu, 24 Sep 2015 12:05:12 -0400
It was thus said that the Great Ervin Hegedüs once stated:
> Hi Lua-l list,
>
>
> On Wed, Sep 23, 2015 at 10:35:21AM +0200, Michal Kottman wrote:
> >
> > Instead, take a look at Programming in Lua, especially
> > http://www.lua.org/pil/24.2.html to learn about accessing Lua from C using
> > the stack. The book is written for Lua 5.0, but still very relevant even
> > with 5.3.
>
> so, I've read the documents above - that's very-very clear. Now I
> think I understand the stack - it's not just very funny, it has
> cold logic, and pure implementation.
>
> Here is the sample code, what I tries first - and there is the
> state of stack, to help me to clarify the working of Lua stack.
>
> Please review and comment it - em I understanding right it?
>
> /*
> myTable = {
> [0] = { ["a"] = 4, ["b"] = 2 },
> [1] = { ["a"] = 13, ["b"] = 37 }
> } */
An alternative to your code:
lua_newtable(L); /* t */
lua_pushinteger(L,0); /* t n */
lua_newtable(L); /* t n t */
lua_pushinteger(L,4); /* t n t n */
lua_setfield(L,-2,"a"); /* t n t */
lua_pushinteger(L,2); /* t n t n */
lua_setfield(L,-2,"b"); /* t n t */
lua_settable(L,-3); /* t */
lua_pushinteger(L,1); /* t n */
lua_newtable(L); /* t n t */
lua_pushinteger(L,13); /* t n t n */
lua_setfield(L,-2,"a"); /* t n t */
lua_pushinteger(L,37); /* t n t n */
lua_setfield(L,-2,"b"); /* t n t */
lua_settable(L,-3); /* t */
lua_setglobal(L,"t"); /* */
The Lua stack is documented in the comments using a notation from Forth.
The top of the stack is to the right; the leftmost item is at index 1, while
the right most item is -1.
I also have a function I occasionally use to help with the stack
manipulations---it dumps out the current Lua stack (it's in C):
void dump_luastack(lua_State *L)
{
int max;
int i;
printf("LUA STACK DUMP");
max = lua_gettop(L);
for (i = 1 ; i <= max ; i++)
{
const char *name;
const char *type;
int ri;
lua_getglobal(L,"tostring");
lua_pushvalue(L,i);
lua_call(L,1,1);
name = lua_tostring(L,-1);
type = luaL_typename(L,i);
ri = i - max - 1;
printf("Stack: %d %d - %s %s",i,ri,type,name);
lua_pop(L,1);
}
}
-spc
- References:
- Embedding lua - passing arrays, multidimensional arrays, Ervin Hegedüs
- Re: Embedding lua - passing arrays, multidimensional arrays, steve donovan
- Re: Embedding lua - passing arrays, multidimensional arrays, Ervin Hegedüs
- Re: Embedding lua - passing arrays, multidimensional arrays, Michal Kottman
- Re: Embedding lua - passing arrays, multidimensional arrays, Ervin Hegedüs