3

I have a C program that uses Lua to run some scripts. I need to open the Lua libraries via C code like luaopen_socket_core(myLuaState), for some reasons I can't load the modules from the Lua code, like socket = require "luasocket".

Once understood the idea of this program now I need to load a library called struct, so I added the struct.c to my project, and when I tried to use its functions like struct.unpack the runtimer complains that there is no global variable called struct. Of course it was loaded with luaopen_struct(myLuaState) instead of struct = require "struct" which is forbidden for me.

Any suggestion about an way of having this struct variable available?

Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

3

Take a look at luaL_requiref in the auxiliary library, which mimics require called from Lua.

You probably called the open-function directly and forgot to set those variables manually, that function would do it all for you.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Why this may be helpful? Open-function `luaopen_struct` invokes `luaL_register`, so global `struct` and `package.loaded` are set correctly already. – Egor Skriptunoff Aug 15 '14 at 15:04
  • @EgorSkriptunoff: Seems you have a badly-behaved module-init function then. A module should not register itself, but let the caller register it however he wants: Just return the module-table. – Deduplicator Aug 15 '14 at 15:08
  • Yes, that's the answer, now it worked perfectly fine. Thanks. – Hola Soy Edu Feliz Navidad Aug 15 '14 at 15:23
  • @Deduplicator - Please download the source and look at `struct.c`:393 (function `LUALIB_API int luaopen_struct`). Does this function "badly-behaved"? – Egor Skriptunoff Aug 15 '14 at 16:15
  • @EgorSkriptunoff: No. Please take a hard look at line 40-44 and 393-396: For Lua 5.2 (2011) and newer it only returns the table, as it should. (Took link from the question) They needed some time to figure out how to properly do modules, especially as they changed the support-structure and that simplified things. – Deduplicator Aug 15 '14 at 16:25
  • @Deduplicator - Oops! Unexpected feature. Thanks. – Egor Skriptunoff Aug 15 '14 at 16:42