lua-users home
lua-l archive

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



> On May 22, 2020, at 12:06 PM, Joseph C. Sible <josephcsible@gmail.com> wrote:
> 
> A lot of emphasis is placed on the fact that Lua bytecode runs on a
> register-based VM, rather than on a stack-based VM, and that this is
> significant for performance reasons. Why is the Lua C API then
> stack-based instead of also being register-based for the same reason?
> 
> Joseph C. Sible

Only Roberti can comment of the rationale used in the design of course. But from my perspective it comes down to compile-time vs runtime. The Lua compiler can assign stack “slots” (aka registers) efficiently, and it has been shown that such models (especially with tertiary opcodes) are generally more efficient than pure stack machines (dont ask me to quote sources, its been years since I looked at this).

But for C code, a stack model is more flexible since you dont have to do as much work juggling register assignments. Yes, the stack can be a grind to handle, but a pure register model can be much harder. And in fact the C API is something of a hybrid, in many cases allowing arguments at arbitrary slots, thus reducing the amount of stack shuffling compared to a pure stack model.

I confess it it were me I would have opted for a stack slot model, and APIs what used stack slots consistently (source1, source2, destination), with a special slot value to mean “push/pop from TOS”. However, I think such a design would probably be slower, and Lua is all about a fast VM.

—Tim