2011-10-26 53 views
3

我的C代碼包括:註冊一個Lua類用C

/* 
** 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; 
} 

構建解決方案,例如後,「打印(game.Workspace())」返回「遊戲」是零,即使我已經註冊了。任何解決方案我完全被卡住了......我相信我需要在某個地方包含lgamelib.c,但我不相信我需要。

+4

你沒有表現出 「LUA_GAMELIBNAME」 的定義。你是否認爲這是「遊戲」,因爲它應該是?另外,你真的叫'luaopen_game'? –

回答

1

在我使用的Lua版本(LuaInterface with lua5.1.1)中,我必須將新庫添加到linit.c中的lualibs[]數組中。該數組由luaL_openlibs函數調用,該函數將調用您的luaopen_game函數或您要添加的任何庫。我不知道這是否是「添加庫」的「正確」方式,但它適用於我的代碼。

編輯:思考完後,你不需要修改linit.c文件。創建你的lua狀態後,你可以手動調用庫加載器。

lua_State *L = lua_open(); 
lua_pushcfunction(L, luaopen_game); 
lua_pushstring(L, "game"); 
lua_call(L, 1, 0);