Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesnt lua_newlib work in this example?

Tags:

c

lua

I tried to call from a lua script the c method my_sin. I'm using lua 5.2.2 and wanted to test to use luaL_newlib instead of lua_register. Unfortunately, the lua script doesn't find mysin.

extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}

#include <cmath>

static int my_sin (lua_State *L) {
  lua_pushnumber(L, sin(luaL_checknumber(L, 1)));
  return 1;
}
static const luaL_Reg my_lib[] = {
   {"mysin",   my_sin},
   {NULL, NULL}
};

int my_open(lua_State *L) {
  luaL_newlib(L, my_lib);  
  return 1;
}

int main() {
    lua_State* L = luaL_newstate();
    luaL_openlibs(L); 
    my_open(L);
    luaL_dostring(L, "print(mysin(2))");
    lua_close(L);
    return 0;
}
like image 621
user2328978 Avatar asked Oct 15 '25 23:10

user2328978


1 Answers

luaL_newlib creates a new table and populates it from a list of functions. Your function mysin is inside this table and is not a global function. If you want it to be a global function, use lua_register.

like image 161
lhf Avatar answered Oct 18 '25 16:10

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!