LuaInterface:将表添加到脚本作用域 [英] LuaInterface: add a table to the script scope

查看:180
本文介绍了LuaInterface:将表添加到脚本作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:如何使用C#对象(最好是匿名类型)将C#中的表插入"LuaInterface"脚本范围?

Question: how can I insert a table from C# into 'LuaInterface' script scope using a C# object (preferably anonymous type)?

/// I want to do this, but it does not work 
/// (complains that 'test' is userdata and not table 
/// when I pass it to pairs() in the script)
//lua["test"] = new { A = 1, B = 2 };

/// another option
/// but building this string is a PITA (actual string is nested and long).
lua.DoString("test = { A = 1, B = 2 }");

// So I have to do this
lua.NewTable("test");
((LuaTable) lua["test"])["A"] = 1;
((LuaTable) lua["test"])["B"] = 2;

lua.DoString("for k,v in pairs(test) do print(k..': '..v) end");

推荐答案

我认为,如果要将匿名类型序列化为lua表,则需要用户反射.也许您可以尝试编写一个lua表序列化器.我想我会尝试将表组装为字符串,然后使用DoString将其传递给Lua

I think if you want to serialize anonymous types into lua tables you will need to user reflection. Maybe you can try to write a lua table serializer. I think I would try to assemble my tables as string and pass it to Lua with DoString

我认为字典解决方案很好,您可以使用无反射的嵌套表.我尝试了Tuples,但是它们不够通用,最终我退回到反思的想法.

I think the dictionary solution is good and you can use nested tables with without reflection. I tried Tuples, but they are not generic enough and eventually I fell back to the reflection idea.

我将创建一个扩展方法:

I would create an extension method:

public static class LuaExt
{
    public static LuaTable GetTable(this Lua lua, string tableName)
    {
        return lua[tableName] as LuaTable;
    }

    public static LuaTable CreateTable(this Lua lua, string tableName)
    {
        lua.NewTable(tableName);
        return lua.GetTable(tableName);
    }

    public static LuaTable CreateTable(this Lua lua)
    {
        lua.NewTable("my");
        return lua.GetTable("my");
    }
}

然后我可以这样写:

var lua = new Lua();
var table = lua.CreateTable("test");

table["A"] = 1;
table["B"] = 1;

table["C"] = lua.CreateTable();
((LuaTable) table["C"])["A"] = 3;

table["D"] = lua.CreateTable();
((LuaTable)table["D"])["A"] = 3;

foreach (var v in table.Keys)
{
    Console.WriteLine(v + ":" + table[v]);
}

这篇关于LuaInterface:将表添加到脚本作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆