lua-users home
lua-l archive

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


On Wed, Jan 7, 2009 at 1:41 PM, 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?

Your table[index].member would access a _key_ value pair of a table like
{ member = value }

I'm not entirely sure if that's you mean, but an array of value pairs
would be something like
{ {v11, v12}, {v21, v22}, {v31, v32}, ... }

So, to get the latter in C you can do something along these lines,
where 'example' contains your Lua script and error checking is
minimal:

#include <stdio.h>
#include <string.h>

#include "lua.h"
#include "lauxlib.h"

int
main(int argc, char *argv[])
{
	lua_State *L;
	char *example =
		"arg1 = select(1, ...)\n"
		"arg2 = select(2, ...)\n"
		"return { { 1, 2 }, { 3, 4 }, { arg1, arg2 } }\n";

	if (!(L = lua_open())) {
		fprintf(stderr, "%s\n", lua_tostring(L, -1));
		return 1;
	}
	luaL_openlibs(L);

	if (luaL_loadbuffer(L, example, strlen(example), "example"))
		lua_error(L);

	lua_pushstring(L, "test1");
	lua_pushstring(L, "test2");
	lua_call(L, 2, 1);
	luaL_checktype(L, -1, LUA_TTABLE);

	{	int i;
		int n = lua_objlen(L, -1);

		for (i = 1; i <= n; i++) {
			lua_rawgeti(L, -1, i);    /* get pair and push on top of stack */
			luaL_checktype(L, -1, LUA_TTABLE);
			if (lua_type(L, -1) != LUA_TTABLE || lua_objlen(L, -1) != 2) {
				fprintf(stderr, "Entry %d is not a pair of values.\n", i);
			} else {
				lua_rawgeti(L, -1, 2);    /* get second value of pair and push on stack */
				lua_rawgeti(L, -2, 1);    /* get first value of pair and push on stack */
				fprintf(stderr, "Entry %d: { %s, %s }.\n",
						i, lua_tolstring(L, -1, NULL), lua_tolstring(L, -2, NULL));
				lua_pop(L, 2);    /* pop the two values */
			}
			lua_pop(L, 1);   /* pop pair */
		}
	}

	lua_close(L);
	return 0;
}


Output of that looks like:

Entry 1: { 1, 2 }.
Entry 2: { 3, 4 }.
Entry 3: { test1, test2 }.


Robby