lua-users home
lua-l archive

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


Has anyone done this previously?
	Of course :)

Or have a good example?

For what I understood, you want to make a table for the result set and one table for each record. It is quite simple, but I don't (and probably no one) recommend you to do so. It's very expensive to create a table for each record and then gc them all.

I propose you to make a function called, say, dbfetch which receives a handle for the resultset and an optional table as second parameter. When called, if the second argument is a table, then the function will just replace that table's values for the new ones. If the second argument is not a table, then create a new one, populate it, and return.

	I'm not a C/C++ programmer, but I'll try my best to show you an example:


int lua_db_fetch(lua_State *L)
{
	/* Check here if the 1st parameter is your data object */


	// Now we check if the second argument is a table
	if(!lua_istable(L,2))
	{
		// Yes, it is. Now we have to make sure it is
		// on the top of the stack.
		lua_settop(L,1);
		lua_newtable(L);
	}

	// iterate over dataset's fields
	for (int i = 0; i < MYRESULTSET->GETFIELDCOUNT(); i++)
	{
		// Push the name of the field as key
		lua_pushstring(L, MYRESULTSET->GETFIELDNAME(i));
		
		// Here you would push the appropriate value
		// according to field's type.
		lua_pushstring(L, MYRESULTSET->GETFIELDVALUE(i));

		// Now we push the key/value into table.
		lua_settable(L, 2);
	}

	// Returns the table, no matter if we created it or it was
	// passed as a parameter.
	return 1;
}



If you really want to have a table for the dataset and one table for each record, do something like:

int lua_db_query(lua_State *L)
{
	DATASET ds = MYDB->QUERY(lua_tostring(L, 1));

	// Create the core table, the one which will hold all
	// records.
	lua_newtable(L);

	int count = 1;

	// Iterate over all records of the dataset
	while(ds->next())
	{
		lua_pushnumber(L,count++);
		lua_newtable(L);
		for (int i = 0; i < ds->GETFIELDCOUNT(); i++)
		{
			lua_pushstring(L, ds->GETFIELDNAME(i));
			lua_pushstring(L, ds->GETFIELDVALUE(i));
			lua_settable(L, -3);
		}
		lua_settable(L, -3);
	}
	return 1;
}


Please note that it would be possible to use << lua_rawseti(L, count++, -2); >> instead of the last << lua_rawset(L, -3); >> but I choosed to do so because I think it is more intuitive at first :)


Hope it helped a bit.

--rb