lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On Wed, Jun 9, 2010 at 1:56 PM, Warlich, Christof <christof.warlich@thermofisher.com> wrote:

Hi,

 

being pretty new to Lua, I’m heavily using it as a configuration language for my C++ code. To make the configuration as user friendly as possible, I selected a table-driven approach for the configuration file, as it offers an easy-to-read hierarchy, e.g.:

 

function setFunction()

    print("received SET command")

end

function statusFunction()

    print("received STATUS command")

end

interface = {

    port = "/dev/ttyS0",

    baud = 9600,

    incoming = {

        SET = setFunction,

        STATUS = statusFunction

    }

}

 

So far, this works just great, even allowing global Lua-Functions to be referenced from within the table.

 

My next idea was to put the functions’ code directly into the table, making the configuration file even more readable:

 

interface = {

    port = "/dev/ttyS0",

    baud = 9600,

    incoming = {

        SET = function()

                  print("received SET command")

              end,

        STATUS = function()

                     print("received SET command")

                 end

 

    }

}

 

But while this simple example still works fine, it seems that there is no way reference another table value from the same table constructor: To give an example, I cannot print the port from my functions:

 

interface = {

    port = "/dev/ttyS0",

    baud = 9600,

    incoming = {

        SET = function()

                  print("received SET command from:")

                  print(interface["port"]) -- error!!

              end,

        STATUS = function()

                     print("received SET command")

                 end

 

    }

}

 

Is there a way to work around this problem, ideally by keeping everything within the same table constructor?

 

Thanks for any suggestions,

 

Christof

 

Do you have a different variable 'interface' defined somewhere else? What is the error you are seeing?

Because I'd have thought this would work:

C:\>lua
Lua 5.1.2  Copyright (C) 1994-2007 Lua.org, PUC-Rio
> T = { v = 1, f = function() print("Here is T.v: " .. T["v"]) end }
> T.f()
Here is T.v: 1
> T = { v = 42, f = function() print("Here is T.v: " .. T.v) end }  -- or using dot notation
> T.f()
Here is T.v: 42
>

Robby