Lua Upvalues and Globals

Upvalues and Globals

When the Lua virtual machine needs an upvalue or a global, there are dedicated instructions to load the value into a register. Similarly, when an upvalue or a global needs to be written to, dedicated instructions are used.
GETGLOBAL A Bx R(A) := Gbl[Kst(Bx)]
Copies the value of the global variable whose name is given in constant number Bx into register R(A). The name constant must be a string.
SETGLOBAL A Bx Gbl[Kst(Bx)] := R(A)
Copies the value from register R(A) into the global variable whose name is given in constant number Bx. The name constant must be a string.
The GETGLOBAL and SETGLOBAL instructions are very straightforward and easy to use. The instructions require that the global variable name be a constant, indexed by instruction field Bx. R(A) is either the source or target register. The names of the global variables used by a function will be part of the constant list of the function.
>a = 40; local b = a ; function [0] definition (level 1) ; 0 upvalues, 0 params, 2 stacks .function 0 0 2 2 .local « b » ; 0 .const « a » ; 0 .const 40 ; 1 [1] loadk 0 1 ; 40 [2] setglobal 0 0 ; a [3] getglobal 0 0 ; a [4] return 0 1 ; end of function
From the example, you can see that “b” is the name of the local variable while “a” is the name of the global variable. Line [1] loads the number 40 into register 0 (functioning as a temporary register, since local b hasn’t been defined.) Line [2] assigns the value in register 0 to the global variable with name “a” (constant 0). By line [3], local b is defined and is assigned the value of global a.
GETUPVAL A B R(A) := UpValue[B]
Copies the value in upvalue number B into register R(A). Each function may have its own upvalue list. This upvalue list is internal to the virtual machine; the list of upvalue name strings in a prototype is not mandatory.
The opcode for GETUPVAL has a second purpose – it is also used in creating closures, always appearing after the CLOSURE instruction; see CLOSURE for more information.
SETUPVAL A B UpValue[B] := R(A)
Copies the value from register R(A) into the upvalue number B in the upvalue list for that function

Cours gratuitTélécharger le cours complet

Télécharger aussi :

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *