顯示具有 Lua 標籤的文章。 顯示所有文章
顯示具有 Lua 標籤的文章。 顯示所有文章

2012-11-01

Lua Callback Function

底下在 Unity3D ( MAC OSX ) 環境下實作 Lua 呼叫 C# 函數 (tellMeNum) 並且同時把 Lua 的函數 (dispResult) 告訴 C#,待 C# 回呼此函數並告知數字 12345.678。
C# 端程式碼如下 :
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
 
public class luaTest : MonoBehaviour
{
    [DllImport("lua521")]
    public static extern IntPtr luaL_newstate();
    [DllImport("lua521")]
    public static extern void luaL_openlibs(IntPtr lua_State);
    [DllImport("lua521")]
    public static extern void lua_close(IntPtr lua_State);
    [DllImport("lua521")]
    public static extern void lua_pushcclosure(IntPtr lua_State, LuaFunction func, int n);
    [DllImport("lua521")]
    public static extern void lua_setglobal(IntPtr lua_State, string s);
    [DllImport("lua521")]
    public static extern int lua_pcallk(IntPtr lua_State, int nargs, int nresults, int errfunc, int ctx, LuaFunction func);
    [DllImport("lua521")]
    public static extern int luaL_loadfilex(IntPtr lua_State, string s, string mode);
    [DllImport("lua521")]
    public static extern int luaL_loadstring(IntPtr lua_State, string s);
    [DllImport("lua521")]
    public static extern IntPtr luaL_checklstring(IntPtr lua_State, int idx, IntPtr len);
 
    [DllImport("lua521")]
    public static extern int lua_rawgeti(IntPtr lua_State, int idx0, int idx1);
    [DllImport("lua521")]
    public static extern int luaL_ref(IntPtr lua_State, int idx);
    [DllImport("lua521")]
    public static extern int luaL_unref(IntPtr lua_State, int idx0, int idx1);
    [DllImport("lua521")]
    public static extern int lua_pushnumber(IntPtr lua_State, double num);
 
    //------------------------------------
    // Lua
    //
 
    //註冊 C# Function 讓 Lua 可以呼叫執行
    public delegate int LuaFunction(IntPtr pLuaState);
    public static void lua_register(IntPtr pLuaState, string strFuncName, LuaFunction pFunc)
    {
        lua_pushcclosure(pLuaState, pFunc, 0);
        lua_setglobal(pLuaState, strFuncName);
    }
 
    //執行 Lua 檔案
    public static int luaL_dofile(IntPtr lua_State, string s)
    {
        if (luaL_loadfilex(lua_State, s, null) != 0)
            return 1;
        return lua_pcallk(lua_State, 0, -1, 0, 0, null);
    }
 
    //執行 Lua Callback Function
    public static int luaL_doCallBackFromCBIdx(IntPtr lua_State, int idx, double num)
    {
        lua_rawgeti(lua_State, -1000000 - 1000, idx);
        lua_pushnumber(lua_State, num);
        int ret = lua_pcallk(lua_State, 1, 0, 0, 0, null);
        if (ret != 0)
        {
            //Error...
        }
        luaL_unref(lua_State, -1000000 - 1000, idx);
        return ret;
    }
 
 
    //------------------------------------
    // Application
    //
    public static int nLuaCBFuncIdx = -1;
    public static IntPtr m_luaState = IntPtr.Zero;
 
    public static int tellMeNum(IntPtr pLuaState)
    {
        //取得回呼函數堆疊上的 index
        nLuaCBFuncIdx = luaL_ref(pLuaState, -1000000 - 1000);
        return 0;
    }
 
    //讓 Lua 在 unity 裡顯示 log 訊息
    public static int msg(IntPtr pLuaState)
    {
        IntPtr retPtr = luaL_checklstring(pLuaState, 1, IntPtr.Zero);
        string retStr = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(retPtr);
 
        Debug.Log(retStr);
        return 0;
    }
 
    //取得 unity 執行路徑
    public static string GetAppPath()
    {
        return Application.dataPath.Substring(0, Application.dataPath.Length - 6);
    }
 
    // Use this for initialization
    void Start()
    {
        //初始化 Lua
        m_luaState = luaL_newstate();
        luaL_openlibs(m_luaState);
 
        //註冊 C# Function
        lua_register(m_luaState, "tellMeNum", tellMeNum);
        lua_register(m_luaState, "msg", msg);
 
        //執行 Lua 檔案
        string strPath = GetAppPath() + "LuaScript/lua.txt";
        luaL_dofile(m_luaState, strPath);
    }
 
    // Update is called once per frame
    void Update()
    {
        if (nLuaCBFuncIdx != -1)
        {
            //回呼取得的 lua callback function, 並給予數字 12345.678
            luaL_doCallBackFromCBIdx(m_luaState, nLuaCBFuncIdx, 12345.678);
            nLuaCBFuncIdx = -1;
        }
    }
 
    void OnApplicationQuit()
    {
        lua_close(m_luaState);
    }
}
其中值得注意的是 luaL_doCallBackFromCBIdx 函數,其用來回呼 Lua Callback Function。

lua.txt 內容如下:
function dispResult(num)
   msg(num)
end
 
tellMeNum(dispResult)
此 lua script 呼叫 tellMeNum 並將 dispResult 以參數傳給 C#,待 C# 呼叫 dispResult,dispResult 接收到 num 之後呼叫 msg 使 num 顯示在 Unity Console。

完整範例程式可在此取得:https://github.com/phardera/unity3d_lua_callback_function.git

2012-07-12

Unity 3D + Lua + iOS 實作筆記

這篇文章概略介紹如何把 Lua 當作 Unity3D 在 iOS 平台上的腳本引擎(若要實作於 Windows 平台可以參考另一篇文章)。範例大略分成三個部分:Unity3D C# 部分、Lua C 部分及 Lua Script 部分,整個程式執行的流程是:
  1. C# 啟動 Lua,並註冊 C#  函數給 Lua (讓 Lua Script 可以呼叫)
  2. 從 iOS 載入 Lua Script 檔案並由 Lua 執行
  3. Lua Script 呼叫 C# 函數
  4. C# 函數印出訊息
最後在 Xcode 的 Output 可以看到 C# 函數印出的訊息,此外值得注意的是,Unity3D 產生的程式碼在模擬器上無法呼叫 Plugins ,所以實作的步驟需要真正的實機才能測試(因此在開始之前必須做好 iOS Developer 相關的設定),底下是整個實作的流程:

1. 開啟 Unity3D 並建立一個空的專案,在專案路徑下建立 Plugins/iOS 目錄,如下圖所示:

2. 到 http://www.lua.org/ftp/ 下載原始碼 lua-5.2.1.tar.gz。解開壓縮檔之後可以看到原始碼在 src 目錄下,將該目錄下所有檔案(除了 Makefile、lua.c、luac.c 之外)複製到 Plugins/iOS 。

3. 建立一個新的 C# Script,命名為 luaTest,此時 Unity3D 的專案目錄呈現如下:

luaTest 內容分成三大部分,一是和 Lua 介接的部分,二是和 lua 之間建立 callback 的部分,三是 Unity3D 程式的部分分別敘述如下:

一、和 Lua 介接的部分:
luaL_newstate、luaL_openlibs 和 lua_close 分別為初始化及關閉 Lua 時呼叫使用。
[DllImport ("__Internal")]
public static extern IntPtr luaL_newstate();

[DllImport ("__Internal")]
public static extern void luaL_openlibs(IntPtr lua_State);

[DllImport ("__Internal")]
public static extern void lua_close(IntPtr lua_State);

lua_pushcclosure 和 lua_setglobal 為註冊 C# 函數給 Lua 時使用。
[DllImport ("__Internal")]
public static extern void lua_pushcclosure(IntPtr lua_State, LuaFunction func, int n);

[DllImport ("__Internal")]
public static extern void lua_setglobal(IntPtr lua_State, string s);

其中 LuaFunction 定義如下:
public delegate int LuaFunction(IntPtr pLuaState);

lua_pcallk 和 luaL_loadfilex 為載入及執行 Lua Script 檔案時使用。
[DllImport ("__Internal")]
public static extern int lua_pcallk(IntPtr lua_State, int nargs, int nresults, int errfunc, int ctx, LuaFunction func);

[DllImport ("__Internal")]
public static extern int luaL_loadfilex(IntPtr lua_State, string s, string mode);

luaL_checklstring 為 C# 函數被 Lua 呼叫時,取得 Lua 所給的參數時使用。
[DllImport ("__Internal")] public static extern IntPtr luaL_checklstring(IntPtr lua_State, int idx, IntPtr len);

此外,使用 DllImport 時需要引入 System.Runtime.InteropServices 名稱空間:
using System.Runtime.InteropServices;

使用 IntPter 時需要引用 System 名稱空間:
using System;

上述 Lua API 在註冊 C# 函數及載入/執行 Lua Script 的部分可寫成 lua_register 及 luaL_dofile 分別如下:
public static void lua_register(IntPtr pLuaState, string strFuncName, LuaFunction pFunc)
{
    lua_pushcclosure(pLuaState, pFunc, 0);
    lua_setglobal(pLuaState, strFuncName);
}

public static int luaL_dofile(IntPtr lua_State, string s)
{
    if (luaL_loadfilex(lua_State, s, null) != 0)
        return 1;
 
    return lua_pcallk(lua_State, 0, -1, 0, 0, null);
}

二、和 lua 之間建立 callback 的部分
1. 建立簡單的 Lua Script ( lua.txt ) 檔案,其內容為:
TestDisplay("Hello world");

將檔案置於專案的 LuaScript 路徑底下,如圖所示:

2. 在 luaTest 內加入 callback 函數如下:
[MonoPInvokeCallbackAttribute (typeof (LuaFunction))]
public static int TestDisplay(IntPtr pLuaState)
{
    IntPtr retPtr =luaL_checklstring(pLuaState, 1, IntPtr.Zero);
    string retStr = Marshal.PtrToStringAnsi(retPtr);
  
    Debug.Log("This line was plotted by TestDisplay() : msg ="+retStr);

    return 0;
}

其中 MonoPInvokeCallbackAttribute 可以預防 mono 在傳遞函數指標時啟動 JIT 的功能(相關參考連結),其定義如下:
[System.AttributeUsage(System.AttributeTargets.Method)]
public sealed class MonoPInvokeCallbackAttribute : Attribute {
    private Type type;
    public MonoPInvokeCallbackAttribute (Type t) { type =t;}
}

luaL_checklstring 負責取得 Lua 在呼叫此函數時給的 "Hello world" 字串指標

三、Unity3D 程式的部分
1. 在 Start 函數加入程式碼:
void Start()
{
    m_luaState = luaL_newstate();
    luaL_openlibs(m_luaState);
    lua_register(m_luaState, "TestDisplay", TestDisplay);
    luaL_dofile(m_luaState, GetAppPath() + "LuaScript/lua.txt");
}

程式碼初始化 Lua 並註冊函數 TestDisplay 給 Lua,最後則是載入 lua.txt 並執行。其中 GetAppPath 函數定義如下:
public static string GetAppPath()
{
    return Application.dataPath.Substring(0, Application.dataPath.Length-4);
} 
m_luaState 定義如下:
public static IntPtr m_luaState = IntPtr.Zero;

2. 在 OnApplicationQuit 函數加入程式碼:
void OnApplicationQuit()
{
    lua_close(m_luaState); 
}

3. 將 luaTest 拖曳至 Main Camera 上,此時在 Inspector 可以看到 luaTest 成為 Camera 的 Component:

編譯時需要稍微做一些設定如下:
1. 在 Build Settings 裡 Switch Platform 至 iOS 之後按下 Build,選擇欲產生的目錄之後 Unity3D 將自動產生 Xcode 專案,開啟後觀察專案底下 Libraries 是否引入 Lua 原始碼:

2. 用滑鼠拖曳 LuaScript 目錄到 Unity-iPhone 上出現訊息如下:

記住此處選擇的是 Create folder references for any added folders。按下 Finish 之後 LuaScript 出現如圖所示:

3. 將裝置接上電腦,編譯的目標選擇 Unity-iPhone > (裝置名稱) 之後按下 Run。

4. 此時觀察 output 視窗的訊息應該顯示如下:

由訊息 "This line was plotted by TestDisplay() : msg =Hello world" 可知 Lua Script 執行成功。範例程式碼可以在 https://github.com/phardera/unity3d_lua_ios 取得。

2011-12-13

lua and 64bit integer

lua 的整數運算很不幸的,只有到 32bit 的範圍(-2,147,483,648 ~ 2,147,483,647),但透過 lnum 之 patch 之後,可支援到 64bit(-9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807)底下是 patch 之過程的記錄:

1. 到 這裡 取得 Lua 5.1.4 原始碼。
2. 到 這裡 取得 lua514-lnum-20090417.patch.tgz。
3. 執行 patch 指令 
    a. linux or mac :  
        i. 解壓解 lua 5.1.4 及 lua514-lnum-20090417.patch.tgz
        ii. 把 lua514-lnum-20090417.patch  擺在 lua 5.1.4 之 src 目錄下
        ii. 進到 lua src 檔目錄下
        iii. 執行 patch < lua514-lnum-20090417.patch
    b. windows :
        i. 到 這裡 下載 patch 執行檔
        ii. 解壓解 lua 5.1.4 及 lua514-lnum-20090417.patch.tgz
        ii. 把 lua514-lnum-20090417.patch 和 patch.exe  擺在 lua 5.1.4 之 src 目錄下
        ii. 進到 lua src 檔目錄下
        iii. 假如使用的是 win7, vista 作業系統,須把 patch.exe 改成其它名稱(例如 cc.exe)
        iv. 執行 patch < lua514-lnum.patch(或者 cc < lua514-lnum.patch)
        v. 假如顯示 Assertion failed: hunk, file ../patch-2.5.9-src/patch.c, line 354…訊息: 
            1. 執行 write lua514-lnum-20090417.path
            2. 將會跳出 wordpad 視窗,此時直接按存檔並離開
            3. 重新執行 iv 指令
4. 開啟 luaconf.h,找到下列關鍵字:

/*
@@ LNUM_DOUBLE | LNUM_FLOAT | LNUM_LDOUBLE: Generic Lua number mode
@@ LNUM_INT32 | LNUM_INT64: Integer type (optional)
@@ LNUM_COMPLEX: Define for using 'a+bi' numbers
@*
@* You can combine LNUM_xxx but only one of each group. I.e. 'LNUM_FLOAT
@* LNUM_INT32 LNUM_COMPLEX' gives float range complex numbers, with
@* 32-bit scalar integer range optimized.
*/
/*#define LNUM_DOUBLE*/

5. 在關鍵字下一行加入 #define LNUM_INT64
6. 開始編譯(可參考 這篇)

2010-12-24

從檔案載入 Lua function 至名稱空間

參考連結,可將 lua 檔案裡的程式載入到 namespace 裡,好處是可避免各個不同檔案裡出現相同 function 的問題。

稍微針對 C# 做了修改如下:

protected bool load_file_into_namespace(IntPtr L, string S, string N, bool bCall)
{
    lua_pushlstring(L, N, N.Length);
    lua_gettable(L, (-10002));
 
    if (lua_isnil(L, -1))
    {
        lua_pop(L, 1);
        lua_newtable(L);
        lua_pushlstring(L, N, N.Length);
        lua_pushvalue(L, -2);
        lua_settable(L, (-10002));
    }
    else
    {
        if (!lua_istable(L, -1))
        {
            lua_pop(L, 1);
            return (false);
        }
    }
 
    lua_newtable(L);
    lua_pushlstring(L, "_G", 2);
    lua_gettable(L, (-10002));
    lua_pushnil(L);
    while (lua_next(L, -2) != 0)
    {
        lua_pushvalue(L, -2);
        lua_pushvalue(L, -2);
        lua_settable(L, -6);
        lua_pop(L, 1);
    }
 
    if ((luaL_loadfile(L, S) > 0))
    {
        Console.Write("Error in file " + S + "!\n");
        for (int i = 0; ; i++)
            if ((lua_isstring(L, i) > 0))
            {
                Console.Write(lua_tolstring(L, i, IntPtr.Zero) + "\n");
            }
            else
                break;
        lua_error(L);
        lua_pop(L, 3);
        return (false);
    }
 
    if (bCall)
        lua_call(L, 0, 0);
    else
        lua_insert(L, -4);
 
    lua_pushnil(L);
    while (lua_next(L, -2) != 0)
    {
        lua_pushvalue(L, -2);
        lua_gettable(L, -5);
        if (lua_isnil(L, -1))
        {
            lua_pop(L, 1);
            lua_pushvalue(L, -2);
            lua_pushvalue(L, -2);
            lua_pushvalue(L, -2);
            lua_pushnil(L);
            lua_settable(L, -7);
            lua_settable(L, -7);
        }
        else
        {
            lua_pop(L, 1);
            lua_pushvalue(L, -2);
            lua_gettable(L, -4);
            if (!(lua_equal(L, -1, -2) > 0))
            {
                lua_pushvalue(L, -3);
                lua_pushvalue(L, -2);
                lua_pushvalue(L, -2);
                lua_pushvalue(L, -5);
                lua_settable(L, -8);
                lua_settable(L, -8);
            }
            lua_pop(L, 1);
        }
        lua_pushvalue(L, -2);
        lua_pushnil(L);
        lua_settable(L, -6);
        lua_pop(L, 1);
    }
 
    lua_pop(L, 3);
    return (true);
}

其中 S 表示檔案路徑, N 表示名稱空間。呼叫名稱空間內的 function 方式也會有些不同:

1) 以 luaL_dostring 方式呼叫:

假設載入的file0.lua 檔如下:
function pp()
  print("this is file0");
end

載入的 file1.lua 檔案下:
function pp()
  print("this is file1");
end

載入 file0.lua 時設定的 namespace 為 A0,載入 file1.lua 時設定的 namespace 為 A1,載入的程式碼為:
load_file_into_namespace(m_luaState, "file0.lua", "A0", true);
load_file_into_namespace(m_luaState, "file1.lua", "A1", true);

則分別呼叫 file0.lua及file1.lua內的 pp() 函數方式如下:
A0.pp();
A1.pp();

程式碼寫法是:
luaL_dostring(m_luaState, "A0.pp()");
luaL_dostring(m_luaState, "A1.pp()");

2) 以 lua_pcall 方式呼叫(以呼叫 A0.pp() 為例子)
lua_getglobal(m_luaState, "A0");
if (lua_type(m_luaState, -1) == 5)
{
    lua_getfield(m_luaState, -1, "pp");
 
    if (lua_type(m_luaState, -1) == 6)
    {
        // This removes the foo table from the stack
        lua_replace(m_luaState, -2); 
        ret = lua_pcall(m_luaState, 0, 0, 0);
 
        if (ret != 0)
        {
            lua_pop(m_luaState, 1);
        }
    }
    else
    {
        lua_pop(m_luaState, 2);
    }
 
}
else
{
    lua_pop(m_luaState, 1);
}

2010-11-05

Unity 3D + Lua 實作筆記


幾天前實作使用 Lua 當 Untiy 3D 的腳本語言,好處是只要用記事本修改 Lua Script 文字檔就可更改程式執行流程,不用重新編譯程式。這裡使用的方法是將 Lua 以 DLL Plugin 的方式掛在 Unity 3D 裡執行,底下是整個實作的流程 (  iOS 平台的實作請參考另一篇 ) :

1. 重新編譯讓 C# 可以 Import 的 Lua DLL 檔。
因為 C 和 .net 的 calling convention 方式不同以致於需要編譯一個 .net 使用的 calling convention 方式的 DLL 檔,可以參考這篇文章。

1.1 到 http://www.lua.org/ftp/ 下載 lua5.1 原始碼,此時的最新版是 lua-5.1.4.tar.gz ,解開後可以看到原始碼在 src 目錄下。

1.2 用 VC 開啟新專案 (Visual C++ 的 Win32 Console Application),Application Type 的部分選擇 DLL,Additional options 的部分選擇 Empty project。

開啟新專案

Application Settings

1.3 引入 src 目錄內的原始檔(除 Makefile、lua.c、luac.c 外)。
1.4 設定 Calling Convention 為 _stdcall(在 Project Property -> Configuration Properties -> C/C++ -> Advanced -> Calling Convention)。

Calling Convention

1.5 在 Preprocessor Definitions ( Project Property -> Configuration Properties -> C/C++ -> Preprocessor->Preprocessor Definitions)裡加入 LUA_BUILD_AS_DLL 和 LUA_CORE 兩個定義。
Preprocessor Definitions

1.6 按下 Build 即可產生一個 DLL 檔。

2 將 DLL 檔複製到 Unity3D 專案的 plugins 目錄下 ("\Assets\Plugins"),測試 Lua DLL。

2.1 測試大約區分成三個部分,第一是 "開啟和關閉 Lua" ,第二是 "註冊 C# 的函數給 Lua",第三是 "執行 Lua Script" 並在 Script 內回呼之前註冊的 C# Function。

2.2 "開啟  Lua" 執行如下:
m_luaState = luaL_newstate();
luaL_openlibs(m_luaState);

其中 m_luaState 的定義是:
protected IntPtr m_luaState = IntPtr.Zero;

luaL_newstate() 和 luaL_openlibs() 這兩個函數在執行前須 Import :
[DllImport("lua514vc")] private static extern IntPtr luaL_newstate();
[DllImport("lua514vc")] private static extern void luaL_openlibs(IntPtr lua_State);
其中 lua514vc 是編譯的 Lua 的 DLL 檔名稱。

2.3 "關閉  Lua" 執行如下:
lua_close(m_luaState);

2.4 "註冊 C# 函數",底下是 Lua 註冊 C# Function 的函數:
protected static void lua_register(IntPtr pLuaState, string strFuncName, LuaFunction pFunc)
{
    lua_pushcclosure(pLuaState, pFunc, 0);
    lua_setfield(pLuaState, (int)LuaIndexes.LUA_GLOBALSINDEX, strFuncName);
}

其中 pLuaState 是開啟 Lua 之後取得的 m_luaState,strFuncName 是欲註冊的函數名稱, pFunc 是 C# 函數, LuaFunction 是函數指標,定義如下:
public delegate int LuaFunction(IntPtr pLuaState);

函數 lua_pushcclosure() 和 lua_setfield() 的 Import 方式如下:
[DllImport("lua514vc")]
private static extern void lua_pushcclosure(
    IntPtr lua_State, 
    [MarshalAs(UnmanagedType.FunctionPtr)] LuaFunction func, 
    int n);

[DllImport("lua514vc")]
private static extern void lua_setfield(
    IntPtr lua_State, 
    int idx, 
    string s);

例如現在有一個函數為:
int TestDisplay(IntPtr pLuaState)
{
    Debug.Log("LuaWrapper.TestDisplay()");
    return 0;
}

則註冊 TestDisplay() 函數的方法就是:
lua_register(m_luaState, "TestDisplay", TestDisplay);

2.5 "執行 Lua Script" 檔案:
執行 Lua Script 檔案的函數是:
protected static int luaL_dofile(IntPtr lua_State, string s)
{
    if (luaL_loadfile(lua_State, s) != 0)
        return 1;
 
    return lua_pcall(lua_State, 0, -1, 0);
}

其中 string s 表示 Lua Script 的檔案路徑。函數 luaL_loadfile和 lua_pcall 的 Import 方式為:
[DllImport("lua514vc")]
private static extern int lua_pcall(IntPtr lua_State, int nargs, int nresults, int errfunc);

[DllImport("lua514vc")]
private static extern int luaL_loadfile(IntPtr lua_State, string s);

最後,編輯一個文字檔,儲存檔名為 test.txt,其內容為:
TestDisplay()

然後在 C# 裡執行:
luaL_dofile( m_luaState , "test.txt" );

就會看到 Untiy3D 裡的 Console 視窗出現 "LuaWrapper.TestDisplay()" 字串了。

update 2012-07-05 :
範例程式碼可以在  https://github.com/phardera/unity3d_lua 下載