Luaopen functions

I found the following calls in the lua code example:

luaopen_table(L);
luaopen_io(L);
luaopen_string(L);
luaopen_math(L);

I was looking for lua header files and I found other functions with luaopen:

LUALIB_API int (luaopen_base) (lua_State *L);
LUALIB_API int (luaopen_table) (lua_State *L);
LUALIB_API int (luaopen_io) (lua_State *L);
LUALIB_API int (luaopen_os) (lua_State *L);
LUALIB_API int (luaopen_string) (lua_State *L);
LUALIB_API int (luaopen_math) (lua_State *L);
LUALIB_API int (luaopen_debug) (lua_State *L);
LUALIB_API int (luaopen_package) (lua_State *L);

Could you explain what these functions mean? For example, can tables be used if I do not call luaopen_table? I did not find any documentation about this!

+3
source share
3 answers

If you are using Lua 5.1, which is the latest version, the Reference Guide has the answer:

, C - luaL_openlibs, . , luaopen_base ( ), luaopen_package ( ), luaopen_string ( ), luaopen_table ( ), luaopen_math ( ), luaopen_io ( -), luaopen_os ( ) luaopen_debug ( debug library). lualib.h : Lua C, , lua_call.

[...]

luaopen_ * ( ) , . Lua, Lua .

, , , . .

+7

, , lua c.

lua_State *l = lua_open();
lua_pushcfunction(l,luaopen_base);
lua_call(l,0,0);
lua_pushcfunction(l,luaopen_math);
lua_call(l,0,0);
lua_pushcfunction(l,luaopen_string);
lua_call(l,0,0);
lua_pushcfunction(l,luaopen_table);
lua_call(l,0,0);
+3

, , , Lua:

Lua 5.3 luaL_requiref, luaL_openlibs. . , , , lua print .

#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>

int main( int argc, char *argv[] ) {

  lua_State *lua = luaL_newstate();
  luaL_requiref( lua, "_G", luaopen_base, 1 );
  lua_pop( lua, 1 );

  luaL_dostring( lua, "print \"Hello, lua\"" );

  lua_close( lua );

  return 0;
}

, , , . ,

luaL_requiref( lua, LUA_IOLIBNAME, luaopen_io, 1 );
lua_pop( lua, 1 );

will only load the I / O library. See also the manual .

0
source

All Articles