lua-users home
lua-l archive

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


Hi all,

I am trying to learn embedding Lua in C++ for a couple of days now and
I've entered the world of operator overloading using metatables.

In the following C++ code I try to overload the __index operator of a
table 'variables' with a method printing a message. However, the message
only appears if the key doesn't match any in the 'variables' table: Why
isn't the indexHandler method called for every indexing operation?

Am I doing something wrong here? Have I misunderstood something? I've
tried to understand the code at
http://lua-users.org/wiki/BindingWithMembersAndMethods but it's still a
bit too advanced for me...

Oh, and another question: what is the difference between the globals
table and the registry table? And which should I use when?

Thanks,

-Leroy

extern "C" {

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

} /* extern "C" */

#include <iostream>
#include <string>

static int indexHandler(lua_State * l)
{
	std::cout << "indexHandler" << std::endl;
	lua_pushnumber(l, 10.20);
	return 1;
}

int main(int argc, char *argv[])
{
	lua_State *l;

	l = lua_open();

	luaopen_base(l);
	luaopen_io(l);

	// create 'variables' table
	lua_pushstring(l, "variables");
	lua_newtable(l);

	// add myvar to variables
	lua_pushstring(l, "myvar");
	lua_pushnumber(l, 123.45);
	lua_rawset(l, -3);

	// create metatable
	lua_newtable(l);

	// add __index method to metatable
	lua_pushstring(l, "__index");
	lua_pushcfunction(l, indexHandler);
	lua_rawset(l, -3);

	lua_setmetatable(l, -2);

	lua_settable(l, LUA_GLOBALSINDEX);

	// myvar is a key in the variables table
	// indexHandler isn't called here, why?
	char cmd1[] = "print(variables.myvar)";
	luaL_loadbuffer(l, cmd1, sizeof(cmd1) - 1, "xxx");
	lua_pcall(l, 0, 0, 0);

	// foo is not a key in the variables table
	// indexHandler is called here, as I would expect
	char cmd2[] = "print(variables.foo)";
	luaL_loadbuffer(l, cmd2, sizeof(cmd2) - 1, "xxx");
	lua_pcall(l, 0, 0, 0); 

	lua_close(l);

	return 0;
}