Koisto
Koisto

Reputation: 63

Lua 5.2 Can't access function in C library

I have written this simple library:

#include "lua.h"
#include "lauxlib.h"

static int l_or(lua_State *l)
{
  int i, result = 0;
  int nargs = lua_gettop(l);
  for(i = 1; i <= nargs; ++i)
  {
    result |= lua_tointeger(l, i);
  }

  lua_pushnumber(l, result);
  return 1;
}

static const luaL_Reg mybit [] = {
  {"or", l_or},
  {NULL, NULL}  /* sentinel */
};

int __declspec(dllexport) luaopen_mybit (lua_State *L)
{
      luaL_newlibtable(L, mybit);
      luaL_setfuncs(L, mybit,0);
      return 1;
}

Compiled to a DLL called mylib.dll.

Which I then test using the standalone Lua interpreter using the following script:

print ("Test script")

mybit = require("mybit")
print(mybit)

mybit.or(1,2,3)
--print(mybit.or)

When I run the script I get the following output:

lua: test.lua:6: <name> expected near 'or'

According to all the examples I have looked at this should be perfectly ok. If I comment out mybit.or(1,2,3) I get

Test script
table: 005A8EB8

So I am fairly confident that the library is being loaded. My problem is that I can't understand why I can't access the or function using the dot operator.

I am using Lua 5.2 compiled with mingw-gcc.

Upvotes: 2

Views: 205

Answers (2)

ToxicFrog
ToxicFrog

Reputation: 2624

or is a reserved word in Lua (it's the logical or operator). This is why all existing bitwise operation libraries in Lua name the or-function something like bor. and and not are similarly reserved. (The complete list of reserved words can be found here.)

You can still call it by using a string:

print(mybit["or"](1,2,3))
print(mybit["or"])

But you're better off following the example of existing bitwise operation libraries and naming it something other than or.

Upvotes: 6

Yu Hao
Yu Hao

Reputation: 122493

You are using or as the function name which is a keyword in Lua, try another name, like my_or.

Upvotes: 2

Related Questions