Bind C Integer to Lua Global Variable

In C, I want to call the lua myFunction () function, which uses the global variable x. I want to be able to register the variable c (integer) directly as this global variable x.

Something along the lines of:

demo.lua:

function myFunction()
  return x + 3
end

demo.c:

int x = 0;
lua_bindglob(L, "x", &x);

for (x = 0; x < 100; ++x)
{
  lua_getglobal(L, "myFunction");

  // here I call the function and it should evaluate
  // to the current value of x (in c)
  lua_pcall(L, 0, 1, 0);      
  int result = lua_tonumber(L, -1);  

  lua_pop(L, 1);
}

I know that I can change the lua global variables as follows:

lua_pushnumber(L, 3);
lua_setglobal(L, "x");

But I need to have a more direct / faster way to do this. I got a hint that LUA ligthuserdata can help here, but I could not find examples for simple variables.

EDIT: Since I get expressions from the reference, I don't want to change them: Examples here :

+4
source share
2 answers

, , - userdata (, ), __call, / C.

, :

function myFunction()
  return x() + 3
end

, , x + 3, . , x .

:

x(3)

- x = 3 , . , .

__newindex __index , , .

LuaJIT FFI.

+2

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...)

+2

Source: https://habr.com/ru/post/1624055/


All Articles