1 # Copyright (C) 2005-2008, The Perl Foundation.
6 lib/luabasic.pir - Lua Basic Library
10 The basic library provides some core functions to Lua.
12 See "Lua 5.1 Reference Manual", section 5.1 "Basic Functions",
13 L<http://www.lua.org/manual/5.1/manual.html#5.1>.
21 .HLL 'Lua', 'lua_group'
22 .namespace [ 'Lua::basic' ]
25 # print "init Lua Basic\n"
27 .local pmc _lua__REGISTRY
28 new _lua__REGISTRY, 'LuaTable'
29 set_hll_global '_REGISTRY', _lua__REGISTRY
31 .local pmc _lua__GLOBAL
32 new _lua__GLOBAL, 'LuaTable'
33 set_hll_global '_G', _lua__GLOBAL
38 _lua__REGISTRY[$P1] = $P0
42 A global variable (not a function) that holds the global environment (that is,
43 C<_G._G = _G>). Lua itself does not use this variable; changing its value
44 does not affect any environment, nor vice-versa. (Use C<setfenv> to change
50 _lua__GLOBAL[$P1] = _lua__GLOBAL
52 lua_register($P1, _lua__GLOBAL)
56 A global variable (not a function) that holds a string containing the current
57 interpreter version. The current contents of this variable is C<"Lua 5.1">.
62 set $P0, "Lua 5.1 (on Parrot)"
64 _lua__GLOBAL[$P1] = $P0
74 .const .Sub _lua_assert = 'assert'
75 _lua_assert.'setfenv'(_lua__GLOBAL)
77 _lua__GLOBAL[$P1] = _lua_assert
79 .const .Sub _lua_collectgarbage = 'collectgarbage'
80 _lua_collectgarbage.'setfenv'(_lua__GLOBAL)
81 set $P1, 'collectgarbage'
82 _lua__GLOBAL[$P1] = _lua_collectgarbage
84 .const .Sub _lua_dofile = 'dofile'
85 _lua_dofile.'setfenv'(_lua__GLOBAL)
87 _lua__GLOBAL[$P1] = _lua_dofile
89 .const .Sub _lua_error = 'error'
90 _lua_error.'setfenv'(_lua__GLOBAL)
92 _lua__GLOBAL[$P1] = _lua_error
94 .const .Sub _lua_getfenv = 'getfenv'
95 _lua_getfenv.'setfenv'(_lua__GLOBAL)
97 _lua__GLOBAL[$P1] = _lua_getfenv
99 .const .Sub _lua_getmetatable = 'getmetatable'
100 _lua_getmetatable.'setfenv'(_lua__GLOBAL)
101 set $P1, 'getmetatable'
102 _lua__GLOBAL[$P1] = _lua_getmetatable
104 .const .Sub _lua_ipairs = 'ipairs'
105 _lua_ipairs.'setfenv'(_lua__GLOBAL)
107 _lua__GLOBAL[$P1] = _lua_ipairs
109 .const .Sub _lua_load = 'load'
110 _lua_load.'setfenv'(_lua__GLOBAL)
112 _lua__GLOBAL[$P1] = _lua_load
114 .const .Sub _lua_loadfile = 'loadfile'
115 _lua_loadfile.'setfenv'(_lua__GLOBAL)
117 _lua__GLOBAL[$P1] = _lua_loadfile
119 .const .Sub _lua_loadstring = 'loadstring'
120 _lua_loadstring.'setfenv'(_lua__GLOBAL)
121 set $P1, 'loadstring'
122 _lua__GLOBAL[$P1] = _lua_loadstring
124 .const .Sub _lua_next = 'next'
125 _lua_next.'setfenv'(_lua__GLOBAL)
127 _lua__GLOBAL[$P1] = _lua_next
129 .const .Sub _lua_pairs = 'pairs'
130 _lua_pairs.'setfenv'(_lua__GLOBAL)
132 _lua__GLOBAL[$P1] = _lua_pairs
134 .const .Sub _lua_pcall = 'pcall'
135 _lua_pcall.'setfenv'(_lua__GLOBAL)
137 _lua__GLOBAL[$P1] = _lua_pcall
139 .const .Sub _lua_print = 'print'
140 _lua_print.'setfenv'(_lua__GLOBAL)
142 _lua__GLOBAL[$P1] = _lua_print
144 .const .Sub _lua_rawequal = 'rawequal'
145 _lua_rawequal.'setfenv'(_lua__GLOBAL)
147 _lua__GLOBAL[$P1] = _lua_rawequal
149 .const .Sub _lua_rawget = 'rawget'
150 _lua_rawget.'setfenv'(_lua__GLOBAL)
152 _lua__GLOBAL[$P1] = _lua_rawget
154 .const .Sub _lua_rawset = 'rawset'
155 _lua_rawset.'setfenv'(_lua__GLOBAL)
157 _lua__GLOBAL[$P1] = _lua_rawset
159 .const .Sub _lua_select = 'select'
160 _lua_select.'setfenv'(_lua__GLOBAL)
162 _lua__GLOBAL[$P1] = _lua_select
164 .const .Sub _lua_setfenv = 'setfenv'
165 _lua_setfenv.'setfenv'(_lua__GLOBAL)
167 _lua__GLOBAL[$P1] = _lua_setfenv
169 .const .Sub _lua_setmetatable = 'setmetatable'
170 _lua_setmetatable.'setfenv'(_lua__GLOBAL)
171 set $P1, 'setmetatable'
172 _lua__GLOBAL[$P1] = _lua_setmetatable
174 .const .Sub _lua_tonumber = 'tonumber'
175 _lua_tonumber.'setfenv'(_lua__GLOBAL)
177 _lua__GLOBAL[$P1] = _lua_tonumber
179 .const .Sub _lua_tostring = 'tostring'
180 _lua_tostring.'setfenv'(_lua__GLOBAL)
182 _lua__GLOBAL[$P1] = _lua_tostring
184 .const .Sub _lua_type = 'type'
185 _lua_type.'setfenv'(_lua__GLOBAL)
187 _lua__GLOBAL[$P1] = _lua_type
189 .const .Sub _lua_unpack = 'unpack'
190 _lua_unpack.'setfenv'(_lua__GLOBAL)
192 _lua__GLOBAL[$P1] = _lua_unpack
194 .const .Sub _lua_xpcall = 'xpcall'
195 _lua_xpcall.'setfenv'(_lua__GLOBAL)
197 _lua__GLOBAL[$P1] = _lua_xpcall
202 =item C<assert (v [, message])>
204 Issues an error when the value of its argument C<v> is false (i.e., B<nil>
205 or B<false>); otherwise, returns all its arguments. C<message> is an error
206 message; when absent, it defaults to "assertion failed!"
211 .param pmc v :optional
212 .param pmc message :optional
213 .param pmc extra :slurpy
217 $S2 = lua_optstring(2, message, "assertion failed!")
220 .return (v, message, extra :flat)
224 =item C<collectgarbage (opt [, arg])>
226 This function is a generic interface to the garbage collector. It performs
227 different functions according to its first argument, C<opt>:
233 stops the garbage collector.
237 restarts the garbage collector.
241 performs a full garbage-collection cycle.
245 returns the total memory in use by Lua (in Kbytes).
249 performs a garbage-collection step. The step C<"size"> is controlled
250 by C<arg> (larger values mean more steps) in a non-specified way.
251 If you want to control the step size you must tune experimentally the value
252 of C<arg>. Returns B<true> if the step finished a collection cycle.
256 sets C<arg>/100 as the new value for the I<pause> of the collector.
258 =item B<"setstepmul">
260 sets C<arg>/100 as the new value for the I<step multiplier> of the collector.
264 STILL INCOMPLETE (see lua_gc).
268 .sub 'collectgarbage' :anon
269 .param pmc opt :optional
270 .param pmc arg :optional
271 .param pmc extra :slurpy
273 $S1 = lua_optstring(1, opt, 'collect')
274 lua_checkoption(1, $S1, 'stop restart collect count step setpause setstepmul')
275 $I2 = lua_optint(2, arg, 0)
276 $N0 = lua_gc($S1, $I2)
277 unless $S1 == 'step' goto L1
278 new res, 'LuaBoolean'
290 =item C<dofile (filename)>
292 Opens the named file and executes its contents as a Lua chunk. When called
293 without arguments, C<dofile> executes the contents of the standard input
294 (C<stdin>). Returns all values returned by the chunk. In case of errors,
295 C<dofile> propagates the error to its caller (that is, dofile does not run in
301 .param pmc filename :optional
302 .param pmc extra :slurpy
303 $S1 = lua_optstring(1, filename, '')
304 ($P0, $S0) = lua_loadfile($S1)
312 =item C<error (message [, level])>
314 Terminates the last protected function called and returns C<message> as the
315 error message. Function C<error> never returns.
317 Usually, C<error> adds some information about the error position at the
318 beginning of the message. The C<level> argument specifies how to get the
319 error position. With level 1 (the default), the error position is where the
320 C<error> function was called. Level 2 points the error to where the function
321 that called C<error> was called; and so on. Passing a level 0 avoids the
322 addition of error position information to the message.
329 .param pmc message :optional
330 .param pmc level :optional
331 .param pmc extra :slurpy
332 $I2 = lua_optint(2, level, 1)
333 lua_checkany(1, message)
342 Returns the current environment in use by the function. C<f> can be a Lua
343 function or a number that specifies the function at that stack level: Level
344 1 is the function calling C<getfenv>. If the given function is not a Lua
345 function, or if C<f> is 0, C<getfenv> returns the global environment. The
346 default for C<f> is 1.
351 .param pmc f :optional
352 .param pmc extra :slurpy
355 .const .LuaNumber zero = '0'
359 $I0 = isa f, 'LuaClosure'
362 res = get_hll_global '_G'
365 .return lua_getfenv(f)
372 $I0 = isa f, 'LuaFunction'
374 $I0 = isa f, 'LuaClosure'
379 level = lua_optint(1, f, 1)
382 level = lua_checknumber(1, f)
384 if level >= 0 goto L5
385 lua_argerror(1, "level must be non-negative")
390 f = $P0['sub'; level]
394 lua_argerror(1, "invalid level")
397 =item C<getmetatable (object)>
399 If C<object> does not have a metatable, returns B<nil>. Otherwise, if the
400 object's metatable has a C<"__metatable"> field, returns the associated value.
401 Otherwise, returns the metatable of the given object.
405 .sub 'getmetatable' :anon
406 .param pmc obj :optional
407 .param pmc extra :slurpy
410 res = obj.'get_metatable'()
415 .const .LuaString mt = '__metatable'
416 prot = res.'rawget'(mt)
426 Returns three values: an iterator function, the table C<t>, and 0, so that
429 for i,v in ipairs(t) do ... end
431 will iterate over the pairs (C<1,t[1]>), (C<2,t[2]>), ..., up to the first
432 integer key with a nil value in the table.
434 See C<next> for the caveats of modifying the table during its traversal.
439 .param pmc t :optional
440 .param pmc i :optional
441 .param pmc extra :slurpy
442 lua_checktype(1, t, 'table')
443 unless null i goto L1
445 _G = get_hll_global '_G'
446 .const .LuaString key_ipairs = 'ipairs'
448 ipairs = _G.'rawget'(key_ipairs)
450 new zero, 'LuaNumber'
452 .return (ipairs, t, zero)
454 $P2 = lua_checknumber(2, i)
458 res = t.'rawget'($P0)
466 =item C<load (func [, chunkname])>
468 Loads a chunk using function C<func> to get its pieces. Each call to C<func>
469 must return a string that concatenates with previous results. A return of
470 B<nil> (or no value) signals the end of the chunk.
472 If there are no errors, returns the compiled chunk as a function; otherwise,
473 returns B<nil> plus the error message. The environment of the returned
474 function is the global environment.
476 C<chunkname> is used as the chunk name for error messages and debug
484 .param pmc func :optional
485 .param pmc chunkname :optional
486 .param pmc extra :slurpy
487 lua_checktype(1, func, 'function')
488 $S2 = lua_optstring(2, chunkname, '=(load)')
490 .return load_aux($P0, $S0)
493 .sub 'load_aux' :anon
507 =item C<loadfile ([filename])>
509 Similar to C<load>, but gets the chunk from file C<filename> or from the
510 standard input, if no file name is given.
514 .sub 'loadfile' :anon
515 .param pmc filename :optional
516 .param pmc extra :slurpy
517 $S1 = lua_optstring(1, filename, '')
518 ($P0, $S0) = lua_loadfile($S1)
519 .return load_aux($P0, $S0)
523 =item C<loadstring (string [, chunkname])>
525 Similar to C<load>, but gets the chunk from the given string.
527 To load and run a given string, use the idiom
529 assert(loadstring(s))()
533 .sub 'loadstring' :anon
534 .param pmc s :optional
535 .param pmc chunkname :optional
536 .param pmc extra :slurpy
537 $S1 = lua_checkstring(1, s)
538 $S2 = lua_optstring(2, chunkname, $S1)
539 ($P0, $S0) = lua_loadbuffer($S1, $S2)
540 .return load_aux($P0, $S0)
544 =item C<next (table [, index])>
546 Allows a program to traverse all fields of a table. Its first argument is a
547 table and its second argument is an index in this table. C<next> returns the
548 next index of the table and its associated value. When called
549 with B<nil> as its second argument, C<next> returns an initial index
550 and its associated value. When called with the last index, or with
551 B<nil> in an empty table, C<next> returns B<nil>. If the second argument is
552 absent, then it is interpreted as B<nil>. In particular, you can use
553 C<next(t)> to check whether a table is empty.
555 Lua has no declaration of fields. There is no difference between a field
556 not present in a table or a field with value B<nil>. Therefore, C<next> only
557 considers fields with non-B<nil> values. The order in which the indices are
558 enumerated is not specified, I<even for numeric indices>. (To traverse a table
559 in numeric order, use a numerical for or the C<ipairs> function.)
561 The behavior of C<next> is I<undefined> if, during the traversal, you assign
562 any value to a non-existent field in the table. You may however modify
563 existing fields. In particular, you may clear existing fields.
568 .param pmc table :optional
569 .param pmc idx :optional
570 .param pmc extra :slurpy
571 lua_checktype(1, table, 'table')
572 $P0 = table.'next'(idx)
582 Returns three values: the C<next> function, the table C<t>, and B<nil>, so
583 that the construction
585 for k,v in pairs(t) do ... end
587 will iterate over all key--value pairs of table C<t>.
589 See C<next> for the caveats of modifying the table during its traversal.
594 .param pmc t :optional
595 .param pmc extra :slurpy
596 lua_checktype(1, t, 'table')
598 _G = get_hll_global '_G'
599 .const .LuaString key_next = 'next'
601 next = _G.'rawget'(key_next)
604 .return (next, t, nil)
608 =item C<pcall (f, arg1, arg2, ...)>
610 Calls function C<f> with the given arguments in protected mode. This means
611 that any error inside C<f> is not propagated; instead, C<pcall> catches the
612 error and returns a status code. Its first result is the status code (a
613 boolean), which is B<true> if the call succeeds without errors. In such case,
614 C<pcall> also returns all results from the call, after this first result.
615 In case of any error, C<pcall> returns B<false> plus the error message.
620 .param pmc f :optional
621 .param pmc argv :slurpy
624 new status, 'LuaBoolean'
627 (res :slurpy) = f(argv :flat)
629 .return (status, res :flat)
638 .return (status, msg)
642 =item C<print (e1, e2, ...)>
644 Receives any number of arguments, and prints their values to C<stdout>, using
645 the C<tostring> function to convert them to strings. C<print> is not intended
646 for formatted output, but only as a quick way to show a value, typically for
647 debugging. For formatted output, use C<string.format>.
652 .param pmc argv :slurpy
663 $P0 = $P0.'tostring'()
672 =item C<rawequal (v1, v2)>
674 Checks whether C<v1> is equal to C<v2>, without invoking any metamethod.
679 .sub 'rawequal' :anon
680 .param pmc v1 :optional
681 .param pmc v2 :optional
682 .param pmc extra :slurpy
686 res = v1.'rawequal'(v2)
691 =item C<rawget (table, index)>
693 Gets the real value of C<table[index]>, without invoking any metamethod.
694 C<table> must be a table; C<index> is any value different from B<nil>.
699 .param pmc table :optional
700 .param pmc idx :optional
701 .param pmc extra :slurpy
703 lua_checktype(1, table, 'table')
705 res = table.'rawget'(idx)
710 =item C<rawset (table, index, value)>
712 Sets the real value of C<table[index]> to value, without invoking any
713 metamethod. C<table> must be a table, C<index> is any value different from
714 B<nil>, and C<value> is any Lua value.
716 This function returns C<table>.
721 .param pmc table :optional
722 .param pmc idx :optional
723 .param pmc value :optional
724 .param pmc extra :slurpy
725 lua_checktype(1, table, 'table')
727 lua_checkany(3, value)
728 table.'rawset'(idx, value)
733 =item C<select (index, ...)>
735 If C<index> is a number, returns all arguments after argument number C<index>.
736 Otherwise, C<index> must be the string C<"#">, and C<select> returns the
737 total number of extra arguments it received.
742 .param pmc idx :optional
743 .param pmc argv :slurpy
746 $I0 = isa idx, 'LuaString'
749 unless $S0 == '#' goto L1
756 i = lua_checknumber(1, idx)
768 lua_argerror(1, "index out of range")
771 new res, 'FixedPMCArray'
776 unless $I1 < $I0 goto L6
787 =item C<setfenv (f, table)>
789 Sets the environment to be used by the given function. C<f> can be a Lua
790 function or a number that specifies the function at that stack level: Level
791 1 is the function calling C<setfenv>. C<setfenv> returns the given function.
793 As a special case, when C<f> is 0 C<setfenv> changes the environment of the
794 running thread. In this case, C<setfenv> returns no values.
801 .param pmc f :optional
802 .param pmc table :optional
803 .param pmc extra :slurpy
804 .const .LuaNumber zero = '0'
805 lua_checktype(2, table, 'table')
806 unless f == zero goto L1
807 # change environment of current thread
812 $I0 = isa f, 'LuaFunction'
814 $I0 = lua_setfenv(f, table)
818 lua_error("'setfenv' cannot change environment of given object")
822 =item C<setmetatable (table, metatable)>
824 Sets the metatable for the given table. (You cannot change the metatable of
825 other types from Lua.) If metatable is B<nil>, removes the metatable of the
826 given table. If the original metatable has a C<"__metatable"> field, raises
829 This function returns C<table>.
833 .sub 'setmetatable' :anon
834 .param pmc table :optional
835 .param pmc metatable :optional
836 .param pmc extra :slurpy
837 lua_checktype(1, table, 'table')
838 if null metatable goto L1
839 $I0 = isa metatable, 'LuaNil'
841 $I0 = isa metatable, 'LuaTable'
844 lua_argerror(2, "nil or table expected")
847 meta = table.'get_metatable'()
850 .const .LuaString mt = '__metatable'
851 prot = meta.'rawget'(mt)
853 lua_error("cannot change a protected metatable")
855 table.'set_metatable'(metatable)
860 =item C<tonumber (e [, base])>
862 Tries to convert its argument to a number. If the argument is already a number
863 or a string convertible to a number, then C<tonumber> returns that number;
864 otherwise, it returns B<nil>.
866 An optional argument specifies the base to interpret the numeral. The base may
867 be any integer between 2 and 36, inclusive. In bases above 10, the letter ‘A’
868 (in either upper or lower case) represents 10, ‘B’ represents 11, and so forth,
869 with ‘Z’ representing 35. In base 10 (the default), the number may have a
870 decimal part, as well as an optional exponent part. In other bases, only
871 unsigned integers are accepted.
875 .sub 'tonumber' :anon
876 .param pmc e :optional
877 .param pmc base :optional
878 .param pmc extra :slurpy
881 $I2 = lua_optint(2, base, 10)
882 unless $I2 == 10 goto L1
886 $P0 = lua_checkstring(1, e)
887 unless 2 <= $I2 goto L2
888 unless $I2 <= 36 goto L2
891 lua_argerror(2, "base out of range")
893 res = $P0.'tobase'($I2)
898 =item C<tostring (e)>
900 Receives an argument of any type and converts it to a string in a reasonable
901 format. For complete control of how numbers are converted, use C<format>.
903 If the metatable of e has a C<"__tostring"> field, C<tostring> calls the
904 corresponding value with C<e> as argument, and uses the result of the call
909 .sub 'tostring' :anon
910 .param pmc e :optional
911 .param pmc extra :slurpy
921 Returns the type of its only argument, coded as a string. The possible results
922 of this function are C<"nil"> (a string, not the value B<nil>), C<"number">,
923 C<"string">, C<"boolean">, C<"table">, C<"function">, C<"thread">, and
929 .param pmc v :optional
930 .param pmc extra :slurpy
940 =item C<unpack (list [, i [, j]])>
942 Returns the elements from the given table. This function is equivalent to
944 return list[i], list[i+1], ..., list[j]
946 except that the above code can be written only for a fixed number of elements.
947 By default, C<i> is 1 and C<j> is the length of the list, as defined by the
953 .param pmc list :optional
954 .param pmc i :optional
955 .param pmc j :optional
956 .param pmc extra :slurpy
962 lua_checktype(1, list, 'table')
964 $I2 = lua_optint(2, i, 1)
965 e = lua_optint(3, j, $I0)
968 new res, 'FixedPMCArray'
970 new index_, 'LuaNumber'
974 unless idx < n goto L2
975 $P0 = list.'rawget'(index_)
985 =item C<xpcall (f, err)>
987 This function is similar to C<pcall>, except that you can set a new error
990 C<xpcall> calls function C<f> in protected mode, using C<err> as the error
991 handler. Any error inside C<f> is not propagated; instead, C<xpcall> catches
992 the error, calls the C<err> function with the original error object, and
993 returns a status code. Its first result is the status code (a boolean), which
994 is true if the call succeeds without errors. In this case, C<xpcall> also
995 returns all results from the call, after this first result. In case of any
996 error, C<xpcall> returns false plus the result from C<err>.
1001 .param pmc f :optional
1002 .param pmc err_ :optional
1003 .param pmc extra :slurpy
1006 new status, 'LuaBoolean'
1008 lua_checkany(2, err_)
1012 .return (status, res :flat)
1015 $I0 = isa err_, 'LuaFunction'
1017 $I0 = isa err_, 'LuaClosure'
1020 (res :slurpy) = err_()
1021 .return (status, res :flat)
1039 # vim: expandtab shiftwidth=4 ft=pir: