xlua - c#中判断LuaTable是否为纯数组

 

public static bool IsPureArray(LuaTable table)
{
    int maxIndex = 0;
    int count = 0;
    bool hasNonInteger = false;

    table.ForEach<object, object>((key, value) =>
    {
        count++;
        if (key is double d && d == Math.Floor(d) && d >= 1)
        {
            int idx = (int)d;
            if (idx > maxIndex) maxIndex = idx;
        }
        else
        {
            hasNonInteger = true;
        }
    });

    // 没有非整数key,且最大索引 == 元素个数(连续无空洞)
    return !hasNonInteger && count > 0 && maxIndex == count;
}

 

方法2

  不会出现local arr = {1, nil, 3}这样的稀疏数组(空洞表)时, 可以用该方式, 因为LuaTable.Length利用了lua的#方式获取长度,#对有空洞的表结果未定义,行为不可预测。

public static bool IsPureArray(LuaTable table)
{
    int length = table.Length;
    if (length <= 0) return false; // 排除空表和无整数索引的表

    int keyCount = 0;
    table.ForEach<object, object>((key, value) => keyCount++);
    
    return keyCount == length;
}

 

测试代码

Test10.lua.txt

local obj = 
{
    1, 
    ["a"] = "A", 
    2, 
    ["b"] = "B", 
    3, 
}
return obj

Test10.cs

public class Test10 : MonoBehaviour
{
    private LuaEnv m_LuaEnv;

    void Start()
    {
        m_LuaEnv = new LuaEnv();
        m_LuaEnv.AddLoader((ref string filePath) =>
        {
            filePath = filePath.Replace('.', '/');
            filePath = $"Assets/{filePath}.lua.txt";
            var txtAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(filePath);
            return Encoding.UTF8.GetBytes(txtAsset.text);
        });
        m_LuaEnv.Global.Set("MonoInst", this);
        var result = m_LuaEnv.DoString("return require('Test10')");
        using (var luaObj = (LuaTable)result[0])
        {
            Debug.Log($"{IsPureArray(luaObj)}");
        }
    }

    void OnDestroy()
    {
        if (null != m_LuaEnv)
        {
            m_LuaEnv.Dispose();
            m_LuaEnv = null;
        }
    }
}

 

posted @ 2026-03-29 00:01  yanghui01  阅读(2)  评论(0)    收藏  举报