My C code consists of:
/*
** lgamelib.c
** Game Library
** See Copyright Notice in lua.h
*/
#include <stdlib.h>
#include <math.h>
#define lgamelib_c
#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
static int game_workspace (lua_State *L) {
lua_pushstring(L, "Workspace");
return 1;
}
static int game_sound (lua_State *L) {
return 1;
}
static const luaL_Reg gamelib[] = {
{"Workspace", game_workspace},
{"Sound", game_sound},
{NULL, NULL}
};
/*
** Open game library
*/
LUALIB_API int luaopen_game (lua_State *L) {
luaL_register(L, LUA_GAMELIBNAME, gamelib);
//lua_pushnumber(L, PI);
//lua_setfield(L, -2, "pi");
//lua_pushnumber(L, HUGE_VAL);
//lua_setfield(L, -2, "huge");
return 1;
}
After building the solution, for example, ‘print(game.Workspace())’ returns that ‘game’ is nil even though I’ve registered it. Any solutions? I’m completely stuck… I believe I need to include lgamelib.c somewhere but I don’t believe I need to.
In the version of Lua I’m using (LuaInterface with lua5.1.1), I have to add new libraries to the
lualibs[]array in linit.c. This array is called by theluaL_openlibsfunction, which will then call yourluaopen_gamefunction, or whichever library you are adding. I don’t know if this is the “correct” way to do add libraries, but it works for my code.Edit: After thinking about it, you don’t need to necissarily modify the linit.c file. After you create your lua state, you could manually call the library loader.