lua-users home
lua-l archive

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


On Wed, Jan 15, 2020 at 11:44 PM Dibyendu Majumdar wrote:
Mixing arrays and maps in a single data structure was a big mistake in my view!



Merging arrays with dictionaries is a step toward making Lua
both compact and powerful.
It has brought some minor problems to the language;
but IMO the step looks correct.

It seems that there is a possibility to make next step in that direction:
to merge Lua tables and Lua functions in a single data structure.

You may have noticed that there is a similarity between how we
construct an array and how we define a function:
   arr = {11; 22; 33}
   function func() local x=42; x=x*x; return x; end
In both cases, it looks like we store a sequence of elements in a container:
in the first line we store numbers, in the second line - Lua statements.
Assuming we have new basic data type "statement",
a function definition may be treated as an array constructor.
So, "func[2]" would be the statement "x=x*x"

Dictionary seems to be a right structure to store
a set of local variables defined inside a function.
For example, we could use _expression_ "func.x" to access
internal variable x which equals to nil before invocation of the function
and equals to 42^2 after invocation.
Actually, these variables would not be "local" anymore
as they could be accessed from outside of the function.

Nested statements, such as "if a then b=b+1 else print(c) end",
are similar to nested tables.
We should consider "b=b+1" as a nested function inside the outer function.
Assuming "func[5]" is the statement "if a then b=b+1 else print(c) end",
we could obtain "b=b+1" by "func[5][1]".

In other words, a function contains its statements (in form of AST)
in its "array part" (in positive integer indices)
and contains its local variables in its "dictionary part" (in fields).

A bonus:
1) A function could modify its own code on-the-fly
by writing to its own "array part".
2) By indexing an inner block "func[2][3][4]" we could obtain access to
its local variable "func[2][3][4].z" which is usually inaccessible
due to lexical scope rules.

(thanks for reading this crazy idea)