lua-users home
lua-l archive

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


On Wed, Jan 7, 2009 at 8:41 AM, Roger Durañona Vargas <luo_hei@yahoo.es> wrote:
> I need a Lua script to return an array of value pairs to the C host
> application. I have been checking the docs, but I cant find the correct
> syntax to define a table with such structure.
> I tried table[index].member, but that was incorrect. Can somebody
> suggest me a way to do this?

There are a lot of different ways to do this.  Assuming that you need
an ordered list, and that each pair contains values of unknown types,
some of which may include duplicates, you could define the structure
statically like so:

t = {
	{"foo", "abcdef"},
	{"bar", 123},
	{"foo", 456},
	{9, "hello"},
	-- and so on
}


You could also define it dynamically using table.insert():

t = {}
table.insert(t, {"foo", "abcdef"})
table.insert(t, {"bar", 123})
table.insert(t, {"foo", 456})
table.insert(t, {9, "hello"})
-- and so on


Assuming the table was defined in it's own lua file, you could pass it
back to the host app by declaring it as a global and then reading that
global in:

Foo1.lua:
MyGlobal = {
	-- etc
}

in Foo1.c:
lua_dofile(L, "Foo1.lua");
lua_getglobal(L, "MyGlobal");
/* The table referenced by MyGlobal, provided it was defined, will now
be on top of the stack. */


Alternatively, you could have the script return the value, thus
preventing it from populating the global namespace:

Foo2.lua:
local t = {
	-- etc
}
return t

in Foo2.c:
lua_dofile(L, "Foo2.lua")
/* The table, provided Foo2.lua was defined as shown above, will now
be on top of the stack. */


You could also have the script pass the table into the host app via a
function.  For example, assuming the host app defined a global
function called FooData, and that the data was statically defined, you
could have a script that looked like this:

FooData({
	{"foo", "abcdef"},
	{"bar", 123},
	{"foo", 456},
	{9, "hello"},
	-- and so on
})

Lua provides some syntactic sugar for such cases as well.  You could
rewrite that as such:

FooData {
	{"foo", "abcdef"},
	{"bar", 123},
	{"foo", 456},
	{9, "hello"},
	-- and so on
}

--
David Ludwig
dludwig@pobox.com