lua-users home
lua-l archive

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



On Oct 6, 2014, at 5:50 AM, Charles Smith <cts.private.yahoo@gmail.com> wrote:

I need to take the time to develop a clearer example, but I think the point is, alt1 and alt2 also use msg_union.  That's what I mean by recursive design.  It's a classic chicken/egg issue.

On Mon, Oct 6, 2014 at 2:35 PM, Coda Highland <chighland@gmail.com> wrote:
On Mon, Oct 6, 2014 at 5:30 AM, Charles Smith
<cts.private.yahoo@gmail.com> wrote:
> Recursive design.
>
>
> msg_union = {
>   ["0"] = "alt1",
>   ["1"] = "alt2",
>   ...
> }
>

A couple of things to consider..

First, are you SURE about those table keys? [“0”] is different from [0] when indexing a table (the first indexes by a string that just happens to look like a number).

Second, you can break the recursion by understanding that your functions CAN reference msg_union before it is defined. So this will work:

function foo()
local x = msg_union[1]
x()
end

function bar()
print(“bar”)
end

msg_union = {
[0] = foo,
[1] = bar
}

foo()

The reason this works is that every reference to a global in Lua is converted into a table lookup that happens at run-time. So the compiler will re-write the first line of foo() as follows:

local x = (_G[“msg_union”])[1]

So it’s only necessary for msg_union to be valid when the functions are CALLED, not when the functions are DEFINED. This breaks your recursion cleanly. Note: Technically, the compiler actually generates slightly different code to what I showed, but I didn’t want to complicate the example. For reference, the exact code the compiler generates uses _ENV in place of _G, but in your example the two are equivalent.

—Tim