Lua (programming Language) - Internals

Internals

Lua programs are not interpreted directly from the textual Lua file, but are compiled into bytecode which is then run on the Lua virtual machine. The compilation process is typically transparent to the user and is performed during run-time, but it can be done offline in order to increase loading performance or reduce the memory footprint of the host environment by leaving out the compiler.

Like most CPUs, and unlike most virtual machines (which are stack-based), the Lua VM is register-based, and therefore more closely resembles an actual hardware design. The register architecture both avoids excessive copying of values and reduces the total number of instructions per function. The virtual machine of Lua 5 is one of the first register-based pure VMs to have a wide use. Perl's Parrot and Android's Dalvik are two other well-known register-based VMs.

This example is the bytecode listing of the factorial function defined above (as shown by the luac 5.1 compiler):

function (10 instructions, 40 bytes at 003D5818) 1 param, 3 slots, 0 upvalues, 1 local, 3 constants, 0 functions 1 EQ 0 0 -1 ; - 0 2 JMP 2 ; to 5 3 LOADK 1 -2 ; 1 4 RETURN 1 2 5 GETGLOBAL 1 -3 ; factorial 6 SUB 2 0 -2 ; - 1 7 CALL 1 2 2 8 MUL 1 0 1 9 RETURN 1 2 10 RETURN 0 1

Read more about this topic:  Lua (programming Language)