lua-users home
lua-l archive

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


On Tue, Jan 1, 2013 at 4:52 PM, Patrick <patrick@spellingbeewinnars.org> wrote:
> Hello
>
> I am trying to write a binding for Lua and I have hit a snag because I don't
> really understand the plain C API well enough.
>
> Could someone please tell me if this is wrong..
>
> If we do this:
> int * foo
>
> we have created a pointer that can accept an int's value at a specific
> memory location.

No, you've created a pointer that can be assigned to point at a memory
location containing an int. It doesn't point to anything until you do
something like:

int bar;
foo = &bar;

(Do be warned that this is dangerous, you wouldn't assign a pointer to
a local variable to a global variable. But this is just for
illustration.)

> If we do this:
> lua_State * foo
>
> We have "prepared" a memory location for all kinds if types ints, chars,
> function pointers and so on that lua will need and when we do this:
>
> foo = luaL_newstate()
>
> We are propagating that memory location with values and that memory location
> is now a lua instance.
>
> Did I get this right?

Not even close.

"lua_State* foo" doesn't do anything with regards to allocating or
preparing memory for the state. It's just a pointer -- a number that
says where you can find something in memory, although you haven't
initialized it until you call luaL_newstate(). That function does the
work of allocating the memory and initializing its contents.

> So this must be silly but I can't figure it out. I know this isn't good
> programming practice but if I do this:
>
> lua_State *L;
> L = luaL_newstate();
>
> int main(void)
> { code continues.....
>
> I get these errors:
>
> hello.c:17:1: warning: data definition has no type or storage class [enabled
> by default]
> hello.c:17:1: error: conflicting types for ‘L’
> hello.c:16:12: note: previous declaration of ‘L’ was here
> hello.c:17:5: warning: initialization makes integer from pointer without a
> cast [enabled by default]
> hello.c:17:1: error: initializer element is not constant
>
> If the space is allocated and propagated in global space would it not just
> be available later inside a function scope?

You can't put code in the "global" space in C. All code has to be
contained within a function. You probably want to put the call to
luaL_newstate() in main().

/s/ Adam