C, Lua, __index __newindex . (get set), , , , ( ).
, :
#include <string.h>
#include <limits.h>
#include <lua.h>
#include <lauxlib.h>
static int x = 0;
static int myvar_index( lua_State* L ) {
char const* key = lua_tostring( L, 2 );
if( key != NULL && strcmp( key, "x" ) == 0 )
lua_pushinteger( L, x );
else
lua_pushnil( L );
return 1;
}
static int myvar_newindex( lua_State* L ) {
char const* key = lua_tostring( L, 2 );
if( key != NULL && strcmp( key, "x" ) == 0 ) {
lua_Integer i = luaL_checkinteger( L, 3 );
if( i > INT_MAX || i < INT_MIN )
luaL_error( L, "variable value out of range" );
x = i;
} else
lua_rawset( L, 1 );
return 0;
}
int luaopen_myvar( lua_State* L ) {
luaL_Reg const metamethods[] = {
{ "__index", myvar_index },
{ "__newindex", myvar_newindex },
{ NULL, NULL }
};
#if LUA_VERSION_NUM < 502
lua_pushvalue( L, LUA_GLOBALSINDEX );
lua_newtable( L );
luaL_register( L, NULL, metamethods );
#else
lua_pushglobaltable( L );
luaL_newlib( L, metamethods );
#endif
lua_setmetatable( L, -2 );
return 0;
}
C , , , , .
, , / , . (I.e. , , C...)