Search code examples
scriptinglualua-tablenested-table

lua:How to use value from table 'A', in table 'B', which nested in table 'A'


In real project, TEST_TABLE would contain much of TEST_TABLE_NESTED, each with its own testVariable and bunch of testScript. test function from testScript would be used in C++ code, and TEST_TABLE_NESTED tables would be added automatically from C++ code too.

TEST_TABLE =
{
    TEST_TABLE_NESTED =
    {
        testVariable = 5, 

        testScript =
        {
            test = function()

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

            end
        }
    }
}

EDIT : This is the actual scenario of using this script:

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
}

Idea is that exists some testVariable object (passed from C++), which data is used all over TEST_TABLE_NESTED. For me, above example looks natural for this task, but it prints nil instead of 5. So how to acces a testVariable from testScript without printing a full path like TEST_TABLE.TEST_TABLE_NESTED.testVariable?


Solution

  • I made it work by providing a gameObjectOwner instance for each GameObjectScript_N. However I don't know is it expensive solution or not.