Lexicals and Globals
So far, we’ve been treating Parrot registers like the variables of a high-level language. This is fine, as far as it goes, but it isn’t the full picture. The dynamic nature and introspective features of languages like Perl make it desirable to manipulate variables by name, instead of just by register or stack location. These languages also have global variables, which are visible throughout the entire program. Storing a global variable in a register would either tie up that register for the lifetime of the program or require unwieldy manipulation of the user stack.
Parrot provides structures for storing both global and lexically scoped named variables. Lexical and global variables must be PMC values. PASM provides instructions for storing and retrieving variables from these structures so the PASM opcodes can operate on their values.
Globals
Global variables are stored in a
PerlHash
, so every
variable name must be unique. PASM has two opcodes for globals,
store_global
and find_global
:
new P10, .PerlInt set P10, 42 store_global "$foo", P10 # . . . find_global P0, "$foo" print P0 # prints 42 end
The first two statements create a PerlInt
in the
PMC register P10
and give it the value 42. In the
third statement, store_global
stores that PMC as
the named global variable $foo
. At some later
point in the program, find_global
retrieves the
PMC from the global variable by name, and stores it in
P0
so it can be printed.
The store_global
opcode only stores a reference to the ...
Get Perl 6 and Parrot Essentials, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.