On Apr 6, 2012, at 7:21 PM, Joe Flemmings wrote:
That would be nice but in lua you create a table in C that you pass to lua.
If you don't mind continue the discussion a little bit longer? I was curious and went and looked at lua and C integration (http://www.lua.org/pil/26.1.html) and came across this example for reading a directory which kind of maps conceptually to a result set.
static int l_dir (lua_State *L) { DIR *dir; struct dirent *entry; int i; const char *path = luaL_checkstring(L, 1);
/* open directory */ dir = opendir(path); if (dir == NULL) { /* error opening the directory? */ lua_pushnil(L); /* return nil and ... */ lua_pushstring(L, strerror(errno)); /* error message */ return 2; /* number of results */ }
/* create result table */ lua_newtable(L); i = 1; while ((entry = readdir(dir)) != NULL) { lua_pushnumber(L, i++); /* push key */ lua_pushstring(L, entry->d_name); /* push value */ lua_settable(L, -3); }
closedir(dir); return 1; /* table is already on top */ }
As far as I can see, lua tables are dynamic hash tables and from the example above there is no need to know the number of entries beforehand.
I simply rewrote the above example to this general C method that can be called from lua and will return any result set given any sql select statement. I have no idea if it will it will compile or has errors, but according to the documentation something like this should be possible. Maybe useful?
static int l_select (lua_State *L) { int result = 1; /* table is on top if all goes well */ const char *select = luaL_checkstring(L, 1); Connection_T c = ConnectionPool_getConnection(pool); // pool is usually global TRY { ResultSet_T r = Connection_executeQuery(c, select); /* create result table */ lua_newtable(L); int columnCount = ResultSet_getColumnCount(r); while (ResultSet_next(r)) { for (int i = 1; i < columnCount; i++) { lua_pushstring(L, ResultSet_getColumnName(r, i)); /* push column name */ lua_pushstring(L, ResultSet_getString(r, i)); /* push value as a string */ lua_settable(L, -3); } } } ELSE { lua_pushnil(L); /* return nil and ... */ lua_pushstring(L, Exception_frame.message); /* error message */ result = 2; /* number of results */ } FINALLY { Connection_close(c); } END_TRY; return result; }