lua:如何使用表'A'中的表'A'中的值,它嵌套在表'A'中

时间:2014-08-13 11:37:28

标签: scripting lua lua-table nested-table

在实际项目中,TEST_TABLE将包含大部分TEST_TABLE_NESTED,每个testVariable都有自己的testScript和一堆test。来自testScript的{​​{1}}函数将在C ++代码中使用,TEST_TABLE_NESTED表也将自动从C ++代码中添加。

TEST_TABLE =
{
    TEST_TABLE_NESTED =
    {
        testVariable = 5, 

        testScript =
        {
            test = function()

                print(testVariable, "hello") --How to access 'testVariable'?

            end
        }
    }
}

编辑: 这是使用此脚本的实际场景:

GameObjectScriptTables =
{
    GameObject_1 = --Container of scripts corresponding to some gameObject
    {
        gameObjectOwner = actual_object_passed_from_c++, --This is an actual object passed from c++

        GameObjectScript_1 = --This is a script with update(dt) method which will be called somwhere in c++ code
        {
            update = function(dt)

                --here I want to use some data from gameObjectOwner like position or velocity

            end
        }
    }

    GameObject_2 =
    {
        gameObjectOwner = actual_object_passed_from_c++,

        GameObjectScript_1 =
        {
            update = function(dt)

                --here I want to use some data from gameObjectOwner like position or velocity

            end
        },

        GameObjectScript_2 =
        {
            update = function(dt)

                --here I want to use some data from gameObjectOwner like position or velocity

            end
        }
    }

    --And so on
}

想法是存在一些testVariable对象(从C ++传递),这些数据遍布TEST_TABLE_NESTED。对我来说,上面的示例对于此任务看起来很自然,但它会打印nil而不是5。那么如何在不打印像testVariable这样的完整路径的情况下从testScript访问TEST_TABLE.TEST_TABLE_NESTED.testVariable

2 个答案:

答案 0 :(得分:3)

你要求像父母那样的东西"指针,它告诉表B关于表A,但这不存在。在内部,他们唯一的关联是A的一个值恰好是B,但是任意数量的表都可以包含B作为值。哪位是B的父母?

如果你想让B了解A,你需要告诉它。您可以向接收游戏所有者对象的update添加额外参数,或者update可以是包含游戏所有者作为绑定变量的闭包,依此类推。

答案 1 :(得分:-1)

我通过为每个gameObjectOwner提供GameObjectScript_N个实例来实现它。但是我不知道它是否是昂贵的解决方案。