Since you have Lua embedded and available, you can use it. A Lua table is an associative array that can be indexed by any Lua value (except nil
) and store any value. Strings work well as keys, and functions as values.
You can easily turn a call like ObjectSet(id, "ANGLE", 45)
into a call like actions.ANGLE(id,45)
.
To do this, arrange to create the actions
table containing functions to implement each action. The easy way is likely to involve a block of Lua code that intializes the table, but it certainly could also be done from the C side.
actions = {
ANGLE = function(id,theta)
-- do something with id and theta
end,
X = function (id, x)
-- do something with id and x
end,
}
or perhaps more clearly as
module("actions")
function ANGLE(id,theta)
-- ...
end
function X(id,theta)
-- ...
end
From C, you could implement ObjectSet()
something like this (untested):
void ObjectSet(int id, const char *action, int arg) {
lua_getglobal(L,"actions");
lua_getfield(L,-1,action);
lua_remove(L,-2);
lua_pushinteger(L,arg);
if (lua_pcall(L,1,0,0)) {
fprintf(stderr, "Lua error: %s\n", lua_tostring(L,-1));
}
return;
}
Real error handling is left as an exercise. Note that lua_pcall()
is used here so that Lua errors do not propagate out of ObjectSet()
. If you are using C++, you need to be careful because Lua uses setjmp()
and longjmp()
for errors which generally must be translated into C++ exceptions by catching the Lua error and throwing a suitable exception.
I've also naturally left associating the object id with the actual object on the Lua side as an exercise. However, you could implement all of the functions in the actions
table in C, and largely evade this issue.