开发者

C & lua metatable for object oriented access

I have something like this: (Its actually C++ but in this simplified form there's nothing C++ specific in it)

struct Blob;

// Some key-value accessors on Blob
char * blob_get_value( Blob * b, char * key );
void set_value( Blob * b, char * key, char * value); 


//Some lu开发者_StackOverflowa wrappers for these functions
int blob_get_value_lua( lua_State * L );
int blob_set_value_lua( lua_State * L );

I make these accessible in a syntactically clean way. Currently I expose the Blob object as a userdata and plug get and set into the metatable, using this I can do:

blob = Blob.new()
blob:set("greeting","hello")
print( blob:get("greeting") )

But I'd prefer

blob = Blob.new()
blob.greeting = hello
print( blob.greeting )

I know this can be done by setting the __index to blob_get_value_lua and __newindex to blob_set_value_lua. However making this change will break backward compatibility.

Is there any easy way to have both syntaxes at the same time?


As long as you will keep get and set functions, both approaches will work.

If your object is a regular Lua table, both __index and __newindex will be called only for non-existant keys.

If your object (as you state in the update) is an userdata, you can simulate this behaviour yourself. In __index, if the key is "get" or "set", return an appropriate function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜