lua-users home
lua-l archive

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


Hello,

I'm here to show you how tables aren't actually Lua's only data structure. This is a side-effect of how the language works, so you might consider it a "feature misuse" instead of a data structure, but it works! and that's what matters, no?

I present you Lua's second data structure: The stack.

Usually when you make a stack you use tables, but there's a caveat: tables don't store nil! What if you could trade tables' "infinite" capacity for being able to store nil? Well, you can. With coroutines.

Lua 5.1 added `...` to the language. Given `...` is a stack, you can implement push and pop as follows: To push onto the stack, you just do `f(<value>, ...)`. To pop from the stack, you just do `f(select(2, ...))`. This is the basic idea behind my Forth VM here: https://github.com/SoniEx2/Stuff/blob/f4ede0a30fd2a15e7d72a819c5fa20366e13eed6/lua/Forth.lua

The basic idea is that `...` is the data stack, and the function calls itself recursively with the data stack.

Conclusion: By making a function like:

local function stackmanager(action, value, ...)
  if action == "push" then
    local _action, _value = coroutine.yield()
    return stackmanager(_action, _value, value, ...)
  elseif action == "pop" then
    local _action, _value = coroutine.yield((...)) -- yield only stack top
    return stackmanager(_action, _value, select(2, ...))
  end
end

You can use coroutines as a revolutionary data structure! With this, Lua doesn't have 1, but 2 data structures. (One could argue strings are also a data structure, and then you'd have 3.)
-- 
Disclaimer: these emails are public and can be accessed from <TODO: get a non-DHCP IP and put it here>. If you do not agree with this, DO NOT REPLY.