最近,在學習lua,寫了個HelloWorld,希望對大家有協助!
lua的原始碼:http://www.lua.org/,之後,將原始碼添加到工程中,我用的XCode,直接將源碼拖到項目中就ok了。
---------------------------------------------------------------------------------------------------
/*
* 匯入標頭檔,因為lua是在C編譯器下的,所以,加上extern "C"標識符,告訴編譯器用C編譯器編譯
*/
extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}
/*全域變數,用來記錄Lua庫運行時所需要的資訊,所以Lua函數庫中的函數參數都帶有這個變數*/
lua_State *lua_s;
/*
* 一些函數原型
*/
int open(lua_State* L);
int luaopen_hello( lua_State* L );
int openLuaLib();
void callLuaString(const char *luaStr );
int openLuaLib()
{
if (lua_s !=
NULL) {
lua_close(lua_s);
lua_s =
NULL;
}
lua_s = lua_open ();
if(lua_s !=NULL) {
luaL_openlibs(lua_s); //1.開啟庫
luaopen_hello(lua_s); //2.註冊
lua_gc(lua_s,LUA_GCRESTART,0);
return 1;
}
return 0;
}
/*註冊到Lua中的函數*/
extern "C"
int open(lua_State* L){
printf("------>> Hello World <<--------\n");
return 0;
}
/*要註冊的函數名稱,存的是對應函數的地址*/
struct luaL_reg lrLibs[] =
{
{ "open", open },
{ NULL, NULL } /* sentinel */
};
extern "C"
int luaopen_hello( lua_State* L )
{
/*將要註冊的函數註冊到Lua庫的表中*/
luaL_register( L,
"window", lrLibs );
return 1;
}
void callLuaString(constchar *luaStr )
{
/*1.開啟Lua庫*/
if(openLuaLib())
/*2.載入Lua指令碼語言*/
luaL_loadbuffer(lua_s, luaStr,strlen(luaStr),"string");
/*3.調用*/
int result = lua_pcall(lua_s,0,0,
0);
if (result) {
}
}
------------------------------------ 調用 -------------------------------
callLuaString("window:open(\"hello world\",\"hi\",\"\");");
這樣就會調用註冊到window索引值上的open方法了。