[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Not one stack but several? I'm mixed up
- From: Jerome Vuarand <jerome.vuarand@...>
- Date: Sun, 6 Jan 2013 14:10:59 +0000
2013/1/6 Patrick <patrick@spellingbeewinnars.org>:
> So I am making progress learning the C API but there is something
> fundamental I am still mixed up about.
>
> After we create a Lua state most of the functions take a pointer to it:
>
> lua_DoSomething( Lua_State *L )
>
> I assume that this is a complex struct that contains the stack mechanisms.
>
> However rereading this in PIL2, on Page 241:
> An important concept here is the stack is not a global structure, each
> function has it's own private local stack
>
> If I push a string onto the stack and then push a number are they not
> sitting on the same data structure? In the Factor language it looks like
> they are but they are in fact not, from what I remember it is some sort of
> overloaded facility.
If you push a string and then a number, they both sit on the same data
structure. The following would print 2:
L = luaL_newstate();
lua_pushstring(L, "foo");
lua_pushnumber(L, 42);
printf("stack size: %d\n", lua_gettop(L));
lua_close(L);
However if you push a string, and then call a function, and that
function push a number, they don't sit on the same stack. The
following would print 1:
static int f(lua_State* L)
{
lua_pushnumber(L, 42);
printf("stack size: %d\n", lua_gettop(L));
return 0;
}
int main()
{
lua_State* L;
L = luaL_newstate();
lua_pushstring(L, "foo");
lua_pushcfunction(L, f);
lua_pcall(L, 0, 0, 0);
lua_close(L);
return 0;
}
In that example, the function f doesn't have access to the stack of
the function main, and cannot access the string "foo". Note that the
functions need to be different in the Lua sense, not the C sense. You
need to use lua_call or lua_pcall to tell Lua that you are calling a
new Lua function. If you call directly f from main in C, they would
then share the same stack.
> Factors core is in C++, Lua is not, so I don't get how
> it could be overloaded and I don't understand how each function has it's own
> stack but "the stack"(as in singular) gets this value or that value if that
> is the case.
>
> Could someone straighten me out?
There is no need for overloading, since you have to explicitly use Lua
API functions (lua_call/lua_pcall) to trigger that change in the data
structure.
I hope this clarifies things for you.