Previous 199869 Revisions Next

r34374 Tuesday 13th January, 2015 at 16:59:12 UTC by Miodrag Milanović
Update to Lua 5.3
[3rdparty/lua]Makefile README
[3rdparty/lua/doc]contents.html lua.1 lua.css manual.html readme.html
[3rdparty/lua/src]Makefile lapi.c lapi.h lauxlib.c lauxlib.h lbaselib.c lbitlib.c lcode.c lcode.h lcorolib.c lctype.c lctype.h ldblib.c ldebug.c ldebug.h ldo.c ldo.h ldump.c lfunc.c lfunc.h lgc.c lgc.h linit.c liolib.c llex.c llex.h llimits.h lmathlib.c lmem.c lmem.h loadlib.c lobject.c lobject.h lopcodes.c lopcodes.h loslib.c lparser.c lparser.h lprefix.h* lstate.c lstate.h lstring.c lstring.h lstrlib.c ltable.c ltable.h ltablib.c ltm.c ltm.h lua.c lua.h luac.c luaconf.h lualib.h lundump.c lundump.h lutf8lib.c* lvm.c lvm.h lzio.c lzio.h

trunk/3rdparty/lua/Makefile
r242885r242886
3636# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
3737
3838# Convenience platforms targets.
39PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris
39PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
4040
4141# What to install.
4242TO_BIN= lua luac
r242885r242886
4545TO_MAN= lua.1 luac.1
4646
4747# Lua version and release.
48V= 5.2
49R= $V.3
48V= 5.3
49R= $V.0
5050
5151# Targets start here.
5252all:   $(PLAT)
trunk/3rdparty/lua/README
r242885r242886
11
2This is Lua 5.2.3, released on 11 Nov 2013.
2This is Lua 5.3.0, released on 06 Jan 2015.
33
44For installation instructions, license details, and
55further information about Lua, see doc/readme.html.
trunk/3rdparty/lua/doc/contents.html
r242885r242886
11<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
22<HTML>
33<HEAD>
4<TITLE>Lua 5.2 Reference Manual - contents</TITLE>
4<TITLE>Lua 5.3 Reference Manual - contents</TITLE>
55<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
66<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
77<STYLE TYPE="text/css">
r242885r242886
1717<HR>
1818<H1>
1919<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="" BORDER=0></A>
20Lua 5.2 Reference Manual
20Lua 5.3 Reference Manual
2121</H1>
2222
2323<P>
r242885r242886
3333<A HREF="#index">index</A>
3434<HR>
3535<SMALL>
36Copyright &copy; 2011&ndash;2013 Lua.org, PUC-Rio.
36Copyright &copy; 2015 Lua.org, PUC-Rio.
3737Freely available under the terms of the
3838<A HREF="http://www.lua.org/license.html">Lua license</A>.
3939</SMALL>
r242885r242886
7373<LI><A HREF="manual.html#3.4">3.4 &ndash; Expressions</A>
7474<UL>
7575<LI><A HREF="manual.html#3.4.1">3.4.1 &ndash; Arithmetic Operators</A>
76<LI><A HREF="manual.html#3.4.2">3.4.2 &ndash; Coercion</A>
77<LI><A HREF="manual.html#3.4.3">3.4.3 &ndash; Relational Operators</A>
78<LI><A HREF="manual.html#3.4.4">3.4.4 &ndash; Logical Operators</A>
79<LI><A HREF="manual.html#3.4.5">3.4.5 &ndash; Concatenation</A>
80<LI><A HREF="manual.html#3.4.6">3.4.6 &ndash; The Length Operator</A>
81<LI><A HREF="manual.html#3.4.7">3.4.7 &ndash; Precedence</A>
82<LI><A HREF="manual.html#3.4.8">3.4.8 &ndash; Table Constructors</A>
83<LI><A HREF="manual.html#3.4.9">3.4.9 &ndash; Function Calls</A>
84<LI><A HREF="manual.html#3.4.10">3.4.10 &ndash; Function Definitions</A>
76<LI><A HREF="manual.html#3.4.2">3.4.2 &ndash; Bitwise Operators</A>
77<LI><A HREF="manual.html#3.4.3">3.4.3 &ndash; Coercions and Conversions</A>
78<LI><A HREF="manual.html#3.4.4">3.4.4 &ndash; Relational Operators</A>
79<LI><A HREF="manual.html#3.4.5">3.4.5 &ndash; Logical Operators</A>
80<LI><A HREF="manual.html#3.4.6">3.4.6 &ndash; Concatenation</A>
81<LI><A HREF="manual.html#3.4.7">3.4.7 &ndash; The Length Operator</A>
82<LI><A HREF="manual.html#3.4.8">3.4.8 &ndash; Precedence</A>
83<LI><A HREF="manual.html#3.4.9">3.4.9 &ndash; Table Constructors</A>
84<LI><A HREF="manual.html#3.4.10">3.4.10 &ndash; Function Calls</A>
85<LI><A HREF="manual.html#3.4.11">3.4.11 &ndash; Function Definitions</A>
8586</UL>
8687<LI><A HREF="manual.html#3.5">3.5 &ndash; Visibility Rules</A>
8788</UL>
r242885r242886
112113<LI><A HREF="manual.html#6.4">6.4 &ndash; String Manipulation</A>
113114<UL>
114115<LI><A HREF="manual.html#6.4.1">6.4.1 &ndash; Patterns</A>
116<LI><A HREF="manual.html#6.4.2">6.4.2 &ndash; Format Strings for Pack and Unpack</A>
115117</UL>
116<LI><A HREF="manual.html#6.5">6.5 &ndash; Table Manipulation</A>
117<LI><A HREF="manual.html#6.6">6.6 &ndash; Mathematical Functions</A>
118<LI><A HREF="manual.html#6.7">6.7 &ndash; Bitwise Operations</A>
118<LI><A HREF="manual.html#6.5">6.5 &ndash; UTF-8 Support</A>
119<LI><A HREF="manual.html#6.6">6.6 &ndash; Table Manipulation</A>
120<LI><A HREF="manual.html#6.7">6.7 &ndash; Mathematical Functions</A>
119121<LI><A HREF="manual.html#6.8">6.8 &ndash; Input and Output Facilities</A>
120122<LI><A HREF="manual.html#6.9">6.9 &ndash; Operating System Facilities</A>
121123<LI><A HREF="manual.html#6.10">6.10 &ndash; The Debug Library</A>
r242885r242886
139141<TD>
140142<H3><A NAME="functions">Lua functions</A></H3>
141143<P>
144<A HREF="manual.html#6.1">basic</A><BR>
142145<A HREF="manual.html#pdf-_G">_G</A><BR>
143146<A HREF="manual.html#pdf-_VERSION">_VERSION</A><BR>
144147
145<P>
146148<A HREF="manual.html#pdf-assert">assert</A><BR>
147149<A HREF="manual.html#pdf-collectgarbage">collectgarbage</A><BR>
148150<A HREF="manual.html#pdf-dofile">dofile</A><BR>
r242885r242886
168170<A HREF="manual.html#pdf-xpcall">xpcall</A><BR>
169171
170172<P>
171<A HREF="manual.html#pdf-bit32.arshift">bit32.arshift</A><BR>
172<A HREF="manual.html#pdf-bit32.band">bit32.band</A><BR>
173<A HREF="manual.html#pdf-bit32.bnot">bit32.bnot</A><BR>
174<A HREF="manual.html#pdf-bit32.bor">bit32.bor</A><BR>
175<A HREF="manual.html#pdf-bit32.btest">bit32.btest</A><BR>
176<A HREF="manual.html#pdf-bit32.bxor">bit32.bxor</A><BR>
177<A HREF="manual.html#pdf-bit32.extract">bit32.extract</A><BR>
178<A HREF="manual.html#pdf-bit32.lrotate">bit32.lrotate</A><BR>
179<A HREF="manual.html#pdf-bit32.lshift">bit32.lshift</A><BR>
180<A HREF="manual.html#pdf-bit32.replace">bit32.replace</A><BR>
181<A HREF="manual.html#pdf-bit32.rrotate">bit32.rrotate</A><BR>
182<A HREF="manual.html#pdf-bit32.rshift">bit32.rshift</A><BR>
183
184<P>
173<A HREF="manual.html#6.2">coroutine</A><BR>
185174<A HREF="manual.html#pdf-coroutine.create">coroutine.create</A><BR>
175<A HREF="manual.html#pdf-coroutine.isyieldable">coroutine.isyieldable</A><BR>
186176<A HREF="manual.html#pdf-coroutine.resume">coroutine.resume</A><BR>
187177<A HREF="manual.html#pdf-coroutine.running">coroutine.running</A><BR>
188178<A HREF="manual.html#pdf-coroutine.status">coroutine.status</A><BR>
r242885r242886
190180<A HREF="manual.html#pdf-coroutine.yield">coroutine.yield</A><BR>
191181
192182<P>
183<A HREF="manual.html#6.10">debug</A><BR>
193184<A HREF="manual.html#pdf-debug.debug">debug.debug</A><BR>
194<A HREF="manual.html#pdf-debug.getuservalue">debug.getuservalue</A><BR>
195185<A HREF="manual.html#pdf-debug.gethook">debug.gethook</A><BR>
196186<A HREF="manual.html#pdf-debug.getinfo">debug.getinfo</A><BR>
197187<A HREF="manual.html#pdf-debug.getlocal">debug.getlocal</A><BR>
198188<A HREF="manual.html#pdf-debug.getmetatable">debug.getmetatable</A><BR>
199189<A HREF="manual.html#pdf-debug.getregistry">debug.getregistry</A><BR>
200190<A HREF="manual.html#pdf-debug.getupvalue">debug.getupvalue</A><BR>
201<A HREF="manual.html#pdf-debug.setuservalue">debug.setuservalue</A><BR>
191<A HREF="manual.html#pdf-debug.getuservalue">debug.getuservalue</A><BR>
202192<A HREF="manual.html#pdf-debug.sethook">debug.sethook</A><BR>
203193<A HREF="manual.html#pdf-debug.setlocal">debug.setlocal</A><BR>
204194<A HREF="manual.html#pdf-debug.setmetatable">debug.setmetatable</A><BR>
205195<A HREF="manual.html#pdf-debug.setupvalue">debug.setupvalue</A><BR>
196<A HREF="manual.html#pdf-debug.setuservalue">debug.setuservalue</A><BR>
206197<A HREF="manual.html#pdf-debug.traceback">debug.traceback</A><BR>
207198<A HREF="manual.html#pdf-debug.upvalueid">debug.upvalueid</A><BR>
208199<A HREF="manual.html#pdf-debug.upvaluejoin">debug.upvaluejoin</A><BR>
209200
210201<P>
211<A HREF="manual.html#pdf-file:close">file:close</A><BR>
212<A HREF="manual.html#pdf-file:flush">file:flush</A><BR>
213<A HREF="manual.html#pdf-file:lines">file:lines</A><BR>
214<A HREF="manual.html#pdf-file:read">file:read</A><BR>
215<A HREF="manual.html#pdf-file:seek">file:seek</A><BR>
216<A HREF="manual.html#pdf-file:setvbuf">file:setvbuf</A><BR>
217<A HREF="manual.html#pdf-file:write">file:write</A><BR>
218
219<P>
202<A HREF="manual.html#6.8">io</A><BR>
220203<A HREF="manual.html#pdf-io.close">io.close</A><BR>
221204<A HREF="manual.html#pdf-io.flush">io.flush</A><BR>
222205<A HREF="manual.html#pdf-io.input">io.input</A><BR>
r242885r242886
232215<A HREF="manual.html#pdf-io.type">io.type</A><BR>
233216<A HREF="manual.html#pdf-io.write">io.write</A><BR>
234217
218<A HREF="manual.html#pdf-file:close">file:close</A><BR>
219<A HREF="manual.html#pdf-file:flush">file:flush</A><BR>
220<A HREF="manual.html#pdf-file:lines">file:lines</A><BR>
221<A HREF="manual.html#pdf-file:read">file:read</A><BR>
222<A HREF="manual.html#pdf-file:seek">file:seek</A><BR>
223<A HREF="manual.html#pdf-file:setvbuf">file:setvbuf</A><BR>
224<A HREF="manual.html#pdf-file:write">file:write</A><BR>
225
235226</TD>
236227<TD>
237228<H3>&nbsp;</H3>
238229<P>
230<A HREF="manual.html#6.7">math</A><BR>
239231<A HREF="manual.html#pdf-math.abs">math.abs</A><BR>
240232<A HREF="manual.html#pdf-math.acos">math.acos</A><BR>
241233<A HREF="manual.html#pdf-math.asin">math.asin</A><BR>
242234<A HREF="manual.html#pdf-math.atan">math.atan</A><BR>
243<A HREF="manual.html#pdf-math.atan2">math.atan2</A><BR>
244235<A HREF="manual.html#pdf-math.ceil">math.ceil</A><BR>
245236<A HREF="manual.html#pdf-math.cos">math.cos</A><BR>
246<A HREF="manual.html#pdf-math.cosh">math.cosh</A><BR>
247237<A HREF="manual.html#pdf-math.deg">math.deg</A><BR>
248238<A HREF="manual.html#pdf-math.exp">math.exp</A><BR>
249239<A HREF="manual.html#pdf-math.floor">math.floor</A><BR>
250240<A HREF="manual.html#pdf-math.fmod">math.fmod</A><BR>
251<A HREF="manual.html#pdf-math.frexp">math.frexp</A><BR>
252241<A HREF="manual.html#pdf-math.huge">math.huge</A><BR>
253<A HREF="manual.html#pdf-math.ldexp">math.ldexp</A><BR>
254242<A HREF="manual.html#pdf-math.log">math.log</A><BR>
255243<A HREF="manual.html#pdf-math.max">math.max</A><BR>
244<A HREF="manual.html#pdf-math.maxinteger">math.maxinteger</A><BR>
256245<A HREF="manual.html#pdf-math.min">math.min</A><BR>
246<A HREF="manual.html#pdf-math.mininteger">math.mininteger</A><BR>
257247<A HREF="manual.html#pdf-math.modf">math.modf</A><BR>
258248<A HREF="manual.html#pdf-math.pi">math.pi</A><BR>
259<A HREF="manual.html#pdf-math.pow">math.pow</A><BR>
260249<A HREF="manual.html#pdf-math.rad">math.rad</A><BR>
261250<A HREF="manual.html#pdf-math.random">math.random</A><BR>
262251<A HREF="manual.html#pdf-math.randomseed">math.randomseed</A><BR>
263252<A HREF="manual.html#pdf-math.sin">math.sin</A><BR>
264<A HREF="manual.html#pdf-math.sinh">math.sinh</A><BR>
265253<A HREF="manual.html#pdf-math.sqrt">math.sqrt</A><BR>
266254<A HREF="manual.html#pdf-math.tan">math.tan</A><BR>
267<A HREF="manual.html#pdf-math.tanh">math.tanh</A><BR>
255<A HREF="manual.html#pdf-math.tointeger">math.tointeger</A><BR>
256<A HREF="manual.html#pdf-math.type">math.type</A><BR>
257<A HREF="manual.html#pdf-math.ult">math.ult</A><BR>
268258
269259<P>
260<A HREF="manual.html#6.9">os</A><BR>
270261<A HREF="manual.html#pdf-os.clock">os.clock</A><BR>
271262<A HREF="manual.html#pdf-os.date">os.date</A><BR>
272263<A HREF="manual.html#pdf-os.difftime">os.difftime</A><BR>
r242885r242886
280271<A HREF="manual.html#pdf-os.tmpname">os.tmpname</A><BR>
281272
282273<P>
274<A HREF="manual.html#6.3">package</A><BR>
283275<A HREF="manual.html#pdf-package.config">package.config</A><BR>
284276<A HREF="manual.html#pdf-package.cpath">package.cpath</A><BR>
285277<A HREF="manual.html#pdf-package.loaded">package.loaded</A><BR>
r242885r242886
290282<A HREF="manual.html#pdf-package.searchpath">package.searchpath</A><BR>
291283
292284<P>
285<A HREF="manual.html#6.4">string</A><BR>
293286<A HREF="manual.html#pdf-string.byte">string.byte</A><BR>
294287<A HREF="manual.html#pdf-string.char">string.char</A><BR>
295288<A HREF="manual.html#pdf-string.dump">string.dump</A><BR>
r242885r242886
300293<A HREF="manual.html#pdf-string.len">string.len</A><BR>
301294<A HREF="manual.html#pdf-string.lower">string.lower</A><BR>
302295<A HREF="manual.html#pdf-string.match">string.match</A><BR>
296<A HREF="manual.html#pdf-string.pack">string.pack</A><BR>
297<A HREF="manual.html#pdf-string.packsize">string.packsize</A><BR>
303298<A HREF="manual.html#pdf-string.rep">string.rep</A><BR>
304299<A HREF="manual.html#pdf-string.reverse">string.reverse</A><BR>
305300<A HREF="manual.html#pdf-string.sub">string.sub</A><BR>
301<A HREF="manual.html#pdf-string.unpack">string.unpack</A><BR>
306302<A HREF="manual.html#pdf-string.upper">string.upper</A><BR>
307303
308304<P>
305<A HREF="manual.html#6.6">table</A><BR>
309306<A HREF="manual.html#pdf-table.concat">table.concat</A><BR>
310307<A HREF="manual.html#pdf-table.insert">table.insert</A><BR>
308<A HREF="manual.html#pdf-table.move">table.move</A><BR>
311309<A HREF="manual.html#pdf-table.pack">table.pack</A><BR>
312310<A HREF="manual.html#pdf-table.remove">table.remove</A><BR>
313311<A HREF="manual.html#pdf-table.sort">table.sort</A><BR>
314312<A HREF="manual.html#pdf-table.unpack">table.unpack</A><BR>
315313
314<P>
315<A HREF="manual.html#6.5">utf8</A><BR>
316<A HREF="manual.html#pdf-utf8.char">utf8.char</A><BR>
317<A HREF="manual.html#pdf-utf8.charpattern">utf8.charpattern</A><BR>
318<A HREF="manual.html#pdf-utf8.codepoint">utf8.codepoint</A><BR>
319<A HREF="manual.html#pdf-utf8.codes">utf8.codes</A><BR>
320<A HREF="manual.html#pdf-utf8.len">utf8.len</A><BR>
321<A HREF="manual.html#pdf-utf8.offset">utf8.offset</A><BR>
322
323<H3><A NAME="env">environment<BR>variables</A></H3>
324<A HREF="manual.html#pdf-LUA_CPATH">LUA_CPATH</A><BR>
325<A HREF="manual.html#pdf-LUA_CPATH_5_3">LUA_CPATH_5_3</A><BR>
326<A HREF="manual.html#pdf-LUA_INIT">LUA_INIT</A><BR>
327<A HREF="manual.html#pdf-LUA_INIT_5_3">LUA_INIT_5_3</A><BR>
328<A HREF="manual.html#pdf-LUA_PATH">LUA_PATH</A><BR>
329<A HREF="manual.html#pdf-LUA_PATH_5_3">LUA_PATH_5_3</A><BR>
330
316331</TD>
317332<TD>
318<H3>C API</H3>
333<H3><A NAME="api">C API</A></H3>
319334<P>
320335<A HREF="manual.html#lua_Alloc">lua_Alloc</A><BR>
321336<A HREF="manual.html#lua_CFunction">lua_CFunction</A><BR>
322337<A HREF="manual.html#lua_Debug">lua_Debug</A><BR>
323338<A HREF="manual.html#lua_Hook">lua_Hook</A><BR>
324339<A HREF="manual.html#lua_Integer">lua_Integer</A><BR>
340<A HREF="manual.html#lua_KContext">lua_KContext</A><BR>
341<A HREF="manual.html#lua_KFunction">lua_KFunction</A><BR>
325342<A HREF="manual.html#lua_Number">lua_Number</A><BR>
326343<A HREF="manual.html#lua_Reader">lua_Reader</A><BR>
327344<A HREF="manual.html#lua_State">lua_State</A><BR>
r242885r242886
344361<A HREF="manual.html#lua_error">lua_error</A><BR>
345362<A HREF="manual.html#lua_gc">lua_gc</A><BR>
346363<A HREF="manual.html#lua_getallocf">lua_getallocf</A><BR>
347<A HREF="manual.html#lua_getctx">lua_getctx</A><BR>
364<A HREF="manual.html#lua_getextraspace">lua_getextraspace</A><BR>
348365<A HREF="manual.html#lua_getfield">lua_getfield</A><BR>
349366<A HREF="manual.html#lua_getglobal">lua_getglobal</A><BR>
350367<A HREF="manual.html#lua_gethook">lua_gethook</A><BR>
351368<A HREF="manual.html#lua_gethookcount">lua_gethookcount</A><BR>
352369<A HREF="manual.html#lua_gethookmask">lua_gethookmask</A><BR>
370<A HREF="manual.html#lua_geti">lua_geti</A><BR>
353371<A HREF="manual.html#lua_getinfo">lua_getinfo</A><BR>
354372<A HREF="manual.html#lua_getlocal">lua_getlocal</A><BR>
355373<A HREF="manual.html#lua_getmetatable">lua_getmetatable</A><BR>
r242885r242886
362380<A HREF="manual.html#lua_isboolean">lua_isboolean</A><BR>
363381<A HREF="manual.html#lua_iscfunction">lua_iscfunction</A><BR>
364382<A HREF="manual.html#lua_isfunction">lua_isfunction</A><BR>
383<A HREF="manual.html#lua_isinteger">lua_isinteger</A><BR>
365384<A HREF="manual.html#lua_islightuserdata">lua_islightuserdata</A><BR>
366385<A HREF="manual.html#lua_isnil">lua_isnil</A><BR>
367386<A HREF="manual.html#lua_isnone">lua_isnone</A><BR>
r242885r242886
371390<A HREF="manual.html#lua_istable">lua_istable</A><BR>
372391<A HREF="manual.html#lua_isthread">lua_isthread</A><BR>
373392<A HREF="manual.html#lua_isuserdata">lua_isuserdata</A><BR>
393<A HREF="manual.html#lua_isyieldable">lua_isyieldable</A><BR>
374394<A HREF="manual.html#lua_len">lua_len</A><BR>
375395<A HREF="manual.html#lua_load">lua_load</A><BR>
376396<A HREF="manual.html#lua_newstate">lua_newstate</A><BR>
r242885r242886
378398<A HREF="manual.html#lua_newthread">lua_newthread</A><BR>
379399<A HREF="manual.html#lua_newuserdata">lua_newuserdata</A><BR>
380400<A HREF="manual.html#lua_next">lua_next</A><BR>
401<A HREF="manual.html#lua_numbertointeger">lua_numbertointeger</A><BR>
381402<A HREF="manual.html#lua_pcall">lua_pcall</A><BR>
382403<A HREF="manual.html#lua_pcallk">lua_pcallk</A><BR>
383404<A HREF="manual.html#lua_pop">lua_pop</A><BR>
r242885r242886
394415<A HREF="manual.html#lua_pushnumber">lua_pushnumber</A><BR>
395416<A HREF="manual.html#lua_pushstring">lua_pushstring</A><BR>
396417<A HREF="manual.html#lua_pushthread">lua_pushthread</A><BR>
397<A HREF="manual.html#lua_pushunsigned">lua_pushunsigned</A><BR>
398418<A HREF="manual.html#lua_pushvalue">lua_pushvalue</A><BR>
399419<A HREF="manual.html#lua_pushvfstring">lua_pushvfstring</A><BR>
400420<A HREF="manual.html#lua_rawequal">lua_rawequal</A><BR>
r242885r242886
409429<A HREF="manual.html#lua_remove">lua_remove</A><BR>
410430<A HREF="manual.html#lua_replace">lua_replace</A><BR>
411431<A HREF="manual.html#lua_resume">lua_resume</A><BR>
432<A HREF="manual.html#lua_rotate">lua_rotate</A><BR>
412433<A HREF="manual.html#lua_setallocf">lua_setallocf</A><BR>
413434<A HREF="manual.html#lua_setfield">lua_setfield</A><BR>
414435<A HREF="manual.html#lua_setglobal">lua_setglobal</A><BR>
415436<A HREF="manual.html#lua_sethook">lua_sethook</A><BR>
437<A HREF="manual.html#lua_seti">lua_seti</A><BR>
416438<A HREF="manual.html#lua_setlocal">lua_setlocal</A><BR>
417439<A HREF="manual.html#lua_setmetatable">lua_setmetatable</A><BR>
418440<A HREF="manual.html#lua_settable">lua_settable</A><BR>
r242885r242886
420442<A HREF="manual.html#lua_setupvalue">lua_setupvalue</A><BR>
421443<A HREF="manual.html#lua_setuservalue">lua_setuservalue</A><BR>
422444<A HREF="manual.html#lua_status">lua_status</A><BR>
445<A HREF="manual.html#lua_stringtonumber">lua_stringtonumber</A><BR>
423446<A HREF="manual.html#lua_toboolean">lua_toboolean</A><BR>
424447<A HREF="manual.html#lua_tocfunction">lua_tocfunction</A><BR>
425448<A HREF="manual.html#lua_tointeger">lua_tointeger</A><BR>
r242885r242886
430453<A HREF="manual.html#lua_topointer">lua_topointer</A><BR>
431454<A HREF="manual.html#lua_tostring">lua_tostring</A><BR>
432455<A HREF="manual.html#lua_tothread">lua_tothread</A><BR>
433<A HREF="manual.html#lua_tounsigned">lua_tounsigned</A><BR>
434<A HREF="manual.html#lua_tounsignedx">lua_tounsignedx</A><BR>
435456<A HREF="manual.html#lua_touserdata">lua_touserdata</A><BR>
436457<A HREF="manual.html#lua_type">lua_type</A><BR>
437458<A HREF="manual.html#lua_typename">lua_typename</A><BR>
r242885r242886
445466
446467</TD>
447468<TD>
448<H3>auxiliary library</H3>
469<H3><A NAME="auxlib">auxiliary library</A></H3>
449470<P>
450471<A HREF="manual.html#luaL_Buffer">luaL_Buffer</A><BR>
451472<A HREF="manual.html#luaL_Reg">luaL_Reg</A><BR>
473<A HREF="manual.html#luaL_Stream">luaL_Stream</A><BR>
452474
453475<P>
454476<A HREF="manual.html#luaL_addchar">luaL_addchar</A><BR>
r242885r242886
462484<A HREF="manual.html#luaL_buffinitsize">luaL_buffinitsize</A><BR>
463485<A HREF="manual.html#luaL_callmeta">luaL_callmeta</A><BR>
464486<A HREF="manual.html#luaL_checkany">luaL_checkany</A><BR>
465<A HREF="manual.html#luaL_checkint">luaL_checkint</A><BR>
466487<A HREF="manual.html#luaL_checkinteger">luaL_checkinteger</A><BR>
467<A HREF="manual.html#luaL_checklong">luaL_checklong</A><BR>
468488<A HREF="manual.html#luaL_checklstring">luaL_checklstring</A><BR>
469489<A HREF="manual.html#luaL_checknumber">luaL_checknumber</A><BR>
470490<A HREF="manual.html#luaL_checkoption">luaL_checkoption</A><BR>
r242885r242886
472492<A HREF="manual.html#luaL_checkstring">luaL_checkstring</A><BR>
473493<A HREF="manual.html#luaL_checktype">luaL_checktype</A><BR>
474494<A HREF="manual.html#luaL_checkudata">luaL_checkudata</A><BR>
475<A HREF="manual.html#luaL_checkunsigned">luaL_checkunsigned</A><BR>
476495<A HREF="manual.html#luaL_checkversion">luaL_checkversion</A><BR>
477496<A HREF="manual.html#luaL_dofile">luaL_dofile</A><BR>
478497<A HREF="manual.html#luaL_dostring">luaL_dostring</A><BR>
r242885r242886
494513<A HREF="manual.html#luaL_newmetatable">luaL_newmetatable</A><BR>
495514<A HREF="manual.html#luaL_newstate">luaL_newstate</A><BR>
496515<A HREF="manual.html#luaL_openlibs">luaL_openlibs</A><BR>
497<A HREF="manual.html#luaL_optint">luaL_optint</A><BR>
498516<A HREF="manual.html#luaL_optinteger">luaL_optinteger</A><BR>
499<A HREF="manual.html#luaL_optlong">luaL_optlong</A><BR>
500517<A HREF="manual.html#luaL_optlstring">luaL_optlstring</A><BR>
501518<A HREF="manual.html#luaL_optnumber">luaL_optnumber</A><BR>
502519<A HREF="manual.html#luaL_optstring">luaL_optstring</A><BR>
503<A HREF="manual.html#luaL_optunsigned">luaL_optunsigned</A><BR>
504520<A HREF="manual.html#luaL_prepbuffer">luaL_prepbuffer</A><BR>
505521<A HREF="manual.html#luaL_prepbuffsize">luaL_prepbuffsize</A><BR>
506522<A HREF="manual.html#luaL_pushresult">luaL_pushresult</A><BR>
r242885r242886
516532<A HREF="manual.html#luaL_unref">luaL_unref</A><BR>
517533<A HREF="manual.html#luaL_where">luaL_where</A><BR>
518534
535<H3><A NAME="library">standard library</A></H3>
536<P>
537<A HREF="manual.html#pdf-luaopen_base">luaopen_base</A><BR>
538<A HREF="manual.html#pdf-luaopen_coroutine">luaopen_coroutine</A><BR>
539<A HREF="manual.html#pdf-luaopen_debug">luaopen_debug</A><BR>
540<A HREF="manual.html#pdf-luaopen_io">luaopen_io</A><BR>
541<A HREF="manual.html#pdf-luaopen_math">luaopen_math</A><BR>
542<A HREF="manual.html#pdf-luaopen_os">luaopen_os</A><BR>
543<A HREF="manual.html#pdf-luaopen_package">luaopen_package</A><BR>
544<A HREF="manual.html#pdf-luaopen_string">luaopen_string</A><BR>
545<A HREF="manual.html#pdf-luaopen_table">luaopen_table</A><BR>
546<A HREF="manual.html#pdf-luaopen_utf8">luaopen_utf8</A><BR>
547
548<H3><A NAME="constants">constants</A></H3>
549<A HREF="manual.html#pdf-LUA_ERRERR">LUA_ERRERR</A><BR>
550<A HREF="manual.html#pdf-LUA_ERRFILE">LUA_ERRFILE</A><BR>
551<A HREF="manual.html#pdf-LUA_ERRGCMM">LUA_ERRGCMM</A><BR>
552<A HREF="manual.html#pdf-LUA_ERRMEM">LUA_ERRMEM</A><BR>
553<A HREF="manual.html#pdf-LUA_ERRRUN">LUA_ERRRUN</A><BR>
554<A HREF="manual.html#pdf-LUA_ERRSYNTAX">LUA_ERRSYNTAX</A><BR>
555<A HREF="manual.html#pdf-LUA_HOOKCALL">LUA_HOOKCALL</A><BR>
556<A HREF="manual.html#pdf-LUA_HOOKCOUNT">LUA_HOOKCOUNT</A><BR>
557<A HREF="manual.html#pdf-LUA_HOOKLINE">LUA_HOOKLINE</A><BR>
558<A HREF="manual.html#pdf-LUA_HOOKRET">LUA_HOOKRET</A><BR>
559<A HREF="manual.html#pdf-LUA_HOOKTAILCALL">LUA_HOOKTAILCALL</A><BR>
560<A HREF="manual.html#pdf-LUA_MASKCALL">LUA_MASKCALL</A><BR>
561<A HREF="manual.html#pdf-LUA_MASKCOUNT">LUA_MASKCOUNT</A><BR>
562<A HREF="manual.html#pdf-LUA_MASKLINE">LUA_MASKLINE</A><BR>
563<A HREF="manual.html#pdf-LUA_MASKRET">LUA_MASKRET</A><BR>
564<A HREF="manual.html#pdf-LUA_MAXINTEGER">LUA_MAXINTEGER</A><BR>
565<A HREF="manual.html#pdf-LUA_MININTEGER">LUA_MININTEGER</A><BR>
566<A HREF="manual.html#pdf-LUA_MINSTACK">LUA_MINSTACK</A><BR>
567<A HREF="manual.html#pdf-LUA_MULTRET">LUA_MULTRET</A><BR>
568<A HREF="manual.html#pdf-LUA_NOREF">LUA_NOREF</A><BR>
569<A HREF="manual.html#pdf-LUA_OK">LUA_OK</A><BR>
570<A HREF="manual.html#pdf-LUA_OPADD">LUA_OPADD</A><BR>
571<A HREF="manual.html#pdf-LUA_OPBAND">LUA_OPBAND</A><BR>
572<A HREF="manual.html#pdf-LUA_OPBNOT">LUA_OPBNOT</A><BR>
573<A HREF="manual.html#pdf-LUA_OPBOR">LUA_OPBOR</A><BR>
574<A HREF="manual.html#pdf-LUA_OPBXOR">LUA_OPBXOR</A><BR>
575<A HREF="manual.html#pdf-LUA_OPDIV">LUA_OPDIV</A><BR>
576<A HREF="manual.html#pdf-LUA_OPEQ">LUA_OPEQ</A><BR>
577<A HREF="manual.html#pdf-LUA_OPIDIV">LUA_OPIDIV</A><BR>
578<A HREF="manual.html#pdf-LUA_OPLE">LUA_OPLE</A><BR>
579<A HREF="manual.html#pdf-LUA_OPLT">LUA_OPLT</A><BR>
580<A HREF="manual.html#pdf-LUA_OPMOD">LUA_OPMOD</A><BR>
581<A HREF="manual.html#pdf-LUA_OPMUL">LUA_OPMUL</A><BR>
582<A HREF="manual.html#pdf-LUA_OPPOW">LUA_OPPOW</A><BR>
583<A HREF="manual.html#pdf-LUA_OPSHL">LUA_OPSHL</A><BR>
584<A HREF="manual.html#pdf-LUA_OPSHR">LUA_OPSHR</A><BR>
585<A HREF="manual.html#pdf-LUA_OPSUB">LUA_OPSUB</A><BR>
586<A HREF="manual.html#pdf-LUA_OPUNM">LUA_OPUNM</A><BR>
587<A HREF="manual.html#pdf-LUA_REFNIL">LUA_REFNIL</A><BR>
588<A HREF="manual.html#pdf-LUA_REGISTRYINDEX">LUA_REGISTRYINDEX</A><BR>
589<A HREF="manual.html#pdf-LUA_RIDX_GLOBALS">LUA_RIDX_GLOBALS</A><BR>
590<A HREF="manual.html#pdf-LUA_RIDX_MAINTHREAD">LUA_RIDX_MAINTHREAD</A><BR>
591<A HREF="manual.html#pdf-LUA_TBOOLEAN">LUA_TBOOLEAN</A><BR>
592<A HREF="manual.html#pdf-LUA_TFUNCTION">LUA_TFUNCTION</A><BR>
593<A HREF="manual.html#pdf-LUA_TLIGHTUSERDATA">LUA_TLIGHTUSERDATA</A><BR>
594<A HREF="manual.html#pdf-LUA_TNIL">LUA_TNIL</A><BR>
595<A HREF="manual.html#pdf-LUA_TNONE">LUA_TNONE</A><BR>
596<A HREF="manual.html#pdf-LUA_TNUMBER">LUA_TNUMBER</A><BR>
597<A HREF="manual.html#pdf-LUA_TSTRING">LUA_TSTRING</A><BR>
598<A HREF="manual.html#pdf-LUA_TTABLE">LUA_TTABLE</A><BR>
599<A HREF="manual.html#pdf-LUA_TTHREAD">LUA_TTHREAD</A><BR>
600<A HREF="manual.html#pdf-LUA_TUSERDATA">LUA_TUSERDATA</A><BR>
601<A HREF="manual.html#pdf-LUA_USE_APICHECK">LUA_USE_APICHECK</A><BR>
602<A HREF="manual.html#pdf-LUA_YIELD">LUA_YIELD</A><BR>
603<A HREF="manual.html#pdf-LUAL_BUFFERSIZE">LUAL_BUFFERSIZE</A><BR>
604
519605</TD>
520606</TR>
521607</TABLE>
r242885r242886
523609<HR>
524610<SMALL CLASS="footer">
525611Last update:
526Tue Mar 12 11:22:18 BRT 2013
612Tue Dec  9 21:26:07 BRST 2014
527613</SMALL>
528614<!--
529Last change: revised for Lua 5.2.2
615Last change: updated for Lua 5.3.0 (final)
530616-->
531617
532618</BODY>
trunk/3rdparty/lua/doc/lua.1
r242885r242886
1.\" $Id: lua.man,v 1.13 2011/11/16 17:16:53 lhf Exp $
2.TH LUA 1 "$Date: 2011/11/16 17:16:53 $"
1.TH LUA 1 "$Date: 2014/12/10 15:55:45 $"
32.SH NAME
43lua \- Lua interpreter
54.SH SYNOPSIS
r242885r242886
5049prompts the user,
5150reads lines from the standard input,
5251and executes them as they are read.
52If the line contains an expression or list of expressions,
53then the line is evaluated and the results are printed.
5354If a line does not contain a complete statement,
5455then a secondary prompt is displayed and
5556lines are read until a complete statement is formed or
5657a syntax error is found.
57If a line starts with
58.BR '=' ,
59then
60.B lua
61evaluates and displays
62the values of the expressions in the remainder of the line.
6358.LP
6459At the very start,
6560before even handling the command line,
6661.B lua
6762checks the contents of the environment variables
68.B LUA_INIT_5_2
63.B LUA_INIT_5_3
6964or
7065.BR LUA_INIT ,
7166in that order.
trunk/3rdparty/lua/doc/lua.css
r242885r242886
5353a:link:hover, a:visited:hover {
5454   color: #000080 ;
5555   background-color: #D0D0FF ;
56   border-radius: 4px;
5657}
5758
5859a:link:active, a:visited:active {
5960   color: #FF0000 ;
6061}
6162
63h1 a img {
64   vertical-align: text-bottom ;
65}
66
6267hr {
6368   border: 0 ;
6469   height: 1px ;
r242885r242886
8691input[type=text] {
8792   border: solid #a0a0a0 2px ;
8893   border-radius: 2em ;
89   -moz-border-radius: 2em ;
9094   background-image: url('images/search.png') ;
91   background-repeat: no-repeat;
95   background-repeat: no-repeat ;
9296   background-position: 4px center ;
9397   padding-left: 20px ;
9498   height: 2em ;
9599}
96100
101pre.session {
102   background-color: #F8F8F8 ;
103   padding: 1em ;
104   border-radius: 8px ;
105}
trunk/3rdparty/lua/doc/manual.html
r242885r242886
22<html>
33
44<head>
5<title>Lua 5.2 Reference Manual</title>
5<title>Lua 5.3 Reference Manual</title>
66<link rel="stylesheet" type="text/css" href="lua.css">
77<link rel="stylesheet" type="text/css" href="manual.css">
88<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
r242885r242886
1313<hr>
1414<h1>
1515<a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
16Lua 5.2 Reference Manual
16Lua 5.3 Reference Manual
1717</h1>
1818
1919by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
2020<p>
2121<small>
22Copyright &copy; 2011&ndash;2013 Lua.org, PUC-Rio.
22Copyright &copy; 2015 Lua.org, PUC-Rio.
2323Freely available under the terms of the
2424<a href="http://www.lua.org/license.html">Lua license</a>.
2525</small>
r242885r242886
3333<!-- ====================================================================== -->
3434<p>
3535
36<!-- $Id: manual.of,v 1.103 2013/03/14 18:51:56 roberto Exp $ -->
36<!-- $Id: manual.of,v 1.146 2015/01/06 11:23:01 roberto Exp $ -->
3737
3838
3939
r242885r242886
4444Lua is an extension programming language designed to support
4545general procedural programming with data description
4646facilities.
47It also offers good support for object-oriented programming,
47Lua also offers good support for object-oriented programming,
4848functional programming, and data-driven programming.
4949Lua is intended to be used as a powerful, lightweight,
5050embeddable scripting language for any program that needs one.
r242885r242886
5353
5454
5555<p>
56Being an extension language, Lua has no notion of a "main" program:
56As an extension language, Lua has no notion of a "main" program:
5757it only works <em>embedded</em> in a host client,
5858called the <em>embedding program</em> or simply the <em>host</em>.
5959The host program can invoke functions to execute a piece of Lua code,
r242885r242886
119119<em>Boolean</em> is the type of the values <b>false</b> and <b>true</b>.
120120Both <b>nil</b> and <b>false</b> make a condition false;
121121any other value makes it true.
122<em>Number</em> represents real (double-precision floating-point) numbers.
123Operations on numbers follow the same rules of
124the underlying C&nbsp;implementation,
125which, in turn, usually follows the IEEE 754 standard.
126(It is easy to build Lua interpreters that use other
127internal representations for numbers,
128such as single-precision floats or long integers;
129see file <code>luaconf.h</code>.)
122<em>Number</em> represents both
123integer numbers and real (floating-point) numbers.
130124<em>String</em> represents immutable sequences of bytes.
131125
132126Lua is 8-bit clean:
133127strings can contain any 8-bit value,
134128including embedded zeros ('<code>\0</code>').
129Lua is also encoding-agnostic;
130it makes no assumptions about the contents of a string.
135131
136132
137133<p>
134The type <em>number</em> uses two internal representations,
135one called <em>integer</em> and the other called <em>float</em>.
136Lua has explicit rules about when each representation is used,
137but it also converts between them automatically as needed (see <a href="#3.4.3">&sect;3.4.3</a>).
138Therefore,
139the programmer may choose to mostly ignore the difference
140between integers and floats
141or to assume complete control over the representation of each number.
142Standard Lua uses 64-bit integers and double-precision (64-bit) floats,
143but you can also compile Lua so that it
144uses 32-bit integers and/or single-precision (32-bit) floats.
145The option with 32 bits for both integers and floats
146is particularly attractive
147for small machines and embedded systems.
148(See macro <code>LUA_32BITS</code> in file <code>luaconf.h</code>.)
149
150
151<p>
138152Lua can call (and manipulate) functions written in Lua and
139functions written in C
140(see <a href="#3.4.9">&sect;3.4.9</a>).
153functions written in C (see <a href="#3.4.10">&sect;3.4.10</a>).
154Both are represented by the type <em>function</em>.
141155
142156
143157<p>
144158The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
145159be stored in Lua variables.
146A userdata value is a pointer to a block of raw memory.
160A userdata value represents a block of raw memory.
147161There are two kinds of userdata:
148full userdata, where the block of memory is managed by Lua,
149and light userdata, where the block of memory is managed by the host.
162<em>full userdata</em>,
163which is an object with a block of memory managed by Lua,
164and <em>light userdata</em>,
165which is simply a C&nbsp;pointer value.
150166Userdata has no predefined operations in Lua,
151167except assignment and identity test.
152168By using <em>metatables</em>,
r242885r242886
160176<p>
161177The type <em>thread</em> represents independent threads of execution
162178and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
163Do not confuse Lua threads with operating-system threads.
179Lua threads are not related to operating-system threads.
164180Lua supports coroutines on all systems,
165even those that do not support threads.
181even those that do not support threads natively.
166182
167183
168184<p>
169185The type <em>table</em> implements associative arrays,
170186that is, arrays that can be indexed not only with numbers,
171but with any Lua value except <b>nil</b> and NaN
172(<em>Not a Number</em>, a special numeric value used to represent
173undefined or unrepresentable results, such as <code>0/0</code>).
187but with any Lua value except <b>nil</b> and NaN.
188(<em>Not a Number</em> is a special numeric value used to represent
189undefined or unrepresentable results, such as <code>0/0</code>.)
174190Tables can be <em>heterogeneous</em>;
175191that is, they can contain values of all types (except <b>nil</b>).
176192Any key with value <b>nil</b> is not considered part of the table.
r242885r242886
179195
180196
181197<p>
182Tables are the sole data structuring mechanism in Lua;
198Tables are the sole data-structuring mechanism in Lua;
183199they can be used to represent ordinary arrays, sequences,
184200symbol tables, sets, records, graphs, trees, etc.
185201To represent records, Lua uses the field name as an index.
186202The language supports this representation by
187203providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
188204There are several convenient ways to create tables in Lua
189(see <a href="#3.4.8">&sect;3.4.8</a>).
205(see <a href="#3.4.9">&sect;3.4.9</a>).
190206
191207
192208<p>
193209We use the term <em>sequence</em> to denote a table where
194the set of all positive numeric keys is equal to <em>{1..n}</em>
195for some integer <em>n</em>,
196which is called the length of the sequence (see <a href="#3.4.6">&sect;3.4.6</a>).
210the set of all positive numeric keys is equal to {1..<em>n</em>}
211for some non-negative integer <em>n</em>,
212which is called the length of the sequence (see <a href="#3.4.7">&sect;3.4.7</a>).
197213
198214
199215<p>
r242885r242886
202218In particular,
203219because functions are first-class values,
204220table fields can contain functions.
205Thus tables can also carry <em>methods</em> (see <a href="#3.4.10">&sect;3.4.10</a>).
221Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>).
206222
207223
208224<p>
r242885r242886
212228denote the same table element
213229if and only if <code>i</code> and <code>j</code> are raw equal
214230(that is, equal without metamethods).
231In particular, floats with integral values
232are equal to their respective integers
233(e.g., <code>1.0 == 1</code>).
234To avoid ambiguities,
235any float with integral value used as a key
236is converted to its respective integer.
237For instance, if you write <code>a[2.0] = true</code>,
238the actual key inserted into the table will be the
239integer <code>2</code>.
240(On the other hand,
2412 and "<code>2</code>" are different Lua values and therefore
242denote different table entries.)
215243
216244
217245<p>
r242885r242886
235263
236264<p>
237265As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
238any reference to a global name <code>var</code> is syntactically translated
239to <code>_ENV.var</code>.
266any reference to a free name
267(that is, a name not bound to any declaration) <code>var</code>
268is syntactically translated to <code>_ENV.var</code>.
240269Moreover, every chunk is compiled in the scope of
241an external local variable called <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
242so <code>_ENV</code> itself is never a global name in a chunk.
270an external local variable named <code>_ENV</code> (see <a href="#3.3.2">&sect;3.3.2</a>),
271so <code>_ENV</code> itself is never a free name in a chunk.
243272
244273
245274<p>
246275Despite the existence of this external <code>_ENV</code> variable and
247the translation of global names,
276the translation of free names,
248277<code>_ENV</code> is a completely regular name.
249278In particular,
250279you can define new variables and parameters with that name.
251Each reference to a global name uses the <code>_ENV</code> that is
280Each reference to a free name uses the <code>_ENV</code> that is
252281visible at that point in the program,
253282following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
254283
r242885r242886
260289<p>
261290Lua keeps a distinguished environment called the <em>global environment</em>.
262291This value is kept at a special index in the C registry (see <a href="#4.5">&sect;4.5</a>).
263In Lua, the variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
292In Lua, the global variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
293(<a href="#pdf-_G"><code>_G</code></a> is never used internally.)
264294
265295
266296<p>
267When Lua compiles a chunk,
268it initializes the value of its <code>_ENV</code> upvalue
269with the global environment (see <a href="#pdf-load"><code>load</code></a>).
297When Lua loads a chunk,
298the default value for its <code>_ENV</code> upvalue
299is the global environment (see <a href="#pdf-load"><code>load</code></a>).
270300Therefore, by default,
271global variables in Lua code refer to entries in the global environment.
301free names in Lua code refer to entries in the global environment
302(and, therefore, they are also called <em>global variables</em>).
272303Moreover, all standard libraries are loaded in the global environment
273and several functions there operate on that environment.
304and some functions there operate on that environment.
274305You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
275306to load a chunk with a different environment.
276307(In C, you have to load the chunk and then change the value
277308of its first upvalue.)
278309
279310
280<p>
281If you change the global environment in the registry
282(through C code or the debug library),
283all chunks loaded after the change will get the new environment.
284Previously loaded chunks are not affected, however,
285as each has its own reference to the environment in its <code>_ENV</code> variable.
286Moreover, the variable <a href="#pdf-_G"><code>_G</code></a>
287(which is stored in the original global environment)
288is never updated by Lua.
289311
290312
291313
292
293
294314<h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
295315
296316<p>
297317Because Lua is an embedded extension language,
298318all Lua actions start from C&nbsp;code in the host program
299calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
319calling a function from the Lua library.
320(When you use Lua standalone,
321the <code>lua</code> application is the host program.)
300322Whenever an error occurs during
301323the compilation or execution of a Lua chunk,
302324control returns to the host,
r242885r242886
316338Whenever there is an error,
317339an <em>error object</em> (also called an <em>error message</em>)
318340is propagated with information about the error.
319Lua itself only generates errors where the error object is a string,
341Lua itself only generates errors whose error object is a string,
320342but programs may generate errors with
321any value for the error object.
343any value as the error object.
344It is up to the Lua program or its host to handle such error objects.
322345
323346
324347<p>
r242885r242886
333356This message handler is still protected by the protected call;
334357so, an error inside the message handler
335358will call the message handler again.
336If this loop goes on, Lua breaks it and returns an appropriate message.
359If this loop goes on for too long,
360Lua breaks it and returns an appropriate message.
337361
338362
339363
r242885r242886
370394You can replace the metatable of tables
371395using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
372396You cannot change the metatable of other types from Lua
373(except by using the debug library);
397(except by using the debug library (<a href="#6.10">&sect;6.10</a>));
374398you must use the C&nbsp;API for that.
375399
376400
r242885r242886
385409
386410
387411<p>
388A metatable controls how an object behaves in arithmetic operations,
389order comparisons, concatenation, length operation, and indexing.
412A metatable controls how an object behaves in
413arithmetic operations, bitwise operations,
414order comparisons, concatenation, length operation, calls, and indexing.
390415A metatable also can define a function to be called
391when a userdata or a table is garbage collected.
392When Lua performs one of these operations over a value,
393it checks whether this value has a metatable with the corresponding event.
394If so, the value associated with that key (the metamethod)
395controls how Lua will perform the operation.
416when a userdata or a table is garbage collected (<a href="#2.5">&sect;2.5</a>).
396417
397418
398419<p>
399Metatables control the operations listed next.
400Each operation is identified by its corresponding name.
401The key for each operation is a string with its name prefixed by
420A detailed list of events controlled by metatables is given next.
421Each operation is identified by its corresponding event name.
422The key for each event is a string with its name prefixed by
402423two underscores, '<code>__</code>';
403424for instance, the key for operation "add" is the
404425string "<code>__add</code>".
426Note that queries for metamethods are always raw;
427the access to a metamethod does not invoke other metamethods.
428You can emulate how Lua queries a metamethod for an object <code>obj</code>
429with the following code:
405430
406
407<p>
408The semantics of these operations is better explained by a Lua function
409describing how the interpreter executes the operation.
410The code shown here in Lua is only illustrative;
411the real behavior is hard coded in the interpreter
412and it is much more efficient than this simulation.
413All functions used in these descriptions
414(<a href="#pdf-rawget"><code>rawget</code></a>, <a href="#pdf-tonumber"><code>tonumber</code></a>, etc.)
415are described in <a href="#6.1">&sect;6.1</a>.
416In particular, to retrieve the metamethod of a given object,
417we use the expression
418
419431<pre>
420     metatable(obj)[event]
421</pre><p>
422This should be read as
432     rawget(getmetatable(obj) or {}, "__" .. event_name)
433</pre>
423434
424<pre>
425     rawget(getmetatable(obj) or {}, event)
426</pre><p>
427This means that the access to a metamethod does not invoke other metamethods,
428and access to objects with no metatables does not fail
429(it simply results in <b>nil</b>).
430
431
432435<p>
433For the unary <code>-</code> and <code>#</code> operators,
434the metamethod is called with a dummy second argument.
435This extra argument is only to simplify Lua's internals;
436it may be removed in future versions and therefore it is not present
437in the following code.
438(For most uses this extra argument is irrelevant.)
436For the unary operators (negation, length, and bitwise not),
437the metamethod is computed and called with a dummy second operand,
438equal to the first one.
439This extra operand is only to simplify Lua's internals
440(by making these operators behave like a binary operation)
441and may be removed in future versions.
442(For most uses this extra operand is irrelevant.)
439443
440444
441445
r242885r242886
444448<li><b>"add": </b>
445449the <code>+</code> operation.
446450
447
448
449<p>
450The function <code>getbinhandler</code> below defines how Lua chooses a handler
451for a binary operation.
452First, Lua tries the first operand.
453If its type does not define a handler for the operation,
454then Lua tries the second operand.
455
456<pre>
457     function getbinhandler (op1, op2, event)
458       return metatable(op1)[event] or metatable(op2)[event]
459     end
460</pre><p>
461By using this function,
462the behavior of the <code>op1 + op2</code> is
463
464<pre>
465     function add_event (op1, op2)
466       local o1, o2 = tonumber(op1), tonumber(op2)
467       if o1 and o2 then  -- both operands are numeric?
468         return o1 + o2   -- '+' here is the primitive 'add'
469       else  -- at least one of the operands is not numeric
470         local h = getbinhandler(op1, op2, "__add")
471         if h then
472           -- call the handler with both operands
473           return (h(op1, op2))
474         else  -- no handler available: default behavior
475           error(&middot;&middot;&middot;)
476         end
477       end
478     end
479</pre><p>
451If any operand for an addition is not a number
452(nor a string coercible to a number),
453Lua will try to call a metamethod.
454First, Lua will check the first operand (even if it is valid).
455If that operand does not define a metamethod for the "<code>__add</code>" event,
456then Lua will check the second operand.
457If Lua can find a metamethod,
458it calls the metamethod with the two operands as arguments,
459and the result of the call
460(adjusted to one value)
461is the result of the operation.
462Otherwise,
463it raises an error.
480464</li>
481465
482466<li><b>"sub": </b>
r242885r242886
500484<li><b>"mod": </b>
501485the <code>%</code> operation.
502486
503Behavior similar to the "add" operation,
504with the operation
505<code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
487Behavior similar to the "add" operation.
506488</li>
507489
508490<li><b>"pow": </b>
509491the <code>^</code> (exponentiation) operation.
510492
511Behavior similar to the "add" operation,
512with the function <code>pow</code> (from the C&nbsp;math library)
513as the primitive operation.
493Behavior similar to the "add" operation.
514494</li>
515495
516496<li><b>"unm": </b>
517the unary <code>-</code> operation.
497the <code>-</code> (unary minus) operation.
518498
499Behavior similar to the "add" operation.
500</li>
519501
520<pre>
521     function unm_event (op)
522       local o = tonumber(op)
523       if o then  -- operand is numeric?
524         return -o  -- '-' here is the primitive 'unm'
525       else  -- the operand is not numeric.
526         -- Try to get a handler from the operand
527         local h = metatable(op).__unm
528         if h then
529           -- call the handler with the operand
530           return (h(op))
531         else  -- no handler available: default behavior
532           error(&middot;&middot;&middot;)
533         end
534       end
535     end
536</pre><p>
502<li><b>"idiv": </b>
503the <code>//</code> (floor division) operation.
504
505Behavior similar to the "add" operation.
537506</li>
538507
539<li><b>"concat": </b>
540the <code>..</code> (concatenation) operation.
508<li><b>"band": </b>
509the <code>&amp;</code> (bitwise and) operation.
541510
511Behavior similar to the "add" operation,
512except that Lua will try a metamethod
513if any operator is neither an integer
514nor a value coercible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>).
515</li>
542516
543<pre>
544     function concat_event (op1, op2)
545       if (type(op1) == "string" or type(op1) == "number") and
546          (type(op2) == "string" or type(op2) == "number") then
547         return op1 .. op2  -- primitive string concatenation
548       else
549         local h = getbinhandler(op1, op2, "__concat")
550         if h then
551           return (h(op1, op2))
552         else
553           error(&middot;&middot;&middot;)
554         end
555       end
556     end
557</pre><p>
517<li><b>"bor": </b>
518the <code>|</code> (bitwise or) operation.
519
520Behavior similar to the "band" operation.
558521</li>
559522
560<li><b>"len": </b>
561the <code>#</code> operation.
523<li><b>"bxor": </b>
524the <code>~</code> (bitwise exclusive or) operation.
562525
526Behavior similar to the "band" operation.
527</li>
563528
564<pre>
565     function len_event (op)
566       if type(op) == "string" then
567         return strlen(op)      -- primitive string length
568       else
569         local h = metatable(op).__len
570         if h then
571           return (h(op))       -- call handler with the operand
572         elseif type(op) == "table" then
573           return #op              -- primitive table length
574         else  -- no handler available: error
575           error(&middot;&middot;&middot;)
576         end
577       end
578     end
579</pre><p>
580See <a href="#3.4.6">&sect;3.4.6</a> for a description of the length of a table.
529<li><b>"bnot": </b>
530the <code>~</code> (bitwise unary not) operation.
531
532Behavior similar to the "band" operation.
581533</li>
582534
583<li><b>"eq": </b>
584the <code>==</code> operation.
535<li><b>"shl": </b>
536the <code>&lt;&lt;</code> (bitwise left shift) operation.
585537
586The function <code>getequalhandler</code> defines how Lua chooses a metamethod
587for equality.
588A metamethod is selected only when both values
589being compared have the same type
590and the same metamethod for the selected operation,
591and the values are either tables or full userdata.
538Behavior similar to the "band" operation.
539</li>
592540
593<pre>
594     function getequalhandler (op1, op2)
595       if type(op1) ~= type(op2) or
596          (type(op1) ~= "table" and type(op1) ~= "userdata") then
597         return nil     -- different values
598       end
599       local mm1 = metatable(op1).__eq
600       local mm2 = metatable(op2).__eq
601       if mm1 == mm2 then return mm1 else return nil end
602     end
603</pre><p>
604The "eq" event is defined as follows:
541<li><b>"shr": </b>
542the <code>&gt;&gt;</code> (bitwise right shift) operation.
605543
606<pre>
607     function eq_event (op1, op2)
608       if op1 == op2 then   -- primitive equal?
609         return true   -- values are equal
610       end
611       -- try metamethod
612       local h = getequalhandler(op1, op2)
613       if h then
614         return not not h(op1, op2)
615       else
616         return false
617       end
618     end
619</pre><p>
620Note that the result is always a boolean.
544Behavior similar to the "band" operation.
621545</li>
622546
623<li><b>"lt": </b>
624the <code>&lt;</code> operation.
547<li><b>"concat": </b>
548the <code>..</code> (concatenation) operation.
625549
550Behavior similar to the "add" operation,
551except that Lua will try a metamethod
552if any operator is neither a string nor a number
553(which is always coercible to a string).
554</li>
626555
627<pre>
628     function lt_event (op1, op2)
629       if type(op1) == "number" and type(op2) == "number" then
630         return op1 &lt; op2   -- numeric comparison
631       elseif type(op1) == "string" and type(op2) == "string" then
632         return op1 &lt; op2   -- lexicographic comparison
633       else
634         local h = getbinhandler(op1, op2, "__lt")
635         if h then
636           return not not h(op1, op2)
637         else
638           error(&middot;&middot;&middot;)
639         end
640       end
641     end
642</pre><p>
643Note that the result is always a boolean.
556<li><b>"len": </b>
557the <code>#</code> (length) operation.
558
559If the object is not a string,
560Lua will try its metamethod.
561If there is a metamethod,
562Lua calls it with the object as argument,
563and the result of the call
564(always adjusted to one value)
565is the result of the operation.
566If there is no metamethod but the object is a table,
567then Lua uses the table length operation (see <a href="#3.4.7">&sect;3.4.7</a>).
568Otherwise, Lua raises an error.
644569</li>
645570
646<li><b>"le": </b>
647the <code>&lt;=</code> operation.
571<li><b>"eq": </b>
572the <code>==</code> (equal) operation.
648573
574Behavior similar to the "add" operation,
575except that Lua will try a metamethod only when the values
576being compared are either both tables or both full userdata
577and they are not primitively equal.
578The result of the call is always converted to a boolean.
579</li>
649580
650<pre>
651     function le_event (op1, op2)
652       if type(op1) == "number" and type(op2) == "number" then
653         return op1 &lt;= op2   -- numeric comparison
654       elseif type(op1) == "string" and type(op2) == "string" then
655         return op1 &lt;= op2   -- lexicographic comparison
656       else
657         local h = getbinhandler(op1, op2, "__le")
658         if h then
659           return not not h(op1, op2)
660         else
661           h = getbinhandler(op1, op2, "__lt")
662           if h then
663             return not h(op2, op1)
664           else
665             error(&middot;&middot;&middot;)
666           end
667         end
668       end
669     end
670</pre><p>
671Note that, in the absence of a "le" metamethod,
672Lua tries the "lt", assuming that <code>a &lt;= b</code> is
673equivalent to <code>not (b &lt; a)</code>.
581<li><b>"lt": </b>
582the <code>&lt;</code> (less than) operation.
674583
584Behavior similar to the "add" operation,
585except that Lua will try a metamethod only when the values
586being compared are neither both numbers nor both strings.
587The result of the call is always converted to a boolean.
588</li>
675589
676<p>
590<li><b>"le": </b>
591the <code>&lt;=</code> (less equal) operation.
592
593Unlike other operations,
594The less-equal operation can use two different events.
595First, Lua looks for the "<code>__le</code>" metamethod in both operands,
596like in the "lt" operation.
597If it cannot find such a metamethod,
598then it will try the "<code>__lt</code>" event,
599assuming that <code>a &lt;= b</code> is equivalent to <code>not (b &lt; a)</code>.
677600As with the other comparison operators,
678601the result is always a boolean.
679602</li>
680603
681604<li><b>"index": </b>
682605The indexing access <code>table[key]</code>.
683Note that the metamethod is tried only
606
607This event happens when <code>table</code> is not a table or
684608when <code>key</code> is not present in <code>table</code>.
685(When <code>table</code> is not a table,
686no key is ever present,
687so the metamethod is always tried.)
609The metamethod is looked up in <code>table</code>.
688610
689611
690<pre>
691     function gettable_event (table, key)
692       local h
693       if type(table) == "table" then
694         local v = rawget(table, key)
695         -- if key is present, return raw value
696         if v ~= nil then return v end
697         h = metatable(table).__index
698         if h == nil then return nil end
699       else
700         h = metatable(table).__index
701         if h == nil then
702           error(&middot;&middot;&middot;)
703         end
704       end
705       if type(h) == "function" then
706         return (h(table, key))     -- call the handler
707       else return h[key]           -- or repeat operation on it
708       end
709     end
710</pre><p>
612<p>
613Despite the name,
614the metamethod for this event can be either a function or a table.
615If it is a function,
616it is called with <code>table</code> and <code>key</code> as arguments.
617If it is a table,
618the final result is the result of indexing this table with <code>key</code>.
619(This indexing is regular, not raw,
620and therefore can trigger another metamethod.)
711621</li>
712622
713623<li><b>"newindex": </b>
714624The indexing assignment <code>table[key] = value</code>.
715Note that the metamethod is tried only
625
626Like the index event,
627this event happens when <code>table</code> is not a table or
716628when <code>key</code> is not present in <code>table</code>.
629The metamethod is looked up in <code>table</code>.
717630
718631
719<pre>
720     function settable_event (table, key, value)
721       local h
722       if type(table) == "table" then
723         local v = rawget(table, key)
724         -- if key is present, do raw assignment
725         if v ~= nil then rawset(table, key, value); return end
726         h = metatable(table).__newindex
727         if h == nil then rawset(table, key, value); return end
728       else
729         h = metatable(table).__newindex
730         if h == nil then
731           error(&middot;&middot;&middot;)
732         end
733       end
734       if type(h) == "function" then
735         h(table, key,value)           -- call the handler
736       else h[key] = value             -- or repeat operation on it
737       end
738     end
739</pre><p>
632<p>
633Like with indexing,
634the metamethod for this event can be either a function or a table.
635If it is a function,
636it is called with <code>table</code>, <code>key</code>, and <code>value</code> as arguments.
637If it is a table,
638Lua does an indexing assignment to this table with the same key and value.
639(This assignment is regular, not raw,
640and therefore can trigger another metamethod.)
641
642
643<p>
644Whenever there is a "newindex" metamethod,
645Lua does not perform the primitive assignment.
646(If necessary,
647the metamethod itself can call <a href="#pdf-rawset"><code>rawset</code></a>
648to do the assignment.)
740649</li>
741650
742651<li><b>"call": </b>
743called when Lua calls a value.
652The call operation <code>func(args)</code>.
744653
745
746<pre>
747     function function_event (func, ...)
748       if type(func) == "function" then
749         return func(...)   -- primitive call
750       else
751         local h = metatable(func).__call
752         if h then
753           return h(func, ...)
754         else
755           error(&middot;&middot;&middot;)
756         end
757       end
758     end
759</pre><p>
654This event happens when Lua tries to call a non-function value
655(that is, <code>func</code> is not a function).
656The metamethod is looked up in <code>func</code>.
657If present,
658the metamethod is called with <code>func</code> as its first argument,
659followed by the arguments of the original call (<code>args</code>).
760660</li>
761661
762662</ul>
r242885r242886
769669<p>
770670Lua performs automatic memory management.
771671This means that
772you have to worry neither about allocating memory for new objects
773nor about freeing it when the objects are no longer needed.
672you do not have to worry about allocating memory for new objects
673or freeing it when the objects are no longer needed.
774674Lua manages memory automatically by running
775675a <em>garbage collector</em> to collect all <em>dead objects</em>
776676(that is, objects that are no longer accessible from Lua).
r242885r242886
803703memory allocation.
804704Larger values make the collector more aggressive but also increase
805705the size of each incremental step.
806Values smaller than 100 make the collector too slow and
706You should not use values smaller than 100,
707because they make the collector too slow and
807708can result in the collector never finishing a cycle.
808709The default is 200,
809710which means that the collector runs at "twice"
r242885r242886
828729the collector directly (e.g., stop and restart it).
829730
830731
831<p>
832As an experimental feature in Lua 5.2,
833you can change the collector's operation mode
834from incremental to <em>generational</em>.
835A <em>generational collector</em> assumes that most objects die young,
836and therefore it traverses only young (recently created) objects.
837This behavior can reduce the time used by the collector,
838but also increases memory usage (as old dead objects may accumulate).
839To mitigate this second problem,
840from time to time the generational collector performs a full collection.
841Remember that this is an experimental feature;
842you are welcome to try it,
843but check your gains.
844732
845
846
847733<h3>2.5.1 &ndash; <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
848734
849735<p>
r242885r242886
866752Note that if you set a metatable without a <code>__gc</code> field
867753and later create that field in the metatable,
868754the object will not be marked for finalization.
869However, after an object is marked,
755However, after an object has been marked,
870756you can freely change the <code>__gc</code> field of its metatable.
871757
872758
r242885r242886
875761it is not collected immediately by the garbage collector.
876762Instead, Lua puts it in a list.
877763After the collection,
878Lua does the equivalent of the following function
879for each object in that list:
764Lua goes through that list.
765For each object in the list,
766it checks the object's <code>__gc</code> metamethod:
767If it is a function,
768Lua calls it with the object as its single argument;
769if the metamethod is not a function,
770Lua simply ignores it.
880771
881<pre>
882     function gc_event (obj)
883       local h = metatable(obj).__gc
884       if type(h) == "function" then
885         h(obj)
886       end
887     end
888</pre>
889772
890773<p>
891774At the end of each garbage-collection cycle,
892775the finalizers for objects are called in
893the reverse order that they were marked for collection,
776the reverse order that the objects were marked for finalization,
894777among those collected in that cycle;
895778that is, the first finalizer to be called is the one associated
896779with the object marked last in the program.
r242885r242886
900783
901784<p>
902785Because the object being collected must still be used by the finalizer,
903it (and other objects accessible only through it)
786that object (and other objects accessible only through it)
904787must be <em>resurrected</em> by Lua.
905788Usually, this resurrection is transient,
906789and the object memory is freed in the next garbage-collection cycle.
907790However, if the finalizer stores the object in some global place
908791(e.g., a global variable),
909then there is a permanent resurrection.
792then the resurrection is permanent.
793Moreover, if the finalizer marks a finalizing object for finalization again,
794its finalizer will be called again in the next cycle where the
795object is unreachable.
910796In any case,
911the object memory is freed only when it becomes completely inaccessible;
912its finalizer will never be called twice.
797the object memory is freed only in the GC cycle where
798the object is unreachable and not marked for finalization.
913799
914800
915801<p>
916802When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
917803Lua calls the finalizers of all objects marked for finalization,
918804following the reverse order that they were marked.
919If any finalizer marks new objects for collection during that phase,
920these new objects will not be finalized.
805If any finalizer marks objects for collection during that phase,
806these marks have no effect.
921807
922808
923809
r242885r242886
974860Values, such as numbers and light C functions,
975861are not subject to garbage collection,
976862and therefore are not removed from weak tables
977(unless its associated value is collected).
863(unless their associated values are collected).
978864Although strings are subject to garbage collection,
979865they do not have an explicit construction,
980866and therefore are not removed from weak tables.
r242885r242886
1029915a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
1030916the coroutine starts its execution,
1031917at the first line of its main function.
1032Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
1033to the coroutine main function.
918Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed
919as arguments to the coroutine's main function.
1034920After the coroutine starts running,
1035921it runs until it terminates or <em>yields</em>.
1036922
r242885r242886
1040926normally, when its main function returns
1041927(explicitly or implicitly, after the last instruction);
1042928and abnormally, if there is an unprotected error.
1043In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
929In case of normal termination,
930<a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1044931plus any values returned by the coroutine main function.
1045932In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
1046933plus an error message.
r242885r242886
11791066Lua is a case-sensitive language:
11801067<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
11811068are two different, valid names.
1182As a convention, names starting with an underscore followed by
1183uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>)
1184are reserved for variables used by Lua.
1069As a convention,
1070programs should avoid creating
1071names that start with an underscore followed by
1072one or more uppercase letters (such as <a href="#pdf-_VERSION"><code>_VERSION</code></a>).
11851073
11861074
11871075<p>
r242885r242886
11891077
11901078<pre>
11911079     +     -     *     /     %     ^     #
1080     &amp;     ~     |     &lt;&lt;    &gt;&gt;    //
11921081     ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
11931082     (     )     {     }     [     ]     ::
11941083     ;     :     ,     .     ..    ...
r242885r242886
12191108
12201109
12211110<p>
1222A byte in a literal string can also be specified by its numerical value.
1223This can be done with the escape sequence <code>\x<em>XX</em></code>,
1111Strings in Lua can contain any 8-bit value, including embedded zeros,
1112which can be specified as '<code>\0</code>'.
1113More generally,
1114we can specify any byte in a literal string by its numerical value.
1115This can be done
1116with the escape sequence <code>\x<em>XX</em></code>,
12241117where <em>XX</em> is a sequence of exactly two hexadecimal digits,
12251118or with the escape sequence <code>\<em>ddd</em></code>,
12261119where <em>ddd</em> is a sequence of up to three decimal digits.
1227(Note that if a decimal escape is to be followed by a digit,
1120(Note that if a decimal escape sequence is to be followed by a digit,
12281121it must be expressed using exactly three digits.)
1229Strings in Lua can contain any 8-bit value, including embedded zeros,
1230which can be specified as '<code>\0</code>'.
12311122
12321123
12331124<p>
1125The UTF-8 encoding of a Unicode character
1126can be inserted in a literal string with
1127the escape sequence <code>\u{<em>XXX</em>}</code>
1128(note the mandatory enclosing brackets),
1129where <em>XXX</em> is a sequence of one or more hexadecimal digits
1130representing the character code point.
1131
1132
1133<p>
12341134Literal strings can also be defined using a long format
12351135enclosed by <em>long brackets</em>.
12361136We define an <em>opening long bracket of level <em>n</em></em> as an opening
12371137square bracket followed by <em>n</em> equal signs followed by another
12381138opening square bracket.
1239So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1240an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
1139So, an opening long bracket of level&nbsp;0 is written as <code>[[</code>,
1140an opening long bracket of level&nbsp;1 is written as <code>[=[</code>,
12411141and so on.
12421142A <em>closing long bracket</em> is defined similarly;
1243for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
1143for instance,
1144a closing long bracket of level&nbsp;4 is written as  <code>]====]</code>.
12441145A <em>long literal</em> starts with an opening long bracket of any level and
12451146ends at the first closing long bracket of the same level.
1246It can contain any text except a closing bracket of the proper level.
1147It can contain any text except a closing bracket of the same level.
12471148Literals in this bracketed form can run for several lines,
12481149do not interpret any escape sequences,
12491150and ignore long brackets of any other level.
r242885r242886
12851186</pre>
12861187
12871188<p>
1288A <em>numerical constant</em> can be written with an optional fractional part
1189A <em>numerical constant</em> (or <em>numeral</em>)
1190can be written with an optional fractional part
12891191and an optional decimal exponent,
12901192marked by a letter '<code>e</code>' or '<code>E</code>'.
12911193Lua also accepts hexadecimal constants,
r242885r242886
12931195Hexadecimal constants also accept an optional fractional part
12941196plus an optional binary exponent,
12951197marked by a letter '<code>p</code>' or '<code>P</code>'.
1296Examples of valid numerical constants are
1198A numeric constant with a fractional dot or an exponent
1199denotes a float;
1200otherwise it denotes an integer.
1201Examples of valid integer constants are
12971202
12981203<pre>
1299     3     3.0     3.1416     314.16e-2     0.31416E1
1300     0xff  0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
1204     3   345   0xff   0xBEBADA
1205</pre><p>
1206Examples of valid float constants are
1207
1208<pre>
1209     3.0     3.1416     314.16e-2     0.31416E1     34e1
1210     0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
13011211</pre>
13021212
13031213<p>
r242885r242886
14661376<p>
14671377Lua handles a chunk as the body of an anonymous function
14681378with a variable number of arguments
1469(see <a href="#3.4.10">&sect;3.4.10</a>).
1379(see <a href="#3.4.11">&sect;3.4.11</a>).
14701380As such, chunks can define local variables,
14711381receive arguments, and return values.
14721382Moreover, such anonymous function is compiled as in the
r242885r242886
14781388<p>
14791389A chunk can be stored in a file or in a string inside the host program.
14801390To execute a chunk,
1481Lua first precompiles the chunk into instructions for a virtual machine,
1482and then it executes the compiled code
1391Lua first <em>loads</em> it,
1392precompiling the chunk's code into instructions for a virtual machine,
1393and then Lua executes the compiled code
14831394with an interpreter for the virtual machine.
14841395
14851396
14861397<p>
14871398Chunks can also be precompiled into binary form;
1488see program <code>luac</code> for details.
1399see program <code>luac</code> and function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
14891400Programs in source and compiled forms are interchangeable;
1490Lua automatically detects the file type and acts accordingly.
1401Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
14911402
14921403
14931404
14941405
14951406
1496
14971407<h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
14981408
14991409<p>
r242885r242886
15271437
15281438<p>
15291439The assignment statement first evaluates all its expressions
1530and only then are the assignments performed.
1440and only then the assignments are performed.
15311441Thus the code
15321442
15331443<pre>
r242885r242886
15631473
15641474
15651475<p>
1566An assignment to a global variable <code>x = val</code>
1476An assignment to a global name <code>x = val</code>
15671477is equivalent to the assignment
15681478<code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
15691479
r242885r242886
16441554
16451555<p>
16461556The <b>return</b> statement is used to return values
1647from a function or a chunk (which is a function in disguise).
1557from a function or a chunk
1558(which is an anonymous function).
16481559
16491560Functions can return more than one value,
16501561so the syntax for the <b>return</b> statement is
r242885r242886
16951606     do
16961607       local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
16971608       if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
1698       while (<em>step</em> &gt; 0 and <em>var</em> &lt;= <em>limit</em>) or (<em>step</em> &lt;= 0 and <em>var</em> &gt;= <em>limit</em>) do
1609       <em>var</em> = <em>var</em> - <em>step</em>
1610       while true do
1611         <em>var</em> = <em>var</em> + <em>step</em>
1612         if (<em>step</em> &gt;= 0 and <em>var</em> &gt; <em>limit</em>) or (<em>step</em> &lt; 0 and <em>var</em> &lt; <em>limit</em>) then
1613           break
1614         end
16991615         local v = <em>var</em>
17001616         <em>block</em>
1701         <em>var</em> = <em>var</em> + <em>step</em>
17021617       end
17031618     end
1704</pre><p>
1619</pre>
1620
1621<p>
17051622Note the following:
17061623
17071624<ul>
r242885r242886
17231640</li>
17241641
17251642<li>
1726You can use <b>break</b> to exit a <b>for</b> loop.
1643You can use <b>break</b> and <b>goto</b> to exit a <b>for</b> loop.
17271644</li>
17281645
17291646<li>
1730The loop variable <code>v</code> is local to the loop;
1731you cannot use its value after the <b>for</b> ends or is broken.
1732If you need this value,
1733assign it to another variable before breaking or exiting the loop.
1647The loop variable <code>v</code> is local to the loop body.
1648If you need its value after the loop,
1649assign it to another variable before exiting the loop.
17341650</li>
17351651
17361652</ul>
r242885r242886
18041720   stat ::= functioncall
18051721</pre><p>
18061722In this case, all returned values are thrown away.
1807Function calls are explained in <a href="#3.4.9">&sect;3.4.9</a>.
1723Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
18081724
18091725
18101726
r242885r242886
18441760<pre>
18451761   exp ::= prefixexp
18461762   exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
1847   exp ::= Number
1848   exp ::= String
1763   exp ::= Numeral
1764   exp ::= LiteralString
18491765   exp ::= functiondef
18501766   exp ::= tableconstructor
18511767   exp ::= &lsquo;<b>...</b>&rsquo;
r242885r242886
18551771</pre>
18561772
18571773<p>
1858Numbers and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
1774Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
18591775variables are explained in <a href="#3.2">&sect;3.2</a>;
1860function definitions are explained in <a href="#3.4.10">&sect;3.4.10</a>;
1861function calls are explained in <a href="#3.4.9">&sect;3.4.9</a>;
1862table constructors are explained in <a href="#3.4.8">&sect;3.4.8</a>.
1776function definitions are explained in <a href="#3.4.11">&sect;3.4.11</a>;
1777function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>;
1778table constructors are explained in <a href="#3.4.9">&sect;3.4.9</a>.
18631779Vararg expressions,
18641780denoted by three dots ('<code>...</code>'), can only be used when
18651781directly inside a vararg function;
1866they are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1782they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
18671783
18681784
18691785<p>
18701786Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</a>),
1871relational operators (see <a href="#3.4.3">&sect;3.4.3</a>), logical operators (see <a href="#3.4.4">&sect;3.4.4</a>),
1872and the concatenation operator (see <a href="#3.4.5">&sect;3.4.5</a>).
1787bitwise operators (see <a href="#3.4.2">&sect;3.4.2</a>),
1788relational operators (see <a href="#3.4.4">&sect;3.4.4</a>), logical operators (see <a href="#3.4.5">&sect;3.4.5</a>),
1789and the concatenation operator (see <a href="#3.4.6">&sect;3.4.6</a>).
18731790Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</a>),
1874the unary <b>not</b> (see <a href="#3.4.4">&sect;3.4.4</a>),
1875and the unary <em>length operator</em> (see <a href="#3.4.6">&sect;3.4.6</a>).
1791the unary bitwise not (see <a href="#3.4.2">&sect;3.4.2</a>),
1792the unary logical <b>not</b> (see <a href="#3.4.5">&sect;3.4.5</a>),
1793and the unary <em>length operator</em> (see <a href="#3.4.7">&sect;3.4.7</a>).
18761794
18771795
18781796<p>
r242885r242886
19231841
19241842
19251843<h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
1926Lua supports the usual arithmetic operators:
1927the binary <code>+</code> (addition),
1928<code>-</code> (subtraction), <code>*</code> (multiplication),
1929<code>/</code> (division), <code>%</code> (modulo), and <code>^</code> (exponentiation);
1930and unary <code>-</code> (mathematical negation).
1931If the operands are numbers, or strings that can be converted to
1932numbers (see <a href="#3.4.2">&sect;3.4.2</a>),
1933then all operations have the usual meaning.
1934Exponentiation works for any exponent.
1935For instance, <code>x^(-0.5)</code> computes the inverse of the square root of <code>x</code>.
1936Modulo is defined as
1844Lua supports the following arithmetic operators:
19371845
1938<pre>
1939     a % b == a - math.floor(a/b)*b
1940</pre><p>
1941That is, it is the remainder of a division that rounds
1942the quotient towards minus infinity.
1846<ul>
1847<li><b><code>+</code>: </b>addition</li>
1848<li><b><code>-</code>: </b>subtraction</li>
1849<li><b><code>*</code>: </b>multiplication</li>
1850<li><b><code>/</code>: </b>float division</li>
1851<li><b><code>//</code>: </b>floor division</li>
1852<li><b><code>%</code>: </b>modulo</li>
1853<li><b><code>^</code>: </b>exponentiation</li>
1854<li><b><code>-</code>: </b>unary minus</li>
1855</ul>
19431856
1857<p>
1858With the exception of exponentiation and float division,
1859the arithmetic operators work as follows:
1860If both operands are integers,
1861the operation is performed over integers and the result is an integer.
1862Otherwise, if both operands are numbers
1863or strings that can be converted to
1864numbers (see <a href="#3.4.3">&sect;3.4.3</a>),
1865then they are converted to floats,
1866the operation is performed following the usual rules
1867for floating-point arithmetic
1868(usually the IEEE 754 standard),
1869and the result is a float.
19441870
19451871
1872<p>
1873Exponentiation and float division (<code>/</code>)
1874always convert their operands to floats
1875and the result is always a float.
1876Exponentiation uses the ISO&nbsp;C function <code>pow</code>,
1877so that it works for non-integer exponents too.
19461878
19471879
1948<h3>3.4.2 &ndash; <a name="3.4.2">Coercion</a></h3>
1880<p>
1881Floor division (<code>//</code>) is a division
1882that rounds the quotient towards minus infinite,
1883that is, the floor of the division of its operands.
19491884
1885
19501886<p>
1951Lua provides automatic conversion between
1952string and number values at run time.
1953Any arithmetic operation applied to a string tries to convert
1954this string to a number, following the rules of the Lua lexer.
1955(The string may have leading and trailing spaces and a sign.)
1956Conversely, whenever a number is used where a string is expected,
1957the number is converted to a string, in a reasonable format.
1887Modulo is defined as the remainder of a division
1888that rounds the quotient towards minus infinite (floor division).
1889
1890
1891<p>
1892In case of overflows in integer arithmetic,
1893all operations <em>wrap around</em>,
1894according to the usual rules of two-complement arithmetic.
1895(In other words,
1896they return the unique representable integer
1897that is equal modulo <em>2<sup>64</sup></em> to the mathematical result.)
1898
1899
1900
1901<h3>3.4.2 &ndash; <a name="3.4.2">Bitwise Operators</a></h3><p>
1902Lua supports the following bitwise operators:
1903
1904<ul>
1905<li><b><code>&amp;</code>: </b>bitwise and</li>
1906<li><b><code>&#124;</code>: </b>bitwise or</li>
1907<li><b><code>~</code>: </b>bitwise exclusive or</li>
1908<li><b><code>&gt;&gt;</code>: </b>right shift</li>
1909<li><b><code>&lt;&lt;</code>: </b>left shift</li>
1910<li><b><code>~</code>: </b>unary bitwise not</li>
1911</ul>
1912
1913<p>
1914All bitwise operations convert its operands to integers
1915(see <a href="#3.4.3">&sect;3.4.3</a>),
1916operate on all bits of those integers,
1917and result in an integer.
1918
1919
1920<p>
1921Both right and left shifts fill the vacant bits with zeros.
1922Negative displacements shift to the other direction;
1923displacements with absolute values equal to or higher than
1924the number of bits in an integer
1925result in zero (as all bits are shifted out).
1926
1927
1928
1929
1930
1931<h3>3.4.3 &ndash; <a name="3.4.3">Coercions and Conversions</a></h3><p>
1932Lua provides some automatic conversions between some
1933types and representations at run time.
1934Bitwise operators always convert float operands to integers.
1935Exponentiation and float division
1936always convert integer operands to floats.
1937All other arithmetic operations applied to mixed numbers
1938(integers and floats) convert the integer operand to a float;
1939this is called the <em>usual rule</em>.
1940The C API also converts both integers to floats and
1941floats to integers, as needed.
1942Moreover, string concatenation accepts numbers as arguments,
1943besides strings.
1944
1945
1946<p>
1947Lua also converts strings to numbers,
1948whenever a number is expected.
1949
1950
1951<p>
1952In a conversion from integer to float,
1953if the integer value has an exact representation as a float,
1954that is the result.
1955Otherwise,
1956the conversion gets the nearest higher or
1957the nearest lower representable value.
1958This kind of conversion never fails.
1959
1960
1961<p>
1962The conversion from float to integer
1963checks whether the float has an exact representation as an integer
1964(that is, the float has an integral value and
1965it is in the range of integer representation).
1966If it does, that representation is the result.
1967Otherwise, the conversion fails.
1968
1969
1970<p>
1971The conversion from strings to numbers goes as follows:
1972First, the string is converted to an integer or a float,
1973following its syntax and the rules of the Lua lexer.
1974(The string may have also leading and trailing spaces and a sign.)
1975Then, the resulting number is converted to the required type
1976(float or integer) according to the previous rules.
1977
1978
1979<p>
1980The conversion from numbers to strings uses a
1981non-specified human-readable format.
19581982For complete control over how numbers are converted to strings,
19591983use the <code>format</code> function from the string library
19601984(see <a href="#pdf-string.format"><code>string.format</code></a>).
r242885r242886
19631987
19641988
19651989
1966<h3>3.4.3 &ndash; <a name="3.4.3">Relational Operators</a></h3><p>
1967The relational operators in Lua are
1990<h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
1991Lua supports the following relational operators:
19681992
1969<pre>
1970     ==    ~=    &lt;     &gt;     &lt;=    &gt;=
1971</pre><p>
1993<ul>
1994<li><b><code>==</code>: </b>equality</li>
1995<li><b><code>~=</code>: </b>inequality</li>
1996<li><b><code>&lt;</code>: </b>less than</li>
1997<li><b><code>&gt;</code>: </b>greater than</li>
1998<li><b><code>&lt;=</code>: </b>less or equal</li>
1999<li><b><code>&gt;=</code>: </b>greater or equal</li>
2000</ul><p>
19722001These operators always result in <b>false</b> or <b>true</b>.
19732002
19742003
r242885r242886
19762005Equality (<code>==</code>) first compares the type of its operands.
19772006If the types are different, then the result is <b>false</b>.
19782007Otherwise, the values of the operands are compared.
1979Numbers and strings are compared in the usual way.
2008Strings are compared in the obvious way.
2009Numbers follow the usual rule for binary operations:
2010if both operands are integers,
2011they are compared as integers;
2012otherwise, they are converted to floats
2013and compared as such.
2014
2015
2016<p>
19802017Tables, userdata, and threads
19812018are compared by reference:
19822019two objects are considered equal only if they are the same object.
r242885r242886
19942031
19952032
19962033<p>
1997The conversion rules of <a href="#3.4.2">&sect;3.4.2</a>
1998do not apply to equality comparisons.
2034Equality comparisons do not convert strings to numbers
2035or vice versa.
19992036Thus, <code>"0"==0</code> evaluates to <b>false</b>,
20002037and <code>t[0]</code> and <code>t["0"]</code> denote different
20012038entries in a table.
r242885r242886
20072044
20082045<p>
20092046The order operators work as follows.
2010If both arguments are numbers, then they are compared as such.
2047If both arguments are numbers,
2048then they are compared following
2049the usual rule for binary operations.
20112050Otherwise, if both arguments are strings,
20122051then their values are compared according to the current locale.
20132052Otherwise, Lua tries to call the "lt" or the "le"
r242885r242886
20192058
20202059
20212060
2022<h3>3.4.4 &ndash; <a name="3.4.4">Logical Operators</a></h3><p>
2061<h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
20232062The logical operators in Lua are
20242063<b>and</b>, <b>or</b>, and <b>not</b>.
20252064Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
r242885r242886
20352074The disjunction operator <b>or</b> returns its first argument
20362075if this value is different from <b>nil</b> and <b>false</b>;
20372076otherwise, <b>or</b> returns its second argument.
2038Both <b>and</b> and <b>or</b> use short-cut evaluation;
2077Both <b>and</b> and <b>or</b> use short-circuit evaluation;
20392078that is,
20402079the second operand is evaluated only if necessary.
20412080Here are some examples:
r242885r242886
20572096
20582097
20592098
2060<h3>3.4.5 &ndash; <a name="3.4.5">Concatenation</a></h3><p>
2099<h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
20612100The string concatenation operator in Lua is
20622101denoted by two dots ('<code>..</code>').
20632102If both operands are strings or numbers, then they are converted to
2064strings according to the rules mentioned in <a href="#3.4.2">&sect;3.4.2</a>.
2103strings according to the rules described in <a href="#3.4.3">&sect;3.4.3</a>.
20652104Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
20662105
20672106
20682107
20692108
20702109
2071<h3>3.4.6 &ndash; <a name="3.4.6">The Length Operator</a></h3>
2110<h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
20722111
20732112<p>
20742113The length operator is denoted by the unary prefix operator <code>#</code>.
r242885r242886
20882127table is a <em>sequence</em>,
20892128that is,
20902129the set of its positive numeric keys is equal to <em>{1..n}</em>
2091for some integer <em>n</em>.
2130for some non-negative integer <em>n</em>.
20922131In that case, <em>n</em> is its length.
20932132Note that a table like
20942133
r242885r242886
21062145
21072146
21082147
2109<h3>3.4.7 &ndash; <a name="3.4.7">Precedence</a></h3><p>
2148<h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
21102149Operator precedence in Lua follows the table below,
21112150from lower to higher priority:
21122151
r242885r242886
21142153     or
21152154     and
21162155     &lt;     &gt;     &lt;=    &gt;=    ~=    ==
2156     |
2157     ~
2158     &amp;
2159     &lt;&lt;    &gt;&gt;
21172160     ..
21182161     +     -
2119     *     /     %
2120     not   #     - (unary)
2162     *     /     //    %
2163     unary operators (not   #     -     ~)
21212164     ^
21222165</pre><p>
21232166As usual,
r242885r242886
21302173
21312174
21322175
2133<h3>3.4.8 &ndash; <a name="3.4.8">Table Constructors</a></h3><p>
2176<h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
21342177Table constructors are expressions that create tables.
21352178Every time a constructor is evaluated, a new table is created.
21362179A constructor can be used to create an empty table
r242885r242886
21502193A field of the form <code>name = exp</code> is equivalent to
21512194<code>["name"] = exp</code>.
21522195Finally, fields of the form <code>exp</code> are equivalent to
2153<code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
2196<code>[i] = exp</code>, where <code>i</code> are consecutive integers
21542197starting with 1.
21552198Fields in the other formats do not affect this counting.
21562199For example,
r242885r242886
21752218</pre>
21762219
21772220<p>
2221The order of the assignments in a constructor is undefined.
2222(This order would be relevant only when there are repeated keys.)
2223
2224
2225<p>
21782226If the last field in the list has the form <code>exp</code>
21792227and the expression is a function call or a vararg expression,
21802228then all values returned by this expression enter the list consecutively
2181(see <a href="#3.4.9">&sect;3.4.9</a>).
2229(see <a href="#3.4.10">&sect;3.4.10</a>).
21822230
21832231
21842232<p>
r242885r242886
21892237
21902238
21912239
2192<h3>3.4.9 &ndash; <a name="3.4.9">Function Calls</a></h3><p>
2240<h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
21932241A function call in Lua has the following syntax:
21942242
21952243<pre>
r242885r242886
22242272<pre>
22252273   args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
22262274   args ::= tableconstructor
2227   args ::= String
2275   args ::= LiteralString
22282276</pre><p>
22292277All argument expressions are evaluated before the call.
22302278A call of the form <code>f{<em>fields</em>}</code> is
r242885r242886
22642312
22652313
22662314
2267<h3>3.4.10 &ndash; <a name="3.4.10">Function Definitions</a></h3>
2315<h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
22682316
22692317<p>
22702318The syntax for function definition is
r242885r242886
25552603In particular,
25562604<em>you are responsible for controlling stack overflow</em>.
25572605You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2558to ensure that the stack has extra slots when pushing new elements.
2606to ensure that the stack has enough space for pushing new elements.
25592607
25602608
25612609<p>
25622610Whenever Lua calls C,
2563it ensures that the stack has at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
2611it ensures that the stack has space for
2612at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
25642613<code>LUA_MINSTACK</code> is defined as 20,
25652614so that usually you do not have to worry about stack space
25662615unless your code has loops pushing elements onto the stack.
r242885r242886
25692618<p>
25702619When you call a Lua function
25712620without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2572Lua ensures that the stack has enough size for all results,
2621Lua ensures that the stack has enough space for all results,
25732622but it does not ensure any extra space.
25742623So, before pushing anything in the stack after such a call
25752624you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
r242885r242886
26732722<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>,
26742723which is a valid index.
26752724Any C&nbsp;library can store data into this table,
2676but it should take care to choose keys
2725but it must take care to choose keys
26772726that are different from those used
26782727by other libraries, to avoid collisions.
26792728Typically, you should use as key a string containing your library name,
26802729or a light userdata with the address of a C&nbsp;object in your code,
26812730or any Lua object created by your code.
2682As with global names,
2731As with variable names,
26832732string keys starting with an underscore followed by
26842733uppercase letters are reserved for Lua.
26852734
26862735
26872736<p>
2688The integer keys in the registry are used by the reference mechanism,
2689implemented by the auxiliary library,
2737The integer keys in the registry are used
2738by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
26902739and by some predefined values.
2691Therefore, integer keys should not be used for other purposes.
2740Therefore, integer keys must not be used for other purposes.
26922741
26932742
26942743<p>
r242885r242886
27162765
27172766<p>
27182767Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2719(You can also choose to use exceptions if you compile Lua as C++;
2720search for <code>LUAI_THROW</code> in the source code.)
2768(Lua will use exceptions if you compile it as C++;
2769search for <code>LUAI_THROW</code> in the source code for details.)
27212770When Lua faces any error
27222771(such as a memory allocation error, type errors, syntax errors,
27232772and runtime errors)
r242885r242886
27412790<p>
27422791The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
27432792in particular, the error message is at the top of the stack.
2744However, there is no guarantees about stack space.
2793However, there is no guarantee about stack space.
27452794To push anything on the stack,
2746the panic function should first check the available space (see <a href="#4.2">&sect;4.2</a>).
2795the panic function must first check the available space (see <a href="#4.2">&sect;4.2</a>).
27472796
27482797
27492798<p>
2750Most functions in the API can throw an error,
2799Most functions in the API can raise an error,
27512800for instance due to a memory allocation error.
27522801The documentation for each function indicates whether
2753it can throw errors.
2802it can raise errors.
27542803
27552804
27562805<p>
2757Inside a C&nbsp;function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2806Inside a C&nbsp;function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>.
27582807
27592808
27602809
r242885r242886
27642813
27652814<p>
27662815Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
2767Therefore, if a function <code>foo</code> calls an API function
2816Therefore, if a C function <code>foo</code> calls an API function
27682817and this API function yields
27692818(directly or indirectly by calling another function that yields),
27702819Lua cannot return to <code>foo</code> any more,
r242885r242886
27772826except for three functions:
27782827<a href="#lua_yieldk"><code>lua_yieldk</code></a>, <a href="#lua_callk"><code>lua_callk</code></a>, and <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
27792828All those functions receive a <em>continuation function</em>
2780(as a parameter called <code>k</code>) to continue execution after a yield.
2829(as a parameter named <code>k</code>) to continue execution after a yield.
27812830
27822831
27832832<p>
r242885r242886
28072856
28082857
28092858<p>
2859As an illustration, consider the following function:
2860
2861<pre>
2862     int original_function (lua_State *L) {
2863       ...     /* code 1 */
2864       status = lua_pcall(L, n, m, h);  /* calls Lua */
2865       ...     /* code 2 */
2866     }
2867</pre><p>
2868Now we want to allow
2869the Lua code being run by <a href="#lua_pcall"><code>lua_pcall</code></a> to yield.
2870First, we can rewrite our function like here:
2871
2872<pre>
2873     int k (lua_State *L, int status, lua_KContext ctx) {
2874       ...  /* code 2 */
2875     }
2876     
2877     int original_function (lua_State *L) {
2878       ...     /* code 1 */
2879       return k(L, lua_pcall(L, n, m, h), ctx);
2880     }
2881</pre><p>
2882In the above code,
2883the new function <code>k</code> is a
2884<em>continuation function</em> (with type <a href="#lua_KFunction"><code>lua_KFunction</code></a>),
2885which should do all the work that the original function
2886was doing after calling <a href="#lua_pcall"><code>lua_pcall</code></a>.
2887Now, we must inform Lua that it must call <code>k</code> if the Lua code
2888being executed by <a href="#lua_pcall"><code>lua_pcall</code></a> gets interrupted in some way
2889(errors or yielding),
2890so we rewrite the code as here,
2891replacing <a href="#lua_pcall"><code>lua_pcall</code></a> by <a href="#lua_pcallk"><code>lua_pcallk</code></a>:
2892
2893<pre>
2894     int original_function (lua_State *L) {
2895       ...     /* code 1 */
2896       return k(L, lua_pcallk(L, n, m, h, ctx2, k), ctx1);
2897     }
2898</pre><p>
2899Note the external, explicit call to the continuation:
2900Lua will call the continuation only if needed, that is,
2901in case of errors or resuming after a yield.
2902If the called function returns normally without ever yielding,
2903<a href="#lua_pcallk"><code>lua_pcallk</code></a> (and <a href="#lua_callk"><code>lua_callk</code></a>) will also return normally.
2904(Of course, instead of calling the continuation in that case,
2905you can do the equivalent work directly inside the original function.)
2906
2907
2908<p>
2909Besides the Lua state,
2910the continuation function has two other parameters:
2911the final status of the call plus the context value (<code>ctx</code>) that
2912was passed originally to <a href="#lua_pcallk"><code>lua_pcallk</code></a>.
2913(Lua does not use this context value;
2914it only passes this value from the original function to the
2915continuation function.)
2916For <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
2917the status is the same value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
2918except that it is <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when being executed after a yield
2919(instead of <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>).
2920For <a href="#lua_yieldk"><code>lua_yieldk</code></a> and <a href="#lua_callk"><code>lua_callk</code></a>,
2921the status is always <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> when Lua calls the continuation.
2922(For these two functions,
2923Lua will not call the continuation in case of errors,
2924because they do not handle errors.)
2925Similarly, when using <a href="#lua_callk"><code>lua_callk</code></a>,
2926you should call the continuation function
2927with <a href="#pdf-LUA_OK"><code>LUA_OK</code></a> as the status.
2928(For <a href="#lua_yieldk"><code>lua_yieldk</code></a>, there is not much point in calling
2929directly the continuation function,
2930because <a href="#lua_yieldk"><code>lua_yieldk</code></a> usually does not return.)
2931
2932
2933<p>
28102934Lua treats the continuation function as if it were the original function.
28112935The continuation function receives the same Lua stack
28122936from the original function,
r242885r242886
28192943of the original function.
28202944
28212945
2822<p>
2823The only difference in the Lua state between the original function
2824and its continuation is the result of a call to <a href="#lua_getctx"><code>lua_getctx</code></a>.
28252946
28262947
28272948
2828
2829
28302949<h2>4.8 &ndash; <a name="4.8">Functions and Types</a></h2>
28312950
28322951<p>
r242885r242886
28502969by looking only at its arguments
28512970(e.g., they may depend on what is on the stack).
28522971The third field, <code>x</code>,
2853tells whether the function may throw errors:
2854'<code>-</code>' means the function never throws any error;
2855'<code>e</code>' means the function may throw errors;
2856'<code>v</code>' means the function may throw an error on purpose.
2972tells whether the function may raise errors:
2973'<code>-</code>' means the function never raises any error;
2974'<code>e</code>' means the function may raise errors;
2975'<code>v</code>' means the function may raise an error on purpose.
28572976
28582977
28592978
r242885r242886
28853004<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
28863005<code>osize</code>, the original size of the block or some code about what
28873006is being allocated;
2888<code>nsize</code>, the new size of the block.
3007and <code>nsize</code>, the new size of the block.
28893008
28903009
28913010<p>
r242885r242886
29113030
29123031<p>
29133032When <code>nsize</code> is zero,
2914the allocator should behave like <code>free</code>
3033the allocator must behave like <code>free</code>
29153034and return <code>NULL</code>.
29163035
29173036
29183037<p>
29193038When <code>nsize</code> is not zero,
2920the allocator should behave like <code>realloc</code>.
3039the allocator must behave like <code>realloc</code>.
29213040The allocator returns <code>NULL</code>
29223041if and only if it cannot fulfill the request.
29233042Lua assumes that the allocator never fails when
r242885r242886
29423061</pre><p>
29433062Note that Standard&nbsp;C ensures
29443063that <code>free(NULL)</code> has no effect and that
2945<code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
3064<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
29463065This code assumes that <code>realloc</code> does not fail when shrinking a block.
29473066(Although Standard&nbsp;C does not ensure this behavior,
29483067it seems to be a safe assumption.)
r242885r242886
29563075<pre>void lua_arith (lua_State *L, int op);</pre>
29573076
29583077<p>
2959Performs an arithmetic operation over the two values
2960(or one, in the case of negation)
3078Performs an arithmetic or bitwise operation over the two values
3079(or one, in the case of negations)
29613080at the top of the stack,
29623081with the value at the top being the second operand,
29633082pops these values, and pushes the result of the operation.
r242885r242886
29733092<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
29743093<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
29753094<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<code>*</code>)</li>
2976<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs division (<code>/</code>)</li>
3095<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs float division (<code>/</code>)</li>
3096<li><b><a name="pdf-LUA_OPIDIV"><code>LUA_OPIDIV</code></a>: </b> performs floor division (<code>//</code>)</li>
29773097<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
29783098<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
29793099<li><b><a name="pdf-LUA_OPUNM"><code>LUA_OPUNM</code></a>: </b> performs mathematical negation (unary <code>-</code>)</li>
3100<li><b><a name="pdf-LUA_OPBNOT"><code>LUA_OPBNOT</code></a>: </b> performs bitwise negation (<code>~</code>)</li>
3101<li><b><a name="pdf-LUA_OPBAND"><code>LUA_OPBAND</code></a>: </b> performs bitwise and (<code>&amp;</code>)</li>
3102<li><b><a name="pdf-LUA_OPBOR"><code>LUA_OPBOR</code></a>: </b> performs bitwise or (<code>|</code>)</li>
3103<li><b><a name="pdf-LUA_OPBXOR"><code>LUA_OPBXOR</code></a>: </b> performs bitwise exclusive or (<code>~</code>)</li>
3104<li><b><a name="pdf-LUA_OPSHL"><code>LUA_OPSHL</code></a>: </b> performs left shift (<code>&lt;&lt;</code>)</li>
3105<li><b><a name="pdf-LUA_OPSHR"><code>LUA_OPSHR</code></a>: </b> performs right shift (<code>&gt;&gt;</code>)</li>
29803106
29813107</ul>
29823108
r242885r242886
30383164
30393165<pre>
30403166     lua_getglobal(L, "f");                  /* function to be called */
3041     lua_pushstring(L, "how");                        /* 1st argument */
3167     lua_pushliteral(L, "how");                       /* 1st argument */
30423168     lua_getglobal(L, "t");                    /* table to be indexed */
30433169     lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
30443170     lua_remove(L, -2);                  /* remove 't' from the stack */
r242885r242886
30463172     lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
30473173     lua_setglobal(L, "a");                         /* set global 'a' */
30483174</pre><p>
3049Note that the code above is "balanced":
3175Note that the code above is <em>balanced</em>:
30503176at its end, the stack is back to its original configuration.
30513177This is considered good programming practice.
30523178
r242885r242886
30563182
30573183<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
30583184<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3059<pre>void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
3060                lua_CFunction k);</pre>
3185<pre>void lua_callk (lua_State *L,
3186                int nargs,
3187                int nresults,
3188                lua_KContext ctx,
3189                lua_KFunction k);</pre>
30613190
30623191<p>
30633192This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
r242885r242886
30953224
30963225<p>
30973226As an example, the following function receives a variable number
3098of numerical arguments and returns their average and sum:
3227of numerical arguments and returns their average and their sum:
30993228
31003229<pre>
31013230     static int foo (lua_State *L) {
31023231       int n = lua_gettop(L);    /* number of arguments */
3103       lua_Number sum = 0;
3232       lua_Number sum = 0.0;
31043233       int i;
31053234       for (i = 1; i &lt;= n; i++) {
31063235         if (!lua_isnumber(L, i)) {
3107           lua_pushstring(L, "incorrect argument");
3236           lua_pushliteral(L, "incorrect argument");
31083237           lua_error(L);
31093238         }
31103239         sum += lua_tonumber(L, i);
r242885r242886
31203249
31213250<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
31223251<span class="apii">[-0, +0, &ndash;]</span>
3123<pre>int lua_checkstack (lua_State *L, int extra);</pre>
3252<pre>int lua_checkstack (lua_State *L, int n);</pre>
31243253
31253254<p>
3126Ensures that there are at least <code>extra</code> free stack slots in the stack.
3255Ensures that the stack has space for at least <code>n</code> extra slots.
31273256It returns false if it cannot fulfill the request,
3128because it would cause the stack to be larger than a fixed maximum size
3129(typically at least a few thousand elements) or
3130because it cannot allocate memory for the new stack size.
3257either because it would cause the stack
3258to be larger than a fixed maximum size
3259(typically at least several thousand elements) or
3260because it cannot allocate memory for the extra space.
31313261This function never shrinks the stack;
31323262if the stack is already larger than the new size,
31333263it is left unchanged.
r242885r242886
31483278because all resources are naturally released when the host program ends.
31493279On the other hand, long-running programs that create multiple states,
31503280such as daemons or web servers,
3151might need to close states as soon as they are not needed.
3281will probably need to close states as soon as they are not needed.
31523282
31533283
31543284
r242885r242886
31653295following the semantics of the corresponding Lua operator
31663296(that is, it may call metamethods).
31673297Otherwise returns&nbsp;0.
3168Also returns&nbsp;0 if any of the indices is non valid.
3298Also returns&nbsp;0 if any of the indices is not valid.
31693299
31703300
31713301<p>
r242885r242886
31933323(that is, the function does nothing);
31943324if <code>n</code> is 0, the result is the empty string.
31953325Concatenation is performed following the usual semantics of Lua
3196(see <a href="#3.4.5">&sect;3.4.5</a>).
3326(see <a href="#3.4.6">&sect;3.4.6</a>).
31973327
31983328
31993329
r242885r242886
32043334<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
32053335
32063336<p>
3207Moves the element at index <code>fromidx</code>
3208into the valid index <code>toidx</code>
3209without shifting any element
3210(therefore replacing the value at that position).
3337Copies the element at index <code>fromidx</code>
3338into the valid index <code>toidx</code>,
3339replacing the value at that position.
3340Values at other positions are not affected.
32113341
32123342
32133343
r242885r242886
32343364
32353365<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
32363366<span class="apii">[-0, +0, <em>e</em>]</span>
3237<pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
3367<pre>int lua_dump (lua_State *L,
3368                        lua_Writer writer,
3369                        void *data,
3370                        int strip);</pre>
32383371
32393372<p>
32403373Dumps a function as a binary chunk.
r242885r242886
32493382
32503383
32513384<p>
3385If <code>strip</code> is true,
3386the binary representation is created without debug information
3387about the function.
3388
3389
3390<p>
32523391The value returned is the error code returned by the last
32533392call to the writer;
325433930&nbsp;means no errors.
r242885r242886
32663405<pre>int lua_error (lua_State *L);</pre>
32673406
32683407<p>
3269Generates a Lua error.
3270The error message (which can actually be a Lua value of any type)
3271must be on the stack top.
3408Generates a Lua error,
3409using the value at the top of the stack as the error object.
32723410This function does a long jump,
32733411and therefore never returns
32743412(see <a href="#luaL_error"><code>luaL_error</code></a>).
r242885r242886
33143452
33153453<li><b><code>LUA_GCSTEP</code>: </b>
33163454performs an incremental step of garbage collection.
3317The step "size" is controlled by <code>data</code>
3318(larger values mean more steps) in a non-specified way.
3319If you want to control the step size
3320you must experimentally tune the value of <code>data</code>.
3321The function returns 1 if the step finished a
3322garbage-collection cycle.
33233455</li>
33243456
33253457<li><b><code>LUA_GCSETPAUSE</code>: </b>
33263458sets <code>data</code> as the new value
3327for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>).
3328The function returns the previous value of the pause.
3459for the <em>pause</em> of the collector (see <a href="#2.5">&sect;2.5</a>)
3460and returns the previous value of the pause.
33293461</li>
33303462
33313463<li><b><code>LUA_GCSETSTEPMUL</code>: </b>
33323464sets <code>data</code> as the new value for the <em>step multiplier</em> of
3333the collector (see <a href="#2.5">&sect;2.5</a>).
3334The function returns the previous value of the step multiplier.
3465the collector (see <a href="#2.5">&sect;2.5</a>)
3466and returns the previous value of the step multiplier.
33353467</li>
33363468
33373469<li><b><code>LUA_GCISRUNNING</code>: </b>
r242885r242886
33393471(i.e., not stopped).
33403472</li>
33413473
3342<li><b><code>LUA_GCGEN</code>: </b>
3343changes the collector to generational mode
3344(see <a href="#2.5">&sect;2.5</a>).
3345</li>
3346
3347<li><b><code>LUA_GCINC</code>: </b>
3348changes the collector to incremental mode.
3349This is the default mode.
3350</li>
3351
33523474</ul>
33533475
33543476<p>
r242885r242886
33663488<p>
33673489Returns the memory-allocation function of a given state.
33683490If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3369opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
3491opaque pointer given when the memory-allocator function was set.
33703492
33713493
33723494
33733495
33743496
3375<hr><h3><a name="lua_getctx"><code>lua_getctx</code></a></h3><p>
3497<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3498<span class="apii">[-0, +1, <em>e</em>]</span>
3499<pre>int lua_getfield (lua_State *L, int index, const char *k);</pre>
3500
3501<p>
3502Pushes onto the stack the value <code>t[k]</code>,
3503where <code>t</code> is the value at the given index.
3504As in Lua, this function may trigger a metamethod
3505for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3506
3507
3508<p>
3509Returns the type of the pushed value.
3510
3511
3512
3513
3514
3515<hr><h3><a name="lua_getextraspace"><code>lua_getextraspace</code></a></h3><p>
33763516<span class="apii">[-0, +0, &ndash;]</span>
3377<pre>int lua_getctx (lua_State *L, int *ctx);</pre>
3517<pre>void *lua_getextraspace (lua_State *L);</pre>
33783518
33793519<p>
3380This function is called by a continuation function (see <a href="#4.7">&sect;4.7</a>)
3381to retrieve the status of the thread and a context information.
3520Returns a pointer to a raw memory area associated with the
3521given Lua state.
3522The application can use this area for any purpose;
3523Lua does not use it for anything.
33823524
33833525
33843526<p>
3385When called in the original function,
3386<a href="#lua_getctx"><code>lua_getctx</code></a> always returns <a href="#pdf-LUA_OK"><code>LUA_OK</code></a>
3387and does not change the value of its argument <code>ctx</code>.
3388When called inside a continuation function,
3389<a href="#lua_getctx"><code>lua_getctx</code></a> returns <a href="#pdf-LUA_YIELD"><code>LUA_YIELD</code></a> and sets
3390the value of <code>ctx</code> to be the context information
3391(the value passed as the <code>ctx</code> argument
3392to the callee together with the continuation function).
3527Each new thread has this area initialized with a copy
3528of the area of the main thread.
33933529
33943530
33953531<p>
3396When the callee is <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3397Lua may also call its continuation function
3398to handle errors during the call.
3399That is, upon an error in the function called by <a href="#lua_pcallk"><code>lua_pcallk</code></a>,
3400Lua may not return to the original function
3401but instead may call the continuation function.
3402In that case, a call to <a href="#lua_getctx"><code>lua_getctx</code></a> will return the error code
3403(the value that would be returned by <a href="#lua_pcallk"><code>lua_pcallk</code></a>);
3404the value of <code>ctx</code> will be set to the context information,
3405as in the case of a yield.
3532By default, this area has the size of a pointer to void,
3533but you can recompile Lua with a different size for this area.
3534(See <code>LUA_EXTRASPACE</code> in <code>luaconf.h</code>.)
34063535
34073536
34083537
34093538
34103539
3411<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
3540<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
34123541<span class="apii">[-0, +1, <em>e</em>]</span>
3413<pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
3542<pre>int lua_getglobal (lua_State *L, const char *name);</pre>
34143543
34153544<p>
3416Pushes onto the stack the value <code>t[k]</code>,
3417where <code>t</code> is the value at the given index.
3418As in Lua, this function may trigger a metamethod
3419for the "index" event (see <a href="#2.4">&sect;2.4</a>).
3545Pushes onto the stack the value of the global <code>name</code>.
3546Returns the type of that value.
34203547
34213548
34223549
34233550
34243551
3425<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
3552<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
34263553<span class="apii">[-0, +1, <em>e</em>]</span>
3427<pre>void lua_getglobal (lua_State *L, const char *name);</pre>
3554<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
34283555
34293556<p>
3430Pushes onto the stack the value of the global <code>name</code>.
3557Pushes onto the stack the value <code>t[i]</code>,
3558where <code>t</code> is the value at the given index.
3559As in Lua, this function may trigger a metamethod
3560for the "index" event (see <a href="#2.4">&sect;2.4</a>).
34313561
34323562
3563<p>
3564Returns the type of the pushed value.
34333565
34343566
34353567
3568
3569
34363570<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
34373571<span class="apii">[-0, +(0|1), &ndash;]</span>
34383572<pre>int lua_getmetatable (lua_State *L, int index);</pre>
34393573
34403574<p>
3441Pushes onto the stack the metatable of the value at the given index.
3442If the value does not have a metatable,
3575If the value at the given index has a metatable,
3576the function pushes that metatable onto the stack and returns&nbsp;1.
3577Otherwise,
34433578the function returns&nbsp;0 and pushes nothing on the stack.
34443579
34453580
r242885r242886
34483583
34493584<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
34503585<span class="apii">[-1, +1, <em>e</em>]</span>
3451<pre>void lua_gettable (lua_State *L, int index);</pre>
3586<pre>int lua_gettable (lua_State *L, int index);</pre>
34523587
34533588<p>
34543589Pushes onto the stack the value <code>t[k]</code>,
r242885r242886
34573592
34583593
34593594<p>
3460This function pops the key from the stack
3461(putting the resulting value in its place).
3595This function pops the key from the stack,
3596pushing the resulting value in its place.
34623597As in Lua, this function may trigger a metamethod
34633598for the "index" event (see <a href="#2.4">&sect;2.4</a>).
34643599
34653600
3601<p>
3602Returns the type of the pushed value.
34663603
34673604
34683605
3606
3607
34693608<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
34703609<span class="apii">[-0, +0, &ndash;]</span>
34713610<pre>int lua_gettop (lua_State *L);</pre>
r242885r242886
34733612<p>
34743613Returns the index of the top element in the stack.
34753614Because indices start at&nbsp;1,
3476this result is equal to the number of elements in the stack
3477(and so 0&nbsp;means an empty stack).
3615this result is equal to the number of elements in the stack;
3616in particular, 0&nbsp;means an empty stack.
34783617
34793618
34803619
r242885r242886
34823621
34833622<hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p>
34843623<span class="apii">[-0, +1, &ndash;]</span>
3485<pre>void lua_getuservalue (lua_State *L, int index);</pre>
3624<pre>int lua_getuservalue (lua_State *L, int index);</pre>
34863625
34873626<p>
34883627Pushes onto the stack the Lua value associated with the userdata
34893628at the given index.
3490This Lua value must be a table or <b>nil</b>.
34913629
34923630
3631<p>
3632Returns the type of the pushed value.
34933633
34943634
34953635
3636
3637
34963638<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
34973639<span class="apii">[-1, +1, &ndash;]</span>
34983640<pre>void lua_insert (lua_State *L, int index);</pre>
r242885r242886
35083650
35093651
35103652<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3511<pre>typedef ptrdiff_t lua_Integer;</pre>
3653<pre>typedef ... lua_Integer;</pre>
35123654
35133655<p>
3514The type used by the Lua API to represent signed integral values.
3656The type of integers in Lua.
35153657
35163658
35173659<p>
3518By default it is a <code>ptrdiff_t</code>,
3519which is usually the largest signed integral type the machine handles
3520"comfortably".
3660By default this type is <code>long long</code>,
3661(usually a 64-bit two-complement integer),
3662but that can be changed to <code>long</code> or <code>int</code>
3663(usually a 32-bit two-complement integer).
3664(See <code>LUA_INT</code> in <code>luaconf.h</code>.)
35213665
35223666
3667<p>
3668Lua also defines the constants
3669<a name="pdf-LUA_MININTEGER"><code>LUA_MININTEGER</code></a> and <a name="pdf-LUA_MAXINTEGER"><code>LUA_MAXINTEGER</code></a>,
3670with the minimum and the maximum values that fit in this type.
35233671
35243672
35253673
3674
3675
35263676<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
35273677<span class="apii">[-0, +0, &ndash;]</span>
35283678<pre>int lua_isboolean (lua_State *L, int index);</pre>
r242885r242886
35593709
35603710
35613711
3712<hr><h3><a name="lua_isinteger"><code>lua_isinteger</code></a></h3><p>
3713<span class="apii">[-0, +0, &ndash;]</span>
3714<pre>int lua_isinteger (lua_State *L, int index);</pre>
3715
3716<p>
3717Returns 1 if the value at the given index is an integer
3718(that is, the value is a number and is represented as an integer),
3719and 0&nbsp;otherwise.
3720
3721
3722
3723
3724
35623725<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
35633726<span class="apii">[-0, +0, &ndash;]</span>
35643727<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
r242885r242886
36703833
36713834
36723835
3836<hr><h3><a name="lua_isyieldable"><code>lua_isyieldable</code></a></h3><p>
3837<span class="apii">[-0, +0, &ndash;]</span>
3838<pre>int lua_isyieldable (lua_State *L);</pre>
3839
3840<p>
3841Returns 1 if the given coroutine can yield,
3842and 0&nbsp;otherwise.
3843
3844
3845
3846
3847
3848<hr><h3><a name="lua_KContext"><code>lua_KContext</code></a></h3>
3849<pre>typedef ... lua_KContext;</pre>
3850
3851<p>
3852The type for continuation-function contexts.
3853It must be a numerical type.
3854This type is defined as <code>intptr_t</code>
3855when <code>intptr_t</code> is available,
3856so that it can store pointers too.
3857Otherwise, it is defined as <code>ptrdiff_t</code>.
3858
3859
3860
3861
3862
3863<hr><h3><a name="lua_KFunction"><code>lua_KFunction</code></a></h3>
3864<pre>typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);</pre>
3865
3866<p>
3867Type for continuation functions (see <a href="#4.7">&sect;4.7</a>).
3868
3869
3870
3871
3872
36733873<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
36743874<span class="apii">[-0, +1, <em>e</em>]</span>
36753875<pre>void lua_len (lua_State *L, int index);</pre>
36763876
36773877<p>
3678Returns the "length" of the value at the given index;
3679it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.6">&sect;3.4.6</a>).
3878Returns the length of the value at the given index.
3879It is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>) and
3880may trigger a metamethod for the "length" event (see <a href="#2.4">&sect;2.4</a>).
36803881The result is pushed on the stack.
36813882
36823883
r242885r242886
36883889<pre>int lua_load (lua_State *L,
36893890              lua_Reader reader,
36903891              void *data,
3691              const char *source,
3892              const char *chunkname,
36923893              const char *mode);</pre>
36933894
36943895<p>
3695Loads a Lua chunk (without running it).
3896Loads a Lua chunk without running it.
36963897If there are no errors,
36973898<code>lua_load</code> pushes the compiled chunk as a Lua
36983899function on top of the stack.
r242885r242886
37273928
37283929
37293930<p>
3730The <code>source</code> argument gives a name to the chunk,
3931The <code>chunkname</code> argument gives a name to the chunk,
37313932which is used for error messages and in debug information (see <a href="#4.9">&sect;4.9</a>).
37323933
37333934
r242885r242886
37413942
37423943<p>
37433944<code>lua_load</code> uses the stack internally,
3744so the reader function should always leave the stack
3945so the reader function must always leave the stack
37453946unmodified when returning.
37463947
37473948
37483949<p>
3749If the resulting function has one upvalue,
3750this upvalue is set to the value of the global environment
3950If the resulting function has upvalues,
3951its first upvalue is set to the value of the global environment
37513952stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">&sect;4.5</a>).
37523953When loading main chunks,
37533954this upvalue will be the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
3955Other upvalues are initialized with <b>nil</b>.
37543956
37553957
37563958
r242885r242886
37623964
37633965<p>
37643966Creates a new thread running in a new, independent state.
3765Returns <code>NULL</code> if cannot create the thread or the state
3967Returns <code>NULL</code> if it cannot create the thread or the state
37663968(due to lack of memory).
37673969The argument <code>f</code> is the allocator function;
37683970Lua does all memory allocation for this state through this function.
r242885r242886
38694071<pre>typedef double lua_Number;</pre>
38704072
38714073<p>
3872The type of numbers in Lua.
3873By default, it is double, but that can be changed in <code>luaconf.h</code>.
3874Through this configuration file you can change
3875Lua to operate with another type for numbers (e.g., float or long).
4074The type of floats in Lua.
38764075
38774076
4077<p>
4078By default this type is double,
4079but that can be changed to a single float.
4080(See <code>LUA_REAL</code> in <code>luaconf.h</code>.)
38784081
38794082
38804083
4084
4085
4086<hr><h3><a name="lua_numbertointeger"><code>lua_numbertointeger</code></a></h3>
4087<pre>int lua_numbertointeger (lua_Number n, lua_Integer *p);</pre>
4088
4089<p>
4090Converts a Lua float to a Lua integer.
4091This macro assumes that <code>n</code> has an integral value.
4092If that value is within the range of Lua integers,
4093it is converted to an integer and assigned to <code>*p</code>.
4094The macro results in a boolean indicating whether the
4095conversion was successful.
4096(Note that this range test can be tricky to do
4097correctly without this macro,
4098due to roundings.)
4099
4100
4101<p>
4102This macro may evaluate its arguments more than once.
4103
4104
4105
4106
4107
38814108<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
38824109<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
38834110<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
r242885r242886
39214148
39224149
39234150<p>
3924The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following codes
4151The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants
39254152(defined in <code>lua.h</code>):
39264153
39274154<ul>
r242885r242886
39444171
39454172<li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
39464173error while running a <code>__gc</code> metamethod.
3947(This error typically has no relation with the function being called.
3948It is generated by the garbage collector.)
4174(This error typically has no relation with the function being called.)
39494175</li>
39504176
39514177</ul>
r242885r242886
39584184<pre>int lua_pcallk (lua_State *L,
39594185                int nargs,
39604186                int nresults,
3961                int errfunc,
3962                int ctx,
3963                lua_CFunction k);</pre>
4187                int msgh,
4188                lua_KContext ctx,
4189                lua_KFunction k);</pre>
39644190
39654191<p>
39664192This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
r242885r242886
40064232thus creating a C&nbsp;closure (see <a href="#4.4">&sect;4.4</a>);
40074233these values are then accessible to the function whenever it is called.
40084234To associate values with a C&nbsp;function,
4009first these values should be pushed onto the stack
4235first these values must be pushed onto the stack
40104236(when there are multiple values, the first value is pushed first).
40114237Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
40124238is called to create and push the C&nbsp;function onto the stack,
4013with the argument <code>n</code> telling how many values should be
4239with the argument <code>n</code> telling how many values will be
40144240associated with the function.
40154241<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
40164242
r242885r242886
40234249When <code>n</code> is zero,
40244250this function creates a <em>light C function</em>,
40254251which is just a pointer to the C&nbsp;function.
4026In that case, it never throws a memory error.
4252In that case, it never raises a memory error.
40274253
40284254
40294255
r242885r242886
40654291<p>
40664292Pushes onto the stack a formatted string
40674293and returns a pointer to this string.
4068It is similar to the ANSI&nbsp;C function <code>sprintf</code>,
4294It is similar to the ISO&nbsp;C function <code>sprintf</code>,
40694295but has some important differences:
40704296
40714297<ul>
r242885r242886
40804306The conversion specifiers are quite restricted.
40814307There are no flags, widths, or precisions.
40824308The conversion specifiers can only be
4083'<code>%%</code>' (inserts a '<code>%</code>' in the string),
4309'<code>%%</code>' (inserts the character '<code>%</code>'),
40844310'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
40854311'<code>%f</code>' (inserts a <a href="#lua_Number"><code>lua_Number</code></a>),
4312'<code>%L</code>' (inserts a <a href="#lua_Integer"><code>lua_Integer</code></a>),
40864313'<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
4087'<code>%d</code>' (inserts an <code>int</code>), and
4088'<code>%c</code>' (inserts an <code>int</code> as a byte).
4314'<code>%d</code>' (inserts an <code>int</code>),
4315'<code>%c</code>' (inserts an <code>int</code> as a one-byte character), and
4316'<code>%U</code>' (inserts a <code>long int</code> as a UTF-8 byte sequence).
40894317</li>
40904318
40914319</ul>
r242885r242886
41094337<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
41104338
41114339<p>
4112Pushes a number with value <code>n</code> onto the stack.
4340Pushes an integer with value <code>n</code> onto the stack.
41134341
41144342
41154343
r242885r242886
41864414<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
41874415
41884416<p>
4189Pushes a number with value <code>n</code> onto the stack.
4417Pushes a float with value <code>n</code> onto the stack.
41904418
41914419
41924420
r242885r242886
42274455
42284456
42294457
4230<hr><h3><a name="lua_pushunsigned"><code>lua_pushunsigned</code></a></h3><p>
4231<span class="apii">[-0, +1, &ndash;]</span>
4232<pre>void lua_pushunsigned (lua_State *L, lua_Unsigned n);</pre>
4233
4234<p>
4235Pushes a number with value <code>n</code> onto the stack.
4236
4237
4238
4239
4240
42414458<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
42424459<span class="apii">[-0, +1, &ndash;]</span>
42434460<pre>void lua_pushvalue (lua_State *L, int index);</pre>
r242885r242886
42734490<code>index2</code> are primitively equal
42744491(that is, without calling metamethods).
42754492Otherwise returns&nbsp;0.
4276Also returns&nbsp;0 if any of the indices are non valid.
4493Also returns&nbsp;0 if any of the indices are not valid.
42774494
42784495
42794496
r242885r242886
42814498
42824499<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
42834500<span class="apii">[-1, +1, &ndash;]</span>
4284<pre>void lua_rawget (lua_State *L, int index);</pre>
4501<pre>int lua_rawget (lua_State *L, int index);</pre>
42854502
42864503<p>
42874504Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
r242885r242886
42934510
42944511<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
42954512<span class="apii">[-0, +1, &ndash;]</span>
4296<pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
4513<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
42974514
42984515<p>
42994516Pushes onto the stack the value <code>t[n]</code>,
r242885r242886
43024519that is, it does not invoke metamethods.
43034520
43044521
4522<p>
4523Returns the type of the pushed value.
43054524
43064525
43074526
4527
4528
43084529<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
43094530<span class="apii">[-0, +1, &ndash;]</span>
4310<pre>void lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4531<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
43114532
43124533<p>
43134534Pushes onto the stack the value <code>t[k]</code>,
r242885r242886
43174538that is, it does not invoke metamethods.
43184539
43194540
4541<p>
4542Returns the type of the pushed value.
43204543
43214544
43224545
4546
4547
43234548<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
43244549<span class="apii">[-0, +0, &ndash;]</span>
43254550<pre>size_t lua_rawlen (lua_State *L, int index);</pre>
r242885r242886
43514576
43524577<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
43534578<span class="apii">[-1, +0, <em>e</em>]</span>
4354<pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
4579<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
43554580
43564581<p>
4357Does the equivalent of <code>t[n] = v</code>,
4582Does the equivalent of <code>t[i] = v</code>,
43584583where <code>t</code> is the table at the given index
43594584and <code>v</code> is the value at the top of the stack.
43604585
r242885r242886
45014726
45024727
45034728
4729<hr><h3><a name="lua_rotate"><code>lua_rotate</code></a></h3><p>
4730<span class="apii">[-0, +0, &ndash;]</span>
4731<pre>void lua_rotate (lua_State *L, int idx, int n);</pre>
4732
4733<p>
4734Rotates the stack elements from <code>idx</code> to the top <code>n</code> positions
4735in the direction of the top, for a positive <code>n</code>,
4736or <code>-n</code> positions in the direction of the bottom,
4737for a negative <code>n</code>.
4738The absolute value of <code>n</code> must not be greater than the size
4739of the slice being rotated.
4740
4741
4742
4743
4744
45044745<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
45054746<span class="apii">[-0, +0, &ndash;]</span>
45064747<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
r242885r242886
45444785
45454786
45464787
4788<hr><h3><a name="lua_seti"><code>lua_seti</code></a></h3><p>
4789<span class="apii">[-1, +0, <em>e</em>]</span>
4790<pre>void lua_seti (lua_State *L, int index, lua_Integer n);</pre>
4791
4792<p>
4793Does the equivalent to <code>t[n] = v</code>,
4794where <code>t</code> is the value at the given index
4795and <code>v</code> is the value at the top of the stack.
4796
4797
4798<p>
4799This function pops the value from the stack.
4800As in Lua, this function may trigger a metamethod
4801for the "newindex" event (see <a href="#2.4">&sect;2.4</a>).
4802
4803
4804
4805
4806
45474807<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
45484808<span class="apii">[-1, +0, &ndash;]</span>
45494809<pre>void lua_setmetatable (lua_State *L, int index);</pre>
r242885r242886
45964856<pre>void lua_setuservalue (lua_State *L, int index);</pre>
45974857
45984858<p>
4599Pops a table or <b>nil</b> from the stack and sets it as
4859Pops a value from the stack and sets it as
46004860the new value associated to the userdata at the given index.
46014861
46024862
r242885r242886
46484908
46494909
46504910
4911<hr><h3><a name="lua_stringtonumber"><code>lua_stringtonumber</code></a></h3><p>
4912<span class="apii">[-0, +1, &ndash;]</span>
4913<pre>size_t lua_stringtonumber (lua_State *L, const char *s);</pre>
4914
4915<p>
4916Converts the zero-terminated string <code>s</code> to a number,
4917pushes that number into the stack,
4918and returns the total size of the string,
4919that is, its length plus one.
4920The conversion can result in an integer or a float,
4921according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
4922The string may have leading and trailing spaces and a sign.
4923If the string is not a valid numeral,
4924returns 0 and pushes nothing.
4925(Note that the result can be used as a boolean,
4926true if the conversion succeeds.)
4927
4928
4929
4930
4931
46514932<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
46524933<span class="apii">[-0, +0, &ndash;]</span>
46534934<pre>int lua_toboolean (lua_State *L, int index);</pre>
r242885r242886
46974978<p>
46984979Converts the Lua value at the given index
46994980to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></a>.
4700The Lua value must be a number or a string convertible to a number
4701(see <a href="#3.4.2">&sect;3.4.2</a>);
4981The Lua value must be an integer,
4982or a number or string convertible to an integer (see <a href="#3.4.3">&sect;3.4.3</a>);
47024983otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
47034984
47044985
47054986<p>
4706If the number is not an integer,
4707it is truncated in some non-specified way.
4708
4709
4710<p>
47114987If <code>isnum</code> is not <code>NULL</code>,
47124988its referent is assigned a boolean value that
47134989indicates whether the operation succeeded.
r242885r242886
47395015This string always has a zero ('<code>\0</code>')
47405016after its last character (as in&nbsp;C),
47415017but can contain other zeros in its body.
5018
5019
5020<p>
47425021Because Lua has garbage collection,
47435022there is no guarantee that the pointer returned by <code>lua_tolstring</code>
4744will be valid after the corresponding value is removed from the stack.
5023will be valid after the corresponding Lua value is removed from the stack.
47455024
47465025
47475026
r242885r242886
47665045Converts the Lua value at the given index
47675046to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
47685047The Lua value must be a number or a string convertible to a number
4769(see <a href="#3.4.2">&sect;3.4.2</a>);
5048(see <a href="#3.4.3">&sect;3.4.3</a>);
47705049otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
47715050
47725051
r242885r242886
48245103
48255104
48265105
4827<hr><h3><a name="lua_tounsigned"><code>lua_tounsigned</code></a></h3><p>
4828<span class="apii">[-0, +0, &ndash;]</span>
4829<pre>lua_Unsigned lua_tounsigned (lua_State *L, int index);</pre>
4830
4831<p>
4832Equivalent to <a href="#lua_tounsignedx"><code>lua_tounsignedx</code></a> with <code>isnum</code> equal to <code>NULL</code>.
4833
4834
4835
4836
4837
4838<hr><h3><a name="lua_tounsignedx"><code>lua_tounsignedx</code></a></h3><p>
4839<span class="apii">[-0, +0, &ndash;]</span>
4840<pre>lua_Unsigned lua_tounsignedx (lua_State *L, int index, int *isnum);</pre>
4841
4842<p>
4843Converts the Lua value at the given index
4844to the unsigned integral type <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
4845The Lua value must be a number or a string convertible to a number
4846(see <a href="#3.4.2">&sect;3.4.2</a>);
4847otherwise, <code>lua_tounsignedx</code> returns&nbsp;0.
4848
4849
4850<p>
4851If the number is not an integer,
4852it is truncated in some non-specified way.
4853If the number is outside the range of representable values,
4854it is normalized to the remainder of its division by
4855one more than the maximum representable value.
4856
4857
4858<p>
4859If <code>isnum</code> is not <code>NULL</code>,
4860its referent is assigned a boolean value that
4861indicates whether the operation succeeded.
4862
4863
4864
4865
4866
48675106<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
48685107<span class="apii">[-0, +0, &ndash;]</span>
48695108<pre>void *lua_touserdata (lua_State *L, int index);</pre>
r242885r242886
49165155
49175156
49185157<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
4919<pre>typedef unsigned long lua_Unsigned;</pre>
5158<pre>typedef ... lua_Unsigned;</pre>
49205159
49215160<p>
4922The type used by the Lua API to represent unsigned integral values.
4923It must have at least 32 bits.
5161The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
49245162
49255163
4926<p>
4927By default it is an <code>unsigned int</code> or an <code>unsigned long</code>,
4928whichever can hold 32-bit values.
49295164
49305165
49315166
4932
4933
49345167<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
49355168<span class="apii">[-0, +0, &ndash;]</span>
49365169<pre>int lua_upvalueindex (int i);</pre>
r242885r242886
50005233
50015234
50025235<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5003<span class="apii">[-?, +?, &ndash;]</span>
5236<span class="apii">[-?, +?, <em>e</em>]</span>
50045237<pre>int lua_yield (lua_State *L, int nresults);</pre>
50055238
50065239<p>
50075240This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
50085241but it has no continuation (see <a href="#4.7">&sect;4.7</a>).
50095242Therefore, when the thread resumes,
5010it returns to the function that called
5243it continues the function that called
50115244the function calling <code>lua_yield</code>.
50125245
50135246
r242885r242886
50155248
50165249
50175250<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
5018<span class="apii">[-?, +?, &ndash;]</span>
5019<pre>int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k);</pre>
5251<span class="apii">[-?, +?, <em>e</em>]</span>
5252<pre>int lua_yieldk (lua_State *L,
5253                int nresults,
5254                lua_KContext ctx,
5255                lua_KFunction k);</pre>
50205256
50215257<p>
5022Yields a coroutine.
5258Yields a coroutine (thread).
50235259
50245260
50255261<p>
5026This function should only be called as the
5027return expression of a C&nbsp;function, as follows:
5028
5029<pre>
5030     return lua_yieldk (L, n, i, k);
5031</pre><p>
5032When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a> in that way,
5262When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
50335263the running coroutine suspends its execution,
50345264and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
50355265The parameter <code>nresults</code> is the number of values from the stack
5036that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5266that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
50375267
50385268
50395269<p>
r242885r242886
50425272the execution of the C function that yielded (see <a href="#4.7">&sect;4.7</a>).
50435273This continuation function receives the same stack
50445274from the previous function,
5045with the results removed and
5275with the <code>n</code> results removed and
50465276replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
50475277Moreover,
5048the continuation function may access the value <code>ctx</code>
5049by calling <a href="#lua_getctx"><code>lua_getctx</code></a>.
5278the continuation function receives the value <code>ctx</code>
5279that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
50505280
50515281
5282<p>
5283Usually, this function does not return;
5284when the coroutine eventually resumes,
5285it continues executing the continuation function.
5286However, there is one special case,
5287which is when this function is called
5288from inside a line hook (see <a href="#4.9">&sect;4.9</a>).
5289In that case, <code>lua_yieldk</code> should be called with no continuation
5290(probably in the form of <a href="#lua_yield"><code>lua_yield</code></a>),
5291and the hook should return immediately after the call.
5292Lua will yield and,
5293when the coroutine resumes again,
5294it will continue the normal execution
5295of the (Lua) function that triggered the hook.
50525296
50535297
5298<p>
5299This function can raise an error if it is called from a thread
5300with a pending C call with no continuation function,
5301or it is called from a thread that is not running inside a resume
5302(e.g., the main thread).
50545303
50555304
50565305
5306
5307
5308
5309
50575310<h2>4.9 &ndash; <a name="4.9">The Debug Interface</a></h2>
50585311
50595312<p>
r242885r242886
51005353<ul>
51015354
51025355<li><b><code>source</code>: </b>
5103the source of the chunk that created the function.
5356the name of the chunk that created the function.
51045357If <code>source</code> starts with a '<code>@</code>',
51055358it means that the function was defined in a file where
51065359the file name follows the '<code>@</code>'.
r242885r242886
52795532(A <em>valid line</em> is a line with some associated code,
52805533that is, a line where you can put a break point.
52815534Non-valid lines include empty lines and comments.)
5535
5536
5537<p>
5538If this option is given together with option '<code>f</code>',
5539its table is pushed after the function.
52825540</li>
52835541
52845542</ul>
r242885r242886
52935551
52945552<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
52955553<span class="apii">[-0, +(0|1), &ndash;]</span>
5296<pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
5554<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
52975555
52985556<p>
52995557Gets information about a local variable of
r242885r242886
53165574
53175575
53185576<p>
5319In the second case, <code>ar</code> should be <code>NULL</code> and the function
5577In the second case, <code>ar</code> must be <code>NULL</code> and the function
53205578to be inspected must be at the top of the stack.
53215579In this case, only parameters of Lua functions are visible
53225580(as there is no information about what variables are active)
r242885r242886
54335691
54345692<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
54355693<span class="apii">[-0, +0, &ndash;]</span>
5436<pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
5694<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
54375695
54385696<p>
54395697Sets the debugging hook function.
r242885r242886
54865744
54875745<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
54885746<span class="apii">[-(0|1), +0, &ndash;]</span>
5489<pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
5747<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
54905748
54915749<p>
54925750Sets the value of a local variable of a given activation record.
r242885r242886
55325790<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
55335791
55345792<p>
5535Returns an unique identifier for the upvalue numbered <code>n</code>
5793Returns a unique identifier for the upvalue numbered <code>n</code>
55365794from the closure at index <code>funcindex</code>.
55375795Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
55385796(see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>)
r242885r242886
56095867
56105868<p>
56115869Functions called <code>luaL_check*</code>
5612always throw an error if the check is not satisfied.
5870always raise an error if the check is not satisfied.
56135871
56145872
56155873
r242885r242886
56685926Adds the zero-terminated string pointed to by <code>s</code>
56695927to the buffer <code>B</code>
56705928(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5671The string cannot contain embedded zeros.
56725929
56735930
56745931
r242885r242886
57035960
57045961<p>
57055962Checks whether <code>cond</code> is true.
5706If not, raises an error with a standard message.
5963If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
57075964
57085965
57095966
r242885r242886
57145971<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
57155972
57165973<p>
5717Raises an error with a standard message
5718that includes <code>extramsg</code> as a comment.
5974Raises an error reporting a problem with argument <code>arg</code>
5975of the C function that called it,
5976using a standard message
5977that includes <code>extramsg</code> as a comment:
57195978
5979<pre>
5980     bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
5981</pre><p>
5982This function never returns.
57205983
5721<p>
5722This function never returns,
5723but it is an idiom to use it in C&nbsp;functions
5724as <code>return luaL_argerror(<em>args</em>)</code>.
57255984
57265985
57275986
57285987
5729
57305988<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
57315989<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
57325990
r242885r242886
58566114
58576115
58586116
5859<hr><h3><a name="luaL_checkint"><code>luaL_checkint</code></a></h3><p>
5860<span class="apii">[-0, +0, <em>v</em>]</span>
5861<pre>int luaL_checkint (lua_State *L, int arg);</pre>
5862
5863<p>
5864Checks whether the function argument <code>arg</code> is a number
5865and returns this number cast to an <code>int</code>.
5866
5867
5868
5869
5870
58716117<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
58726118<span class="apii">[-0, +0, <em>v</em>]</span>
58736119<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
58746120
58756121<p>
5876Checks whether the function argument <code>arg</code> is a number
5877and returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
6122Checks whether the function argument <code>arg</code> is an integer
6123(or can be converted to an integer)
6124and returns this integer cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
58786125
58796126
58806127
58816128
58826129
5883<hr><h3><a name="luaL_checklong"><code>luaL_checklong</code></a></h3><p>
5884<span class="apii">[-0, +0, <em>v</em>]</span>
5885<pre>long luaL_checklong (lua_State *L, int arg);</pre>
5886
5887<p>
5888Checks whether the function argument <code>arg</code> is a number
5889and returns this number cast to a <code>long</code>.
5890
5891
5892
5893
5894
58956130<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
58966131<span class="apii">[-0, +0, <em>v</em>]</span>
58976132<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
r242885r242886
60106245
60116246
60126247
6013<hr><h3><a name="luaL_checkunsigned"><code>luaL_checkunsigned</code></a></h3><p>
6014<span class="apii">[-0, +0, <em>v</em>]</span>
6015<pre>lua_Unsigned luaL_checkunsigned (lua_State *L, int arg);</pre>
6016
6017<p>
6018Checks whether the function argument <code>arg</code> is a number
6019and returns this number cast to a <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
6020
6021
6022
6023
6024
60256248<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
60266249<span class="apii">[-0, +0, &ndash;]</span>
60276250<pre>void luaL_checkversion (lua_State *L);</pre>
r242885r242886
61296352
61306353<p>
61316354Pushes onto the stack the field <code>e</code> from the metatable
6132of the object at index <code>obj</code>.
6355of the object at index <code>obj</code> and returns the type of pushed value.
61336356If the object does not have a metatable,
61346357or if the metatable does not have this field,
6135returns false and pushes nothing.
6358pushes nothing and returns <code>LUA_TNIL</code>.
61366359
61376360
61386361
r242885r242886
61406363
61416364<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
61426365<span class="apii">[-0, +1, &ndash;]</span>
6143<pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
6366<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
61446367
61456368<p>
61466369Pushes onto the stack the metatable associated with name <code>tname</code>
61476370in the registry (see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6371If there is no metatable associated with <code>tname</code>,
6372returns false and pushes <b>nil</b>.
61486373
61496374
61506375
r242885r242886
61856410
61866411<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
61876412<span class="apii">[-0, +0, <em>e</em>]</span>
6188<pre>int luaL_len (lua_State *L, int index);</pre>
6413<pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
61896414
61906415<p>
61916416Returns the "length" of the value at the given index
61926417as a number;
6193it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.6">&sect;3.4.6</a>).
6194Raises an error if the result of the operation is not a number.
6418it is equivalent to the '<code>#</code>' operator in Lua (see <a href="#3.4.7">&sect;3.4.7</a>).
6419Raises an error if the result of the operation is not an integer.
61956420(This case only can happen through metamethods.)
61966421
61976422
r242885r242886
63036528
63046529<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
63056530<span class="apii">[-0, +1, <em>e</em>]</span>
6306<pre>void luaL_newlib (lua_State *L, const luaL_Reg *l);</pre>
6531<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
63076532
63086533<p>
63096534Creates a new table and registers there
63106535the functions in list <code>l</code>.
6536
6537
6538<p>
63116539It is implemented as the following macro:
63126540
63136541<pre>
63146542     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
6315</pre>
6543</pre><p>
6544The array <code>l</code> must be the actual array,
6545not a pointer to it.
63166546
63176547
63186548
63196549
6550
63206551<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
63216552<span class="apii">[-0, +1, <em>e</em>]</span>
63226553<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
r242885r242886
63476578returns 0.
63486579Otherwise,
63496580creates a new table to be used as a metatable for userdata,
6350adds it to the registry with key <code>tname</code>,
6581adds to this new table the pair <code>__name = tname</code>,
6582adds to the registry the pair <code>[tname] = new table</code>,
63516583and returns 1.
6584(The entry <code>__name</code> is used by some error-reporting functions.)
63526585
63536586
63546587<p>
r242885r242886
63916624
63926625
63936626
6394<hr><h3><a name="luaL_optint"><code>luaL_optint</code></a></h3><p>
6395<span class="apii">[-0, +0, <em>v</em>]</span>
6396<pre>int luaL_optint (lua_State *L, int arg, int d);</pre>
6397
6398<p>
6399If the function argument <code>arg</code> is a number,
6400returns this number cast to an <code>int</code>.
6401If this argument is absent or is <b>nil</b>,
6402returns <code>d</code>.
6403Otherwise, raises an error.
6404
6405
6406
6407
6408
64096627<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
64106628<span class="apii">[-0, +0, <em>v</em>]</span>
64116629<pre>lua_Integer luaL_optinteger (lua_State *L,
r242885r242886
64136631                             lua_Integer d);</pre>
64146632
64156633<p>
6416If the function argument <code>arg</code> is a number,
6417returns this number cast to a <a href="#lua_Integer"><code>lua_Integer</code></a>.
6634If the function argument <code>arg</code> is an integer
6635(or convertible to an integer),
6636returns this integer.
64186637If this argument is absent or is <b>nil</b>,
64196638returns <code>d</code>.
64206639Otherwise, raises an error.
r242885r242886
64236642
64246643
64256644
6426<hr><h3><a name="luaL_optlong"><code>luaL_optlong</code></a></h3><p>
6427<span class="apii">[-0, +0, <em>v</em>]</span>
6428<pre>long luaL_optlong (lua_State *L, int arg, long d);</pre>
6429
6430<p>
6431If the function argument <code>arg</code> is a number,
6432returns this number cast to a <code>long</code>.
6433If this argument is absent or is <b>nil</b>,
6434returns <code>d</code>.
6435Otherwise, raises an error.
6436
6437
6438
6439
6440
64416645<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
64426646<span class="apii">[-0, +0, <em>v</em>]</span>
64436647<pre>const char *luaL_optlstring (lua_State *L,
r242885r242886
64936697
64946698
64956699
6496<hr><h3><a name="luaL_optunsigned"><code>luaL_optunsigned</code></a></h3><p>
6497<span class="apii">[-0, +0, <em>v</em>]</span>
6498<pre>lua_Unsigned luaL_optunsigned (lua_State *L,
6499                               int arg,
6500                               lua_Unsigned u);</pre>
6501
6502<p>
6503If the function argument <code>arg</code> is a number,
6504returns this number cast to a <a href="#lua_Unsigned"><code>lua_Unsigned</code></a>.
6505If this argument is absent or is <b>nil</b>,
6506returns <code>u</code>.
6507Otherwise, raises an error.
6508
6509
6510
6511
6512
65136700<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
65146701<span class="apii">[-?, +?, <em>e</em>]</span>
65156702<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
r242885r242886
66016788<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
66026789<code>name</code> is the function name and <code>func</code> is a pointer to
66036790the function.
6604Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
6791Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
66056792in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
66066793
66076794
r242885r242886
66146801                    lua_CFunction openf, int glb);</pre>
66156802
66166803<p>
6617Calls function <code>openf</code> with string <code>modname</code> as an argument
6804If <code>modname</code> is not already present in <a href="#pdf-package.loaded"><code>package.loaded</code></a>,
6805calls function <code>openf</code> with string <code>modname</code> as an argument
66186806and sets the call result in <code>package.loaded[modname]</code>,
66196807as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
66206808
66216809
66226810<p>
66236811If <code>glb</code> is true,
6624also stores the result into global <code>modname</code>.
6812also stores the module into global <code>modname</code>.
66256813
66266814
66276815<p>
6628Leaves a copy of that result on the stack.
6816Leaves a copy of the module on the stack.
66296817
66306818
66316819
r242885r242886
66656853
66666854
66676855
6856<hr><h3><a name="luaL_Stream"><code>luaL_Stream</code></a></h3>
6857<pre>typedef struct luaL_Stream {
6858  FILE *f;
6859  lua_CFunction closef;
6860} luaL_Stream;</pre>
6861
6862<p>
6863The standard representation for file handles,
6864which is used by the standard I/O library.
6865
6866
6867<p>
6868A file handle is implemented as a full userdata,
6869with a metatable called <code>LUA_FILEHANDLE</code>
6870(where <code>LUA_FILEHANDLE</code> is a macro with the actual metatable's name).
6871The metatable is created by the I/O library
6872(see <a href="#luaL_newmetatable"><code>luaL_newmetatable</code></a>).
6873
6874
6875<p>
6876This userdata must start with the structure <code>luaL_Stream</code>;
6877it can contain other data after this initial structure.
6878Field <code>f</code> points to the corresponding C stream
6879(or it can be <code>NULL</code> to indicate an incompletely created handle).
6880Field <code>closef</code> points to a Lua function
6881that will be called to close the stream
6882when the handle is closed or collected;
6883this function receives the file handle as its sole argument and
6884must return either <b>true</b> (in case of success)
6885or <b>nil</b> plus an error message (in case of error).
6886Once Lua calls this field,
6887the field value is changed to <code>NULL</code>
6888to signal that the handle is closed.
6889
6890
6891
6892
6893
66686894<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
66696895<span class="apii">[-0, +0, <em>e</em>]</span>
66706896<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
r242885r242886
66726898<p>
66736899This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
66746900except that, when the test fails,
6675it returns <code>NULL</code> instead of throwing an error.
6901it returns <code>NULL</code> instead of raising an error.
66766902
66776903
66786904
r242885r242886
68027028
68037029<li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
68047030
6805<li>table manipulation (<a href="#6.5">&sect;6.5</a>);</li>
7031<li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
68067032
6807<li>mathematical functions (<a href="#6.6">&sect;6.6</a>) (sin, log, etc.);</li>
7033<li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
68087034
6809<li>bitwise operations (<a href="#6.7">&sect;6.7</a>);</li>
7035<li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
68107036
68117037<li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
68127038
r242885r242886
68317057<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
68327058<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
68337059<a name="pdf-luaopen_string"><code>luaopen_string</code></a> (for the string library),
7060<a name="pdf-luaopen_utf8"><code>luaopen_utf8</code></a> (for the UTF8 library),
68347061<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
68357062<a name="pdf-luaopen_math"><code>luaopen_math</code></a> (for the mathematical library),
6836<a name="pdf-luaopen_bit32"><code>luaopen_bit32</code></a> (for the bit library),
68377063<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
6838<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the Operating System library),
7064<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
68397065and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
68407066These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
68417067
r242885r242886
68527078
68537079<p>
68547080<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
6855Issues an  error when
7081
7082
7083<p>
7084Calls <a href="#pdf-error"><code>error</code></a> if
68567085the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
68577086otherwise, returns all its arguments.
6858<code>message</code> is an error message;
6859when absent, it defaults to "assertion failed!"
7087In case of error,
7088<code>message</code> is the error object;
7089when absent, it defaults to "<code>assertion failed!</code>"
68607090
68617091
68627092
r242885r242886
68877117</li>
68887118
68897119<li><b>"<code>count</code>": </b>
6890returns the total memory in use by Lua (in Kbytes) and
6891a second value with the total memory in bytes modulo 1024.
6892The first value has a fractional part,
6893so the following equality is always true:
6894
6895<pre>
6896     k, b = collectgarbage("count")
6897     assert(k*1024 == math.floor(k)*1024 + b)
6898</pre><p>
6899(The second result is useful when Lua is compiled
6900with a non floating-point type for numbers.)
7120returns the total memory in use by Lua in Kbytes.
7121The value has a fractional part,
7122so that it multiplied by 1024
7123gives the exact number of bytes in use by Lua
7124(except for overflows).
69017125</li>
69027126
69037127<li><b>"<code>step</code>": </b>
69047128performs a garbage-collection step.
6905The step "size" is controlled by <code>arg</code>
6906(larger values mean more steps) in a non-specified way.
6907If you want to control the step size
6908you must experimentally tune the value of <code>arg</code>.
7129The step "size" is controlled by <code>arg</code>.
7130With a zero value,
7131the collector will perform one basic (indivisible) step.
7132For non-zero values,
7133the collector will perform as if that amount of memory
7134(in KBytes) had been allocated by Lua.
69097135Returns <b>true</b> if the step finished a collection cycle.
69107136</li>
69117137
r242885r242886
69267152(i.e., not stopped).
69277153</li>
69287154
6929<li><b>"<code>generational</code>": </b>
6930changes the collector to generational mode.
6931This is an experimental feature (see <a href="#2.5">&sect;2.5</a>).
6932</li>
6933
6934<li><b>"<code>incremental</code>": </b>
6935changes the collector to incremental mode.
6936This is the default mode.
6937</li>
6938
69397155</ul>
69407156
69417157
r242885r242886
69557171<p>
69567172<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
69577173Terminates the last protected function called
6958and returns <code>message</code> as the error message.
7174and returns <code>message</code> as the error object.
69597175Function <code>error</code> never returns.
69607176
69617177
r242885r242886
69797195holds the global environment (see <a href="#2.2">&sect;2.2</a>).
69807196Lua itself does not use this variable;
69817197changing its value does not affect any environment,
6982nor vice-versa.
7198nor vice versa.
69837199
69847200
69857201
r242885r242886
70037219
70047220
70057221<p>
7006If <code>t</code> has a metamethod <code>__ipairs</code>,
7007calls it with <code>t</code> as argument and returns the first three
7008results from the call.
7009
7010
7011<p>
7012Otherwise,
7013returns three values: an iterator function, the table <code>t</code>, and 0,
7222Returns three values (an iterator function, the table <code>t</code>, and 0)
70147223so that the construction
70157224
70167225<pre>
70177226     for i,v in ipairs(t) do <em>body</em> end
70187227</pre><p>
7019will iterate over the pairs (<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7020up to the first integer key absent from the table.
7228will iterate over the key&ndash;value pairs
7229(<code>1,t[1]</code>), (<code>2,t[2]</code>), ...,
7230up to the first nil value.
70217231
70227232
70237233
70247234
70257235<p>
7026<hr><h3><a name="pdf-load"><code>load (ld [, source [, mode [, env]]])</code></a></h3>
7236<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
70277237
70287238
70297239<p>
r242885r242886
70317241
70327242
70337243<p>
7034If <code>ld</code> is a string, the chunk is this string.
7035If <code>ld</code> is a function,
7244If <code>chunk</code> is a string, the chunk is this string.
7245If <code>chunk</code> is a function,
70367246<code>load</code> calls it repeatedly to get the chunk pieces.
7037Each call to <code>ld</code> must return a string that concatenates
7247Each call to <code>chunk</code> must return a string that concatenates
70387248with previous results.
70397249A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
70407250
r242885r242886
70507260the first upvalue is set to the value of <code>env</code>,
70517261if that parameter is given,
70527262or to the value of the global environment.
7263Other upvalues are initialized with <b>nil</b>.
70537264(When you load a main chunk,
70547265the resulting function will always have exactly one upvalue,
70557266the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
7056When you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
7057the resulting function can have arbitrary upvalues.)
7267However,
7268when you load a binary chunk created from a function (see <a href="#pdf-string.dump"><code>string.dump</code></a>),
7269the resulting function can have an arbitrary number of upvalues.)
7270All upvalues are fresh, that is,
7271they are not shared with any other function.
70587272
70597273
70607274<p>
7061<code>source</code> is used as the source of the chunk for error messages
7275<code>chunkname</code> is used as the name of the chunk for error messages
70627276and debug information (see <a href="#4.9">&sect;4.9</a>).
70637277When absent,
7064it defaults to <code>ld</code>, if <code>ld</code> is a string,
7278it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
70657279or to "<code>=(load)</code>" otherwise.
70667280
70677281
r242885r242886
70747288The default is "<code>bt</code>".
70757289
70767290
7291<p>
7292Lua does not check the consistency of binary chunks.
7293Maliciously crafted binary chunks can crash
7294the interpreter.
70777295
70787296
7297
7298
70797299<p>
70807300<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
70817301
r242885r242886
72127432Returns the length of the object <code>v</code>,
72137433which must be a table or a string,
72147434without invoking any metamethod.
7215Returns an integer number.
7435Returns an integer.
72167436
72177437
72187438
r242885r242886
72737493When called with no <code>base</code>,
72747494<code>tonumber</code> tries to convert its argument to a number.
72757495If the argument is already a number or
7276a string convertible to a number (see <a href="#3.4.2">&sect;3.4.2</a>),
7496a string convertible to a number,
72777497then <code>tonumber</code> returns this number;
72787498otherwise, it returns <b>nil</b>.
72797499
72807500
72817501<p>
7502The conversion of strings can result in integers or floats,
7503according to the lexical conventions of Lua (see <a href="#3.1">&sect;3.1</a>).
7504(The string may have leading and trailing spaces and a sign.)
7505
7506
7507<p>
72827508When called with <code>base</code>,
7283then <code>e</code> should be a string to be interpreted as
7509then <code>e</code> must be a string to be interpreted as
72847510an integer numeral in that base.
72857511The base may be any integer between 2 and 36, inclusive.
72867512In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
r242885r242886
72957521<p>
72967522<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
72977523Receives a value of any type and
7298converts it to a string in a reasonable format.
7524converts it to a string in a human-readable format.
7525Floats always produce strings with some
7526floating-point indication (either a decimal dot or an exponent).
72997527(For complete control of how numbers are converted,
73007528use <a href="#pdf-string.format"><code>string.format</code></a>.)
73017529
r242885r242886
73297557<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
73307558A global variable (not a function) that
73317559holds a string containing the current interpreter version.
7332The current contents of this variable is "<code>Lua 5.2</code>".
7560The current value of this variable is "<code>Lua 5.3</code>".
73337561
73347562
73357563
r242885r242886
73707598
73717599
73727600<p>
7601<hr><h3><a name="pdf-coroutine.isyieldable"><code>coroutine.isyieldable ()</code></a></h3>
7602
7603
7604<p>
7605Returns true when the running coroutine can yield.
7606
7607
7608<p>
7609A running coroutine is yieldable if it is not the main thread and
7610it is not inside a non-yieldable C function.
7611
7612
7613
7614
7615<p>
73737616<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
73747617
73757618
r242885r242886
73887631<p>
73897632If the coroutine runs without any errors,
73907633<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
7391(if the coroutine yields) or any values returned by the body function
7392(if the coroutine terminates).
7634(when the coroutine yields) or any values returned by the body function
7635(when the coroutine terminates).
73937636If there is any error,
73947637<code>resume</code> returns <b>false</b> plus the error message.
73957638
r242885r242886
74917734<p>
74927735First <code>require</code> queries <code>package.preload[modname]</code>.
74937736If it has a value,
7494this value (which should be a function) is the loader.
7737this value (which must be a function) is the loader.
74957738Otherwise <code>require</code> searches for a Lua loader using the
74967739path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
74977740If that also fails, it searches for a C&nbsp;loader using the
r242885r242886
75477790is replaced by the executable's directory.
75487791Default is '<code>!</code>'.</li>
75497792
7550<li>The fifth line is a mark to ignore all text before it
7793<li>The fifth line is a mark to ignore all text after it
75517794when building the <code>luaopen_</code> function name.
75527795Default is '<code>-</code>'.</li>
75537796
r242885r242886
75667809<p>
75677810Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
75687811it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
7569using the environment variable <a name="pdf-LUA_CPATH_5_2"><code>LUA_CPATH_5_2</code></a>
7812using the environment variable <a name="pdf-LUA_CPATH_5_3"><code>LUA_CPATH_5_3</code></a>
75707813or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
75717814or a default path defined in <code>luaconf.h</code>.
75727815
r242885r242886
76447887
76457888<p>
76467889At start-up, Lua initializes this variable with
7647the value of the environment variable <a name="pdf-LUA_PATH_5_2"><code>LUA_PATH_5_2</code></a> or
7890the value of the environment variable <a name="pdf-LUA_PATH_5_3"><code>LUA_PATH_5_3</code></a> or
76487891the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
76497892with a default path defined in <code>luaconf.h</code>,
76507893if those environment variables are not defined.
r242885r242886
77297972concatenated with a copy of the module name where each dot
77307973is replaced by an underscore.
77317974Moreover, if the module name has a hyphen,
7732its prefix up to (and including) the first hyphen is removed.
7733For instance, if the module name is <code>a.v1-b.c</code>,
7734the function name will be <code>luaopen_b_c</code>.
7975its suffix after (and including) the first hyphen is removed.
7976For instance, if the module name is <code>a.b.c-v2.1</code>,
7977the function name will be <code>luaopen_a_b_c</code>.
77357978
77367979
77377980<p>
r242885r242886
78598102
78608103
78618104<p>
7862<hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
8105<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
78638106
78648107
78658108<p>
7866Returns a string containing a binary representation of the given function,
8109Returns a string containing a binary representation
8110(a <em>binary chunk</em>)
8111of the given function,
78678112so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
78688113a copy of the function (but with new upvalues).
8114If <code>strip</code> is a true value,
8115the binary representation is created without debug information
8116about the function
8117(local variable names, lines, etc.).
78698118
78708119
8120<p>
8121Functions with upvalues have only their number of upvalues saved.
8122When (re)loaded,
8123those upvalues receive fresh instances containing <b>nil</b>.
8124(You can use the debug library to serialize
8125and reload the upvalues of a function
8126in a way adequate to your needs.)
78718127
78728128
8129
8130
78738131<p>
78748132<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
78758133
78768134
78778135<p>
78788136Looks for the first match of
7879<code>pattern</code> in the string <code>s</code>.
8137<code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
78808138If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
78818139where this occurrence starts and ends;
78828140otherwise, it returns <b>nil</b>.
r242885r242886
79068164<p>
79078165Returns a formatted version of its variable number of arguments
79088166following the description given in its first argument (which must be a string).
7909The format string follows the same rules as the ANSI&nbsp;C function <code>sprintf</code>.
8167The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
79108168The only differences are that the options/modifiers
79118169<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>,
79128170and <code>p</code> are not supported
r242885r242886
79338191<code>G</code>, and <code>g</code> all expect a number as argument.
79348192Options <code>c</code>, <code>d</code>,
79358193<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
7936also expect a number,
7937but the range of that number may be limited by
7938the underlying C&nbsp;implementation.
7939For options <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>,
7940the number cannot be negative.
8194expect an integer.
79418195Option <code>q</code> expects a string;
79428196option <code>s</code> expects a string without embedded zeros.
79438197If the argument to option <code>s</code> is not a string,
r242885r242886
79508204<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
79518205Returns an iterator function that,
79528206each time it is called,
7953returns the next captures from <code>pattern</code> over the string <code>s</code>.
8207returns the next captures from <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>)
8208over the string <code>s</code>.
79548209If <code>pattern</code> specifies no captures,
79558210then the whole match is produced in each call.
79568211
r242885r242886
79888243<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
79898244Returns a copy of <code>s</code>
79908245in which all (or the first <code>n</code>, if given)
7991occurrences of the <code>pattern</code> have been
8246occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
79928247replaced by a replacement string specified by <code>repl</code>,
79938248which can be a string, a table, or a function.
79948249<code>gsub</code> also returns, as its second value,
r242885r242886
80538308         end)
80548309     --&gt; x="4+5 = 9"
80558310     
8056     local t = {name="lua", version="5.2"}
8311     local t = {name="lua", version="5.3"}
80578312     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
8058     --&gt; x="lua-5.2.tar.gz"
8313     --&gt; x="lua-5.3.tar.gz"
80598314</pre>
80608315
80618316
r242885r242886
80838338<p>
80848339<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
80858340Looks for the first <em>match</em> of
8086<code>pattern</code> in the string <code>s</code>.
8341<code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
80878342If it finds one, then <code>match</code> returns
80888343the captures from the pattern;
80898344otherwise it returns <b>nil</b>.
r242885r242886
80978352
80988353
80998354<p>
8355<hr><h3><a name="pdf-string.pack"><code>string.pack (fmt, v1, v2, &middot;&middot;&middot;)</code></a></h3>
8356
8357
8358<p>
8359Returns a binary string containing the values <code>v1</code>, <code>v2</code>, etc.
8360packed (that is, serialized in binary form)
8361according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
8362
8363
8364
8365
8366<p>
8367<hr><h3><a name="pdf-string.packsize"><code>string.packsize (fmt)</code></a></h3>
8368
8369
8370<p>
8371Returns the size of a string resulting from <a href="#pdf-string.pack"><code>string.pack</code></a>
8372with the given format.
8373The format string cannot have the variable-length options
8374'<code>s</code>' or '<code>z</code>' (see <a href="#6.4.2">&sect;6.4.2</a>).
8375
8376
8377
8378
8379<p>
81008380<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
81018381Returns a string that is the concatenation of <code>n</code> copies of
81028382the string <code>s</code> separated by the string <code>sep</code>.
81038383The default value for <code>sep</code> is the empty string
81048384(that is, no separator).
8385Returns the empty string if <code>n</code> is not positive.
81058386
81068387
81078388
r242885r242886
81418422
81428423
81438424<p>
8425<hr><h3><a name="pdf-string.unpack"><code>string.unpack (fmt, s [, pos])</code></a></h3>
8426
8427
8428<p>
8429Returns the values packed in string <code>s</code> (see <a href="#pdf-string.pack"><code>string.pack</code></a>)
8430according to the format string <code>fmt</code> (see <a href="#6.4.2">&sect;6.4.2</a>).
8431An optional <code>pos</code> marks where
8432to start reading in <code>s</code> (default is 1).
8433After the read values,
8434this function also returns the index of the first unread byte in <code>s</code>.
8435
8436
8437
8438
8439<p>
81448440<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
81458441Receives a string and returns a copy of this string with all
81468442lowercase letters changed to uppercase.
r242885r242886
81498445
81508446
81518447
8448
8449
81528450<h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
81538451
8452<p>
8453Patterns in Lua are described by regular strings,
8454which are interpreted as patterns by the pattern-matching functions
8455<a href="#pdf-string.find"><code>string.find</code></a>,
8456<a href="#pdf-string.gmatch"><code>string.gmatch</code></a>,
8457<a href="#pdf-string.gsub"><code>string.gsub</code></a>,
8458and <a href="#pdf-string.match"><code>string.match</code></a>.
8459This section describes the syntax and the meaning
8460(that is, what they match) of these strings.
81548461
8462
8463
81558464<h4>Character Class:</h4><p>
81568465A <em>character class</em> is used to represent a set of characters.
81578466The following combinations are allowed in describing a character class:
r242885r242886
81898498<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
81908499represents the character <em>x</em>.
81918500This is the standard way to escape the magic characters.
8192Any punctuation character (even the non magic)
8501Any non-alphanumeric character
8502(including all punctuations, even the non-magical)
81938503can be preceded by a '<code>%</code>'
81948504when used to represent itself in a pattern.
81958505</li>
r242885r242886
81998509characters in <em>set</em>.
82008510A range of characters can be specified by
82018511separating the end characters of the range,
8202in ascending order, with a '<code>-</code>',
8512in ascending order, with a '<code>-</code>'.
82038513All classes <code>%</code><em>x</em> described above can also be used as
82048514components in <em>set</em>.
82058515All other characters in <em>set</em> represent themselves.
r242885r242886
82488558
82498559<li>
82508560a single character class followed by '<code>*</code>',
8251which matches 0 or more repetitions of characters in the class.
8561which matches zero or more repetitions of characters in the class.
82528562These repetition items will always match the longest possible sequence;
82538563</li>
82548564
82558565<li>
82568566a single character class followed by '<code>+</code>',
8257which matches 1 or more repetitions of characters in the class.
8567which matches one or more repetitions of characters in the class.
82588568These repetition items will always match the longest possible sequence;
82598569</li>
82608570
82618571<li>
82628572a single character class followed by '<code>-</code>',
8263which also matches 0 or more repetitions of characters in the class.
8573which also matches zero or more repetitions of characters in the class.
82648574Unlike '<code>*</code>',
82658575these repetition items will always match the shortest possible sequence;
82668576</li>
82678577
82688578<li>
82698579a single character class followed by '<code>?</code>',
8270which matches 0 or 1 occurrence of a character in the class;
8580which matches zero or one occurrence of a character in the class.
8581It always matches one occurrence if possible;
82718582</li>
82728583
82738584<li>
r242885r242886
83408651
83418652
83428653
8654<h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
83438655
8656<p>
8657The first argument to <a href="#pdf-string.pack"><code>string.pack</code></a>,
8658<a href="#pdf-string.packsize"><code>string.packsize</code></a>, and <a href="#pdf-string.unpack"><code>string.unpack</code></a>
8659is a format string,
8660which describes the layout of the structure being created or read.
83448661
83458662
8663<p>
8664A format string is a sequence of conversion options.
8665The conversion options are as follows:
83468666
8347<h2>6.5 &ndash; <a name="6.5">Table Manipulation</a></h2>
8667<ul>
8668<li><b><code>&lt;</code>: </b>sets little endian</li>
8669<li><b><code>&gt;</code>: </b>sets big endian</li>
8670<li><b><code>=</code>: </b>sets native endian</li>
8671<li><b><code>![<em>n</em>]</code>: </b>sets maximum alignment to <code>n</code>
8672(default is native alignment)</li>
8673<li><b><code>b</code>: </b>a signed byte (<code>char</code>)</li>
8674<li><b><code>B</code>: </b>an unsigned byte (<code>char</code>)</li>
8675<li><b><code>h</code>: </b>a signed <code>short</code> (native size)</li>
8676<li><b><code>H</code>: </b>an unsigned <code>short</code> (native size)</li>
8677<li><b><code>l</code>: </b>a signed <code>long</code> (native size)</li>
8678<li><b><code>L</code>: </b>an unsigned <code>long</code> (native size)</li>
8679<li><b><code>j</code>: </b>a <code>lua_Integer</code></li>
8680<li><b><code>J</code>: </b>a <code>lua_Unsigned</code></li>
8681<li><b><code>T</code>: </b>a <code>size_t</code> (native size)</li>
8682<li><b><code>i[<em>n</em>]</code>: </b>a signed <code>int</code> with <code>n</code> bytes
8683(default is native size)</li>
8684<li><b><code>I[<em>n</em>]</code>: </b>an unsigned <code>int</code> with <code>n</code> bytes
8685(default is native size)</li>
8686<li><b><code>f</code>: </b>a <code>float</code> (native size)</li>
8687<li><b><code>d</code>: </b>a <code>double</code> (native size)</li>
8688<li><b><code>n</code>: </b>a <code>lua_Number</code></li>
8689<li><b><code>c<em>n</em></code>: </b>a fixed-sized string with <code>n</code> bytes</li>
8690<li><b><code>z</code>: </b>a zero-terminated string</li>
8691<li><b><code>s[<em>n</em>]</code>: </b>a string preceded by its length
8692coded as an unsigned integer with <code>n</code> bytes
8693(default is a <code>size_t</code>)</li>
8694<li><b><code>x</code>: </b>one byte of padding</li>
8695<li><b><code>X<em>op</em></code>: </b>an empty item that aligns
8696according to option <code>op</code>
8697(which is otherwise ignored)</li>
8698<li><b>'<code> </code>': </b>(empty space) ignored</li>
8699</ul><p>
8700(A "<code>[<em>n</em>]</code>" means an optional integral numeral.)
8701Except for padding, spaces, and configurations
8702(options "<code>xX &lt;=&gt;!</code>"),
8703each option corresponds to an argument (in <a href="#pdf-string.pack"><code>string.pack</code></a>)
8704or a result (in <a href="#pdf-string.unpack"><code>string.unpack</code></a>).
83488705
8706
83498707<p>
8708For options "<code>!<em>n</em></code>", "<code>s<em>n</em></code>", "<code>i<em>n</em></code>", and "<code>I<em>n</em></code>",
8709<code>n</code> can be any integer between 1 and 16.
8710All integral options check overflows;
8711<a href="#pdf-string.pack"><code>string.pack</code></a> checks whether the given value fits in the given size;
8712<a href="#pdf-string.unpack"><code>string.unpack</code></a> checks whether the read value fits in a Lua integer.
8713
8714
8715<p>
8716Any format string starts as if prefixed by "<code>!1=</code>",
8717that is,
8718with maximum alignment of 1 (no alignment)
8719and native endianness.
8720
8721
8722<p>
8723Alignment works as follows:
8724For each option,
8725the format gets extra padding until the data starts
8726at an offset that is a multiple of the minimum between the
8727option size and the maximum alignment;
8728this minimum must be a power of 2.
8729Options "<code>c</code>" and "<code>z</code>" are not aligned;
8730option "<code>s</code>" follows the alignment of its starting integer.
8731
8732
8733<p>
8734All padding is filled with zeros by <a href="#pdf-string.pack"><code>string.pack</code></a>
8735(and ignored by <a href="#pdf-string.unpack"><code>string.unpack</code></a>).
8736
8737
8738
8739
8740
8741
8742
8743<h2>6.5 &ndash; <a name="6.5">UTF-8 Support</a></h2>
8744
8745<p>
8746This library provides basic support for UTF-8 encoding.
8747It provides all its functions inside the table <a name="pdf-utf8"><code>utf8</code></a>.
8748This library does not provide any support for Unicode other
8749than the handling of the encoding.
8750Any operation that needs the meaning of a character,
8751such as character classification, is outside its scope.
8752
8753
8754<p>
8755Unless stated otherwise,
8756all functions that expect a byte position as a parameter
8757assume that the given position is either the start of a byte sequence
8758or one plus the length of the subject string.
8759As in the string library,
8760negative indices count from the end of the string.
8761
8762
8763<p>
8764<hr><h3><a name="pdf-utf8.char"><code>utf8.char (&middot;&middot;&middot;)</code></a></h3>
8765Receives zero or more integers,
8766converts each one to its corresponding UTF-8 byte sequence
8767and returns a string with the concatenation of all these sequences.
8768
8769
8770
8771
8772<p>
8773<hr><h3><a name="pdf-utf8.charpattern"><code>utf8.charpattern</code></a></h3>
8774The pattern (a string, not a function) "<code>[\0-\x7F\xC2-\xF4][\x80-\xBF]*</code>"
8775(see <a href="#6.4.1">&sect;6.4.1</a>),
8776which matches exactly one UTF-8 byte sequence,
8777assuming that the subject is a valid UTF-8 string.
8778
8779
8780
8781
8782<p>
8783<hr><h3><a name="pdf-utf8.codes"><code>utf8.codes (s)</code></a></h3>
8784
8785
8786<p>
8787Returns values so that the construction
8788
8789<pre>
8790     for p, c in utf8.codes(s) do <em>body</em> end
8791</pre><p>
8792will iterate over all characters in string <code>s</code>,
8793with <code>p</code> being the position (in bytes) and <code>c</code> the code point
8794of each character.
8795It raises an error if it meets any invalid byte sequence.
8796
8797
8798
8799
8800<p>
8801<hr><h3><a name="pdf-utf8.codepoint"><code>utf8.codepoint (s [, i [, j]])</code></a></h3>
8802Returns the codepoints (as integers) from all characters in <code>s</code>
8803that start between byte position <code>i</code> and <code>j</code> (both included).
8804The default for <code>i</code> is 1 and for <code>j</code> is <code>i</code>.
8805It raises an error if it meets any invalid byte sequence.
8806
8807
8808
8809
8810<p>
8811<hr><h3><a name="pdf-utf8.len"><code>utf8.len (s [, i [, j]])</code></a></h3>
8812Returns the number of UTF-8 characters in string <code>s</code>
8813that start between positions <code>i</code> and <code>j</code> (both inclusive).
8814The default for <code>i</code> is 1 and for <code>j</code> is -1.
8815If it finds any invalid byte sequence,
8816returns a false value plus the position of the first invalid byte.
8817
8818
8819
8820
8821<p>
8822<hr><h3><a name="pdf-utf8.offset"><code>utf8.offset (s, n [, i])</code></a></h3>
8823Returns the position (in bytes) where the encoding of the
8824<code>n</code>-th character of <code>s</code>
8825(counting from position <code>i</code>) starts.
8826A negative <code>n</code> gets characters before position <code>i</code>.
8827The default for <code>i</code> is 1 when <code>n</code> is non-negative
8828and <code>#s + 1</code> otherwise,
8829so that <code>utf8.offset(s, -n)</code> gets the offset of the
8830<code>n</code>-th character from the end of the string.
8831If the specified character is neither in the subject
8832nor right after its end,
8833the function returns <b>nil</b>.
8834
8835
8836<p>
8837As a special case,
8838when <code>n</code> is 0 the function returns the start of the encoding
8839of the character that contains the <code>i</code>-th byte of <code>s</code>.
8840
8841
8842<p>
8843This function assumes that <code>s</code> is a valid UTF-8 string.
8844
8845
8846
8847
8848
8849
8850
8851<h2>6.6 &ndash; <a name="6.6">Table Manipulation</a></h2>
8852
8853<p>
83508854This library provides generic functions for table manipulation.
83518855It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
83528856
83538857
83548858<p>
83558859Remember that, whenever an operation needs the length of a table,
8356the table should be a proper sequence
8357or have a <code>__len</code> metamethod (see <a href="#3.4.6">&sect;3.4.6</a>).
8860the table must be a proper sequence
8861or have a <code>__len</code> metamethod (see <a href="#3.4.7">&sect;3.4.7</a>).
83588862All functions ignore non-numeric keys
8359in tables given as arguments.
8863in the tables given as arguments.
83608864
83618865
83628866<p>
8363For performance reasons,
8364all table accesses (get/set) performed by these functions are raw.
8365
8366
8367<p>
83688867<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
83698868
83708869
r242885r242886
83958894
83968895
83978896<p>
8897<hr><h3><a name="pdf-table.move"><code>table.move (a1, f, e, t [,a2])</code></a></h3>
8898
8899
8900<p>
8901Moves elements from table <code>a1</code> to table <code>a2</code>.
8902This function performs the equivalent to the following
8903multiple assignment:
8904<code>a2[t],&middot;&middot;&middot; = a1[f],&middot;&middot;&middot;,a1[e]</code>.
8905The default for <code>a2</code> is <code>a1</code>.
8906The destination range can overlap with the source range.
8907Index <code>f</code> must be positive.
8908
8909
8910
8911
8912<p>
83988913<hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
83998914
84008915
r242885r242886
84248939
84258940<p>
84268941The default value for <code>pos</code> is <code>#list</code>,
8427so that a call <code>table.remove(t)</code> removes the last element
8428of list <code>t</code>.
8942so that a call <code>table.remove(l)</code> removes the last element
8943of list <code>l</code>.
84298944
84308945
84318946
r242885r242886
84598974
84608975
84618976<p>
8462Returns the elements from the given table.
8977Returns the elements from the given list.
84638978This function is equivalent to
84648979
84658980<pre>
r242885r242886
84738988
84748989
84758990
8476<h2>6.6 &ndash; <a name="6.6">Mathematical Functions</a></h2>
8991<h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
84778992
84788993<p>
8479This library is an interface to the standard C&nbsp;math library.
8480It provides all its functions inside the table <a name="pdf-math"><code>math</code></a>.
8994This library provides basic mathematical functions.
8995It provides all its functions and constants inside the table <a name="pdf-math"><code>math</code></a>.
8996Functions with the annotation "<code>integer/float</code>" give
8997integer results for integer arguments
8998and float results for float (or mixed) arguments.
8999Rounding functions
9000(<a href="#pdf-math.ceil"><code>math.ceil</code></a>, <a href="#pdf-math.floor"><code>math.floor</code></a>, and <a href="#pdf-math.modf"><code>math.modf</code></a>)
9001return an integer when the result fits in the range of an integer,
9002or a float otherwise.
84819003
84829004
84839005<p>
r242885r242886
84859007
84869008
84879009<p>
8488Returns the absolute value of <code>x</code>.
9010Returns the absolute value of <code>x</code>. (integer/float)
84899011
84909012
84919013
r242885r242886
85119033
85129034
85139035<p>
8514<hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
9036<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
85159037
85169038
85179039<p>
8518Returns the arc tangent of <code>x</code> (in radians).
85199040
8520
8521
8522
8523<p>
8524<hr><h3><a name="pdf-math.atan2"><code>math.atan2 (y, x)</code></a></h3>
8525
8526
8527<p>
85289041Returns the arc tangent of <code>y/x</code> (in radians),
85299042but uses the signs of both parameters to find the
85309043quadrant of the result.
85319044(It also handles correctly the case of <code>x</code> being zero.)
85329045
85339046
9047<p>
9048The default value for <code>x</code> is 1,
9049so that the call <code>math.atan(y)</code>
9050returns the arc tangent of <code>y</code>.
85349051
85359052
9053
9054
85369055<p>
85379056<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
85389057
85399058
85409059<p>
8541Returns the smallest integer larger than or equal to <code>x</code>.
9060Returns the smallest integral value larger than or equal to <code>x</code>.
85429061
85439062
85449063
r242885r242886
85549073
85559074
85569075<p>
8557<hr><h3><a name="pdf-math.cosh"><code>math.cosh (x)</code></a></h3>
8558
8559
8560<p>
8561Returns the hyperbolic cosine of <code>x</code>.
8562
8563
8564
8565
8566<p>
85679076<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
85689077
85699078
85709079<p>
8571Returns the angle <code>x</code> (given in radians) in degrees.
9080Converts the angle <code>x</code> from radians to degrees.
85729081
85739082
85749083
r242885r242886
85789087
85799088
85809089<p>
8581Returns the value <em>e<sup>x</sup></em>.
9090Returns the value <em>e<sup>x</sup></em>
9091(where <code>e</code> is the base of natural logarithms).
85829092
85839093
85849094
r242885r242886
85889098
85899099
85909100<p>
8591Returns the largest integer smaller than or equal to <code>x</code>.
9101Returns the largest integral value smaller than or equal to <code>x</code>.
85929102
85939103
85949104
r242885r242886
85999109
86009110<p>
86019111Returns the remainder of the division of <code>x</code> by <code>y</code>
8602that rounds the quotient towards zero.
9112that rounds the quotient towards zero. (integer/float)
86039113
86049114
86059115
86069116
86079117<p>
8608<hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
9118<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
86099119
86109120
86119121<p>
8612Returns <code>m</code> and <code>e</code> such that <em>x = m2<sup>e</sup></em>,
8613<code>e</code> is an integer and the absolute value of <code>m</code> is
8614in the range <em>[0.5, 1)</em>
8615(or zero when <code>x</code> is zero).
9122The float value <code>HUGE_VAL</code>,
9123a value larger than any other numerical value.
86169124
86179125
86189126
86199127
86209128<p>
8621<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
9129<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
86229130
86239131
86249132<p>
8625The value <code>HUGE_VAL</code>,
8626a value larger than or equal to any other numerical value.
9133Returns the logarithm of <code>x</code> in the given base.
9134The default for <code>base</code> is <em>e</em>
9135(so that the function returns the natural logarithm of <code>x</code>).
86279136
86289137
86299138
86309139
86319140<p>
8632<hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
9141<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
86339142
86349143
86359144<p>
8636Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
9145Returns the argument with the maximum value,
9146according to the Lua operator <code>&lt;</code>. (integer/float)
86379147
86389148
86399149
86409150
86419151<p>
8642<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
9152<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
9153An integer with the maximum value for an integer.
86439154
86449155
8645<p>
8646Returns the logarithm of <code>x</code> in the given base.
8647The default for <code>base</code> is <em>e</em>
8648(so that the function returns the natural logarithm of <code>x</code>).
86499156
86509157
8651
8652
86539158<p>
8654<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
9159<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
86559160
86569161
86579162<p>
8658Returns the maximum value among its arguments.
9163Returns the argument with the minimum value,
9164according to the Lua operator <code>&lt;</code>. (integer/float)
86599165
86609166
86619167
86629168
86639169<p>
8664<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
9170<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
9171An integer with the minimum value for an integer.
86659172
86669173
8667<p>
8668Returns the minimum value among its arguments.
86699174
86709175
8671
8672
86739176<p>
86749177<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
86759178
86769179
86779180<p>
8678Returns two numbers,
8679the integral part of <code>x</code> and the fractional part of <code>x</code>.
9181Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
9182Its second result is always a float.
86809183
86819184
86829185
r242885r242886
86929195
86939196
86949197<p>
8695<hr><h3><a name="pdf-math.pow"><code>math.pow (x, y)</code></a></h3>
8696
8697
8698<p>
8699Returns <em>x<sup>y</sup></em>.
8700(You can also use the expression <code>x^y</code> to compute this value.)
8701
8702
8703
8704
8705<p>
87069198<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
87079199
87089200
87099201<p>
8710Returns the angle <code>x</code> (given in degrees) in radians.
9202Converts the angle <code>x</code> from degrees to radians.
87119203
87129204
87139205
r242885r242886
87179209
87189210
87199211<p>
8720This function is an interface to the simple
8721pseudo-random generator function <code>rand</code> provided by Standard&nbsp;C.
8722(No guarantees can be given for its statistical properties.)
9212When called without arguments,
9213returns a pseudo-random float with uniform distribution
9214in the range  <em>[0,1)</em>. 
9215When called with two integers <code>m</code> and <code>n</code>,
9216<code>math.random</code> returns a pseudo-random integer
9217with uniform distribution in the range <em>[m, n]</em>.
9218(The value <em>m-n</em> cannot be negative and must fit in a Lua integer.)
9219The call <code>math.random(n)</code> is equivalent to <code>math.random(1,n)</code>.
87239220
87249221
87259222<p>
8726When called without arguments,
8727returns a uniform pseudo-random real number
8728in the range <em>[0,1)</em>. 
8729When called with an integer number <code>m</code>,
8730<code>math.random</code> returns
8731a uniform pseudo-random integer in the range <em>[1, m]</em>.
8732When called with two integer numbers <code>m</code> and <code>n</code>,
8733<code>math.random</code> returns a uniform pseudo-random
8734integer in the range <em>[m, n]</em>.
9223This function is an interface to the underling
9224pseudo-random generator function provided by C.
9225No guarantees can be given for its statistical properties.
87359226
87369227
87379228
r242885r242886
87599250
87609251
87619252<p>
8762<hr><h3><a name="pdf-math.sinh"><code>math.sinh (x)</code></a></h3>
8763
8764
8765<p>
8766Returns the hyperbolic sine of <code>x</code>.
8767
8768
8769
8770
8771<p>
87729253<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
87739254
87749255
r242885r242886
87909271
87919272
87929273<p>
8793<hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
9274<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
87949275
87959276
87969277<p>
8797Returns the hyperbolic tangent of <code>x</code>.
9278If the value <code>x</code> is convertible to an integer,
9279returns that integer.
9280Otherwise, returns <b>nil</b>.
87989281
87999282
88009283
88019284
8802
8803
8804
8805<h2>6.7 &ndash; <a name="6.7">Bitwise Operations</a></h2>
8806
88079285<p>
8808This library provides bitwise operations.
8809It provides all its functions inside the table <a name="pdf-bit32"><code>bit32</code></a>.
9286<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
88109287
88119288
88129289<p>
8813Unless otherwise stated,
8814all functions accept numeric arguments in the range
8815<em>(-2<sup>51</sup>,+2<sup>51</sup>)</em>;
8816each argument is normalized to
8817the remainder of its division by <em>2<sup>32</sup></em>
8818and truncated to an integer (in some unspecified way),
8819so that its final value falls in the range <em>[0,2<sup>32</sup> - 1]</em>.
8820Similarly, all results are in the range <em>[0,2<sup>32</sup> - 1]</em>.
8821Note that <code>bit32.bnot(0)</code> is <code>0xFFFFFFFF</code>,
8822which is different from <code>-1</code>.
9290Returns "<code>integer</code>" if <code>x</code> is an integer,
9291"<code>float</code>" if it is a float,
9292or <b>nil</b> if <code>x</code> is not a number.
88239293
88249294
8825<p>
8826<hr><h3><a name="pdf-bit32.arshift"><code>bit32.arshift (x, disp)</code></a></h3>
88279295
88289296
88299297<p>
8830Returns the number <code>x</code> shifted <code>disp</code> bits to the right.
8831The number <code>disp</code> may be any representable integer.
8832Negative displacements shift to the left.
9298<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
88339299
88349300
88359301<p>
8836This shift operation is what is called arithmetic shift.
8837Vacant bits on the left are filled
8838with copies of the higher bit of <code>x</code>;
8839vacant bits on the right are filled with zeros.
8840In particular,
8841displacements with absolute values higher than 31
8842result in zero or <code>0xFFFFFFFF</code> (all original bits are shifted out).
9302Returns a boolean,
9303true if integer <code>m</code> is below integer <code>n</code> when
9304they are compared as unsigned integers.
88439305
88449306
88459307
88469308
8847<p>
8848<hr><h3><a name="pdf-bit32.band"><code>bit32.band (&middot;&middot;&middot;)</code></a></h3>
88499309
88509310
8851<p>
8852Returns the bitwise <em>and</em> of its operands.
88539311
8854
8855
8856
8857<p>
8858<hr><h3><a name="pdf-bit32.bnot"><code>bit32.bnot (x)</code></a></h3>
8859
8860
8861<p>
8862Returns the bitwise negation of <code>x</code>.
8863For any integer <code>x</code>,
8864the following identity holds:
8865
8866<pre>
8867     assert(bit32.bnot(x) == (-1 - x) % 2^32)
8868</pre>
8869
8870
8871
8872<p>
8873<hr><h3><a name="pdf-bit32.bor"><code>bit32.bor (&middot;&middot;&middot;)</code></a></h3>
8874
8875
8876<p>
8877Returns the bitwise <em>or</em> of its operands.
8878
8879
8880
8881
8882<p>
8883<hr><h3><a name="pdf-bit32.btest"><code>bit32.btest (&middot;&middot;&middot;)</code></a></h3>
8884
8885
8886<p>
8887Returns a boolean signaling
8888whether the bitwise <em>and</em> of its operands is different from zero.
8889
8890
8891
8892
8893<p>
8894<hr><h3><a name="pdf-bit32.bxor"><code>bit32.bxor (&middot;&middot;&middot;)</code></a></h3>
8895
8896
8897<p>
8898Returns the bitwise <em>exclusive or</em> of its operands.
8899
8900
8901
8902
8903<p>
8904<hr><h3><a name="pdf-bit32.extract"><code>bit32.extract (n, field [, width])</code></a></h3>
8905
8906
8907<p>
8908Returns the unsigned number formed by the bits
8909<code>field</code> to <code>field + width - 1</code> from <code>n</code>.
8910Bits are numbered from 0 (least significant) to 31 (most significant).
8911All accessed bits must be in the range <em>[0, 31]</em>.
8912
8913
8914<p>
8915The default for <code>width</code> is 1.
8916
8917
8918
8919
8920<p>
8921<hr><h3><a name="pdf-bit32.replace"><code>bit32.replace (n, v, field [, width])</code></a></h3>
8922
8923
8924<p>
8925Returns a copy of <code>n</code> with
8926the bits <code>field</code> to <code>field + width - 1</code>
8927replaced by the value <code>v</code>.
8928See <a href="#pdf-bit32.extract"><code>bit32.extract</code></a> for details about <code>field</code> and <code>width</code>.
8929
8930
8931
8932
8933<p>
8934<hr><h3><a name="pdf-bit32.lrotate"><code>bit32.lrotate (x, disp)</code></a></h3>
8935
8936
8937<p>
8938Returns the number <code>x</code> rotated <code>disp</code> bits to the left.
8939The number <code>disp</code> may be any representable integer.
8940
8941
8942<p>
8943For any valid displacement,
8944the following identity holds:
8945
8946<pre>
8947     assert(bit32.lrotate(x, disp) == bit32.lrotate(x, disp % 32))
8948</pre><p>
8949In particular,
8950negative displacements rotate to the right.
8951
8952
8953
8954
8955<p>
8956<hr><h3><a name="pdf-bit32.lshift"><code>bit32.lshift (x, disp)</code></a></h3>
8957
8958
8959<p>
8960Returns the number <code>x</code> shifted <code>disp</code> bits to the left.
8961The number <code>disp</code> may be any representable integer.
8962Negative displacements shift to the right.
8963In any direction, vacant bits are filled with zeros.
8964In particular,
8965displacements with absolute values higher than 31
8966result in zero (all bits are shifted out).
8967
8968
8969<p>
8970For positive displacements,
8971the following equality holds:
8972
8973<pre>
8974     assert(bit32.lshift(b, disp) == (b * 2^disp) % 2^32)
8975</pre>
8976
8977
8978
8979<p>
8980<hr><h3><a name="pdf-bit32.rrotate"><code>bit32.rrotate (x, disp)</code></a></h3>
8981
8982
8983<p>
8984Returns the number <code>x</code> rotated <code>disp</code> bits to the right.
8985The number <code>disp</code> may be any representable integer.
8986
8987
8988<p>
8989For any valid displacement,
8990the following identity holds:
8991
8992<pre>
8993     assert(bit32.rrotate(x, disp) == bit32.rrotate(x, disp % 32))
8994</pre><p>
8995In particular,
8996negative displacements rotate to the left.
8997
8998
8999
9000
9001<p>
9002<hr><h3><a name="pdf-bit32.rshift"><code>bit32.rshift (x, disp)</code></a></h3>
9003
9004
9005<p>
9006Returns the number <code>x</code> shifted <code>disp</code> bits to the right.
9007The number <code>disp</code> may be any representable integer.
9008Negative displacements shift to the left.
9009In any direction, vacant bits are filled with zeros.
9010In particular,
9011displacements with absolute values higher than 31
9012result in zero (all bits are shifted out).
9013
9014
9015<p>
9016For positive displacements,
9017the following equality holds:
9018
9019<pre>
9020     assert(bit32.rshift(b, disp) == math.floor(b % 2^32 / 2^disp))
9021</pre>
9022
9023<p>
9024This shift operation is what is called logical shift.
9025
9026
9027
9028
9029
9030
9031
90329312<h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
90339313
90349314<p>
90359315The I/O library provides two different styles for file manipulation.
9036The first one uses implicit file descriptors;
9316The first one uses implicit file handles;
90379317that is, there are operations to set a default input file and a
90389318default output file,
90399319and all input/output operations are over these default files.
9040The second style uses explicit file descriptors.
9320The second style uses explicit file handles.
90419321
90429322
90439323<p>
9044When using implicit file descriptors,
9324When using implicit file handles,
90459325all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
9046When using explicit file descriptors,
9047the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file descriptor
9048and then all operations are supplied as methods of the file descriptor.
9326When using explicit file handles,
9327the operation <a href="#pdf-io.open"><code>io.open</code></a> returns a file handle
9328and then all operations are supplied as methods of the file handle.
90499329
90509330
90519331<p>
90529332The table <code>io</code> also provides
9053three predefined file descriptors with their usual meanings from C:
9333three predefined file handles with their usual meanings from C:
90549334<a name="pdf-io.stdin"><code>io.stdin</code></a>, <a name="pdf-io.stdout"><code>io.stdout</code></a>, and <a name="pdf-io.stderr"><code>io.stderr</code></a>.
90559335The I/O library never closes these files.
90569336
r242885r242886
90619341(plus an error message as a second result and
90629342a system-dependent error code as a third result)
90639343and some value different from <b>nil</b> on success.
9064On non-Posix systems,
9344On non-POSIX systems,
90659345the computation of the error message and error code
90669346in case of errors
90679347may be not thread safe,
r242885r242886
91189398and returns an iterator function that
91199399works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
91209400When the iterator function detects the end of file,
9121it returns <b>nil</b> (to finish the loop) and automatically closes the file.
9401it returns no values (to finish the loop) and automatically closes the file.
91229402
91239403
91249404<p>
91259405The call <code>io.lines()</code> (with no file name) is equivalent
9126to <code>io.input():lines()</code>;
9406to <code>io.input():lines("*l")</code>;
91279407that is, it iterates over the lines of the default input file.
91289408In this case it does not close the file when the loop ends.
91299409
r242885r242886
92769556each time it is called,
92779557reads the file according to the given formats.
92789558When no format is given,
9279uses "*l" as a default.
9559uses "<code>l</code>" as a default.
92809560As an example, the construction
92819561
92829562<pre>
r242885r242886
93039583Reads the file <code>file</code>,
93049584according to the given formats, which specify what to read.
93059585For each format,
9306the function returns a string (or a number) with the characters read,
9586the function returns a string or a number with the characters read,
93079587or <b>nil</b> if it cannot read data with the specified format.
9588(In this latter case,
9589the function does not read subsequent formats.)
93089590When called without formats,
93099591it uses a default format that reads the next line
93109592(see below).
r242885r242886
93159597
93169598<ul>
93179599
9318<li><b>"<code>*n</code>": </b>
9319reads a number;
9320this is the only format that returns a number instead of a string.
9600<li><b>"<code>n</code>": </b>
9601reads a numeral and returns it as a float or an integer,
9602following the lexical conventions of Lua.
9603(The numeral may have leading spaces and a sign.)
9604This format always reads the longest input sequence that
9605is a valid prefix for a number;
9606if that prefix does not form a valid number
9607(e.g., an empty string, "<code>0x</code>", or "<code>3.4e-</code>"),
9608it is discarded and the function returns <b>nil</b>.
93219609</li>
93229610
9323<li><b>"<code>*a</code>": </b>
9611<li><b>"<code>i</code>": </b>
9612reads an integral number and returns it as an integer.
9613</li>
9614
9615<li><b>"<code>a</code>": </b>
93249616reads the whole file, starting at the current position.
93259617On end of file, it returns the empty string.
93269618</li>
93279619
9328<li><b>"<code>*l</code>": </b>
9620<li><b>"<code>l</code>": </b>
93299621reads the next line skipping the end of line,
93309622returning <b>nil</b> on end of file.
93319623This is the default format.
93329624</li>
93339625
9334<li><b>"<code>*L</code>": </b>
9335reads the next line keeping the end of line (if present),
9626<li><b>"<code>L</code>": </b>
9627reads the next line keeping the end-of-line character (if present),
93369628returning <b>nil</b> on end of file.
93379629</li>
93389630
93399631<li><b><em>number</em>: </b>
93409632reads a string with up to this number of bytes,
93419633returning <b>nil</b> on end of file.
9342If number is zero,
9634If <code>number</code> is zero,
93439635it reads nothing and returns an empty string,
93449636or <b>nil</b> on end of file.
93459637</li>
93469638
9347</ul>
9639</ul><p>
9640The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
93489641
93499642
93509643
9644
93519645<p>
93529646<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
93539647
r242885r242886
94869780<p>
94879781If <code>format</code> is not "<code>*t</code>",
94889782then <code>date</code> returns the date as a string,
9489formatted according to the same rules as the ANSI&nbsp;C function <code>strftime</code>.
9783formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
94909784
94919785
94929786<p>
r242885r242886
94979791
94989792
94999793<p>
9500On non-Posix systems,
9794On non-POSIX systems,
95019795this function may be not thread safe
95029796because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
95039797
r242885r242886
95099803
95109804
95119805<p>
9512Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
9806Returns the difference, in seconds,
9807from time <code>t1</code> to time <code>t2</code>
9808(where the times are values returned by <a href="#pdf-os.time"><code>os.time</code></a>).
95139809In POSIX, Windows, and some other systems,
95149810this value is exactly <code>t2</code><em>-</em><code>t1</code>.
95159811
r242885r242886
95219817
95229818
95239819<p>
9524This function is equivalent to the ANSI&nbsp;C function <code>system</code>.
9820This function is equivalent to the ISO&nbsp;C function <code>system</code>.
95259821It passes <code>command</code> to be executed by an operating system shell.
95269822Its first result is <b>true</b>
95279823if the command terminated successfully,
95289824or <b>nil</b> otherwise.
95299825After this first result
9530the function returns a string and a number,
9826the function returns a string plus a number,
95319827as follows:
95329828
95339829<ul>
r242885r242886
95529848
95539849
95549850<p>
9555<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close])</code></a></h3>
9851<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
95569852
95579853
95589854<p>
9559Calls the ANSI&nbsp;C function <code>exit</code> to terminate the host program.
9855Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
95609856If <code>code</code> is <b>true</b>,
95619857the returned status is <code>EXIT_SUCCESS</code>;
95629858if <code>code</code> is <b>false</b>,
r242885r242886
981910115
982010116<p>
982110117The first parameter or local variable has index&nbsp;1, and so on,
9822until the last active variable.
10118following the order that they are declared in the code,
10119counting only the variables that are active
10120in the current scope of the function.
982310121Negative indices refer to vararg parameters;
982410122-1 is the first vararg parameter.
982510123The function returns <b>nil</b> if there is no variable with the given index,
r242885r242886
982810126
982910127
983010128<p>
9831Variable names starting with '<code>(</code>' (open parenthesis)
9832represent internal variables
9833(loop control variables, temporaries, varargs, and C&nbsp;function locals).
10129Variable names starting with '<code>(</code>' (open parenthesis)
10130represent variables with no known names
10131(internal variables such as loop control variables,
10132and variables from chunks saved without debug information).
983410133
983510134
983610135<p>
r242885r242886
987110170The function returns <b>nil</b> if there is no upvalue with the given index.
987210171
987310172
10173<p>
10174Variable names starting with '<code>(</code>' (open parenthesis)
10175represent variables with no known names
10176(variables from chunks saved without debug information).
987410177
987510178
10179
10180
987610181<p>
987710182<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3>
987810183
r242885r242886
989310198Sets the given function as a hook.
989410199The string <code>mask</code> and the number <code>count</code> describe
989510200when the hook will be called.
9896The string mask may have the following characters,
10201The string mask may have any combination of the following characters,
989710202with the given meaning:
989810203
989910204<ul>
r242885r242886
990110206<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
990210207<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
990310208</ul><p>
9904With a <code>count</code> different from zero,
9905the hook is called after every <code>count</code> instructions.
10209Moreover,
10210with a <code>count</code> different from zero,
10211the hook is called also after every <code>count</code> instructions.
990610212
990710213
990810214<p>
r242885r242886
998110287<p>
998210288Sets the given <code>value</code> as
998310289the Lua value associated to the given <code>udata</code>.
9984<code>value</code> must be a table or <b>nil</b>;
998510290<code>udata</code> must be a full userdata.
998610291
998710292
r242885r242886
1000010305this function returns <code>message</code> without further processing.
1000110306Otherwise,
1000210307it returns a string with a traceback of the call stack.
10003An optional <code>message</code> string is appended
10308The optional <code>message</code> string is appended
1000410309at the beginning of the traceback.
1000510310An optional <code>level</code> number tells at which level
1000610311to start the traceback
r242885r242886
1001410319
1001510320
1001610321<p>
10017Returns an unique identifier (as a light userdata)
10322Returns a unique identifier (as a light userdata)
1001810323for the upvalue numbered <code>n</code>
1001910324from the given function.
1002010325
r242885r242886
1007010375<li><b><code>--</code>: </b> stops handling options;</li>
1007110376<li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li>
1007210377</ul><p>
10073After handling its options, <code>lua</code> runs the given <em>script</em>,
10074passing to it the given <em>args</em> as string arguments.
10378After handling its options, <code>lua</code> runs the given <em>script</em>.
1007510379When called without arguments,
1007610380<code>lua</code> behaves as <code>lua -v -i</code>
1007710381when the standard input (<code>stdin</code>) is a terminal,
r242885r242886
1008010384
1008110385<p>
1008210386When called without option <code>-E</code>,
10083the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_2"><code>LUA_INIT_5_2</code></a>
10084(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if it is not defined)
10387the interpreter checks for an environment variable <a name="pdf-LUA_INIT_5_3"><code>LUA_INIT_5_3</code></a>
10388(or <a name="pdf-LUA_INIT"><code>LUA_INIT</code></a> if the versioned name is not defined)
1008510389before running any argument.
1008610390If the variable content has the format <code>@<em>filename</em></code>,
1008710391then <code>lua</code> executes the file.
r242885r242886
1011110415
1011210416
1011310417<p>
10114Before starting to run the script,
10115<code>lua</code> collects all arguments in the command line
10418Before running any code,
10419<code>lua</code> collects all command-line arguments
1011610420in a global table called <code>arg</code>.
10117The script name is stored at index 0,
10421The script name goes to index 0,
1011810422the first argument after the script name goes to index 1,
1011910423and so on.
1012010424Any arguments before the script name
10121(that is, the interpreter name plus the options)
10425(that is, the interpreter name plus its options)
1012210426go to negative indices.
1012310427For instance, in the call
1012410428
1012510429<pre>
1012610430     $ lua -la b.lua t1 t2
1012710431</pre><p>
10128the interpreter first runs the file <code>a.lua</code>,
10129then creates a table
10432the table is like this:
1013010433
1013110434<pre>
1013210435     arg = { [-2] = "lua", [-1] = "-la",
1013310436             [0] = "b.lua",
1013410437             [1] = "t1", [2] = "t2" }
1013510438</pre><p>
10136and finally runs the file <code>b.lua</code>.
10137The script is called with <code>arg[1]</code>, <code>arg[2]</code>, ...
10138as arguments;
10139it can also access these arguments with the vararg expression '<code>...</code>'.
10439If there is no script in the call,
10440the interpreter name goes to index 0,
10441followed by the other arguments.
10442For instance, the call
1014010443
10444<pre>
10445     $ lua -e "print(arg[1])"
10446</pre><p>
10447will print "<code>-e</code>".
10448If there is a script,
10449the script is called with parameters
10450<code>arg[1]</code>, &middot;&middot;&middot;, <code>arg[#arg]</code>.
10451(Like all chunks in Lua,
10452the script is compiled as a vararg function.)
1014110453
10454
1014210455<p>
1014310456In interactive mode,
10144if you write an incomplete statement,
10457Lua repeatedly prompts and waits for a line.
10458After reading a line,
10459Lua first try to interpret the line as an expression.
10460If it succeeds, it prints its value.
10461Otherwise, it interprets the line as a statement.
10462If you write an incomplete statement,
1014510463the interpreter waits for its completion
1014610464by issuing a different prompt.
1014710465
r242885r242886
1014910467<p>
1015010468In case of unprotected errors in the script,
1015110469the interpreter reports the error to the standard error stream.
10152If the error object is a string,
10153the interpreter adds a stack traceback to it.
10154Otherwise, if the error object has a metamethod <code>__tostring</code>,
10470If the error object is not a string but
10471has a metamethod <code>__tostring</code>,
1015510472the interpreter calls this metamethod to produce the final message.
10156Finally, if the error object is <b>nil</b>,
10157the interpreter does not report the error.
10473Otherwise, the interpreter converts the error object to a string
10474and adds a stack traceback to it.
1015810475
1015910476
1016010477<p>
r242885r242886
1019310510
1019410511<p>
1019510512Here we list the incompatibilities that you may find when moving a program
10196from Lua&nbsp;5.1 to Lua&nbsp;5.2.
10513from Lua&nbsp;5.2 to Lua&nbsp;5.3.
1019710514You can avoid some incompatibilities by compiling Lua with
1019810515appropriate options (see file <code>luaconf.h</code>).
1019910516However,
10200all these compatibility options will be removed in the next version of Lua.
10201Similarly,
10202all features marked as deprecated in Lua&nbsp;5.1
10203have been removed in Lua&nbsp;5.2.
10517all these compatibility options will be removed in the future.
1020410518
1020510519
10520<p>
10521Lua versions can always change the C API in ways that
10522do not imply source-code changes in a program,
10523such as the numeric values for constants
10524or the implementation of functions as macros.
10525Therefore,
10526you should not assume that binaries are compatible between
10527different Lua versions.
10528Always recompile clients of the Lua API when
10529using a new version.
1020610530
10207<h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2>
10208<ul>
1020910531
10210<li>
10211The concept of <em>environment</em> changed.
10212Only Lua functions have environments.
10213To set the environment of a Lua function,
10214use the variable <code>_ENV</code> or the function <a href="#pdf-load"><code>load</code></a>.
10532<p>
10533Similarly, Lua versions can always change the internal representation
10534of precompiled chunks;
10535precompiled chunks are not compatible between different Lua versions.
1021510536
1021610537
1021710538<p>
10218C functions no longer have environments.
10219Use an upvalue with a shared table if you need to keep
10220shared state among several C functions.
10221(You may use <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a> to open a C library
10222with all functions sharing a common upvalue.)
10539The standard paths in the official distribution may
10540change between versions.
1022310541
1022410542
10225<p>
10226To manipulate the "environment" of a userdata
10227(which is now called user value),
10228use the new functions
10229<a href="#lua_getuservalue"><code>lua_getuservalue</code></a> and <a href="#lua_setuservalue"><code>lua_setuservalue</code></a>.
10230</li>
1023110543
10544<h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2>
10545<ul>
10546
1023210547<li>
10233Lua identifiers cannot use locale-dependent letters.
10234</li>
10548The main difference between Lua&nbsp;5.2 and Lua&nbsp;5.3 is the
10549introduction of an integer subtype for numbers.
10550Although this change should not affect "normal" computations,
10551some computations
10552(mainly those that involve some kind of overflow)
10553can give different results.
1023510554
10236<li>
10237Doing a step or a full collection in the garbage collector
10238does not restart the collector if it has been stopped.
10555
10556<p>
10557You can fix these differences by forcing a number to be a float
10558(in Lua&nbsp;5.2 all numbers were float),
10559in particular writing constants with an ending <code>.0</code>
10560or using <code>x = x + 0.0</code> to convert a variable.
10561(This recommendation is only for a quick fix
10562for an occasional incompatibility;
10563it is not a general guideline for good programming.
10564For good programming,
10565use floats where you need floats
10566and integers where you need integers.)
1023910567</li>
1024010568
1024110569<li>
10242Weak tables with weak keys now perform like <em>ephemeron tables</em>.
10243</li>
10570The conversion of a float to a string now adds a <code>.0</code> suffix
10571to the result if it looks like an integer.
10572(For instance, the float 2.0 will be printed as <code>2.0</code>,
10573not as <code>2</code>.)
10574You should always use an explicit format
10575when you need a specific format for numbers.
1024410576
10245<li>
10246The event <em>tail return</em> in debug hooks was removed.
10247Instead, tail calls generate a special new event,
10248<em>tail call</em>, so that the debugger can know that
10249there will not be a corresponding return event.
10577
10578<p>
10579(Formally this is not an incompatibility,
10580because Lua does not specify how numbers are formatted as strings,
10581but some programs assumed a specific format.)
1025010582</li>
1025110583
1025210584<li>
10253Equality between function values has changed.
10254Now, a function definition may not create a new value;
10255it may reuse some previous value if there is no
10256observable difference to the new function.
10585The generational mode for the garbage collector was removed.
10586(It was an experimental feature in Lua&nbsp;5.2.)
1025710587</li>
1025810588
1025910589</ul>
r242885r242886
1026510595<ul>
1026610596
1026710597<li>
10268Function <code>module</code> is deprecated.
10269It is easy to set up a module with regular Lua code.
10270Modules are not expected to set global variables.
10598The <code>bit32</code> library has been deprecated.
10599It is easy to require a compatible external library or,
10600better yet, to replace its functions with appropriate bitwise operations.
10601(Keep in mind that <code>bit32</code> operates on 32-bit integers,
10602while the bitwise operators in standard Lua operate on 64-bit integers.)
1027110603</li>
1027210604
1027310605<li>
10274Functions <code>setfenv</code> and <code>getfenv</code> were removed,
10275because of the changes in environments.
10606The Table library now respects metamethods
10607for setting and getting elements.
1027610608</li>
1027710609
1027810610<li>
10279Function <code>math.log10</code> is deprecated.
10280Use <a href="#pdf-math.log"><code>math.log</code></a> with 10 as its second argument, instead.
10611The <a href="#pdf-ipairs"><code>ipairs</code></a> iterator now respects metamethods and
10612its <code>__ipairs</code> metamethod has been deprecated.
1028110613</li>
1028210614
1028310615<li>
10284Function <code>loadstring</code> is deprecated.
10285Use <code>load</code> instead; it now accepts string arguments
10286and are exactly equivalent to <code>loadstring</code>.
10616Option names in <a href="#pdf-io.read"><code>io.read</code></a> do not have a starting '<code>*</code>' anymore.
10617For compatibility, Lua will continue to ignore this character.
1028710618</li>
1028810619
1028910620<li>
10290Function <code>table.maxn</code> is deprecated.
10291Write it in Lua if you really need it.
10621The following functions were deprecated in the mathematical library:
10622<code>atan2</code>, <code>cosh</code>, <code>sinh</code>, <code>tanh</code>, <code>pow</code>,
10623<code>frexp</code>, and <code>ldexp</code>.
10624You can replace <code>math.pow(x,y)</code> with <code>x^y</code>;
10625you can replace <code>math.atan2</code> with <code>math.atan</code>,
10626which now accepts one or two parameters;
10627you can replace <code>math.ldexp(x,exp)</code> with <code>x * 2.0^exp</code>.
10628For the other operations,
10629you can either use an external library or
10630implement them in Lua.
1029210631</li>
1029310632
1029410633<li>
10295Function <code>os.execute</code> now returns <b>true</b> when command
10296terminates successfully and <b>nil</b> plus error information
10297otherwise.
10634The searcher for C loaders used by <a href="#pdf-require"><code>require</code></a>
10635changed the way it handles versioned names.
10636Now, the version should come after the module name
10637(as is usual in most other tools).
10638For compatibility, that searcher still tries the old format
10639if it cannot find an open function according to the new style.
10640(Lua&nbsp;5.2 already worked that way,
10641but it did not document the change.)
1029810642</li>
1029910643
10300<li>
10301Function <code>unpack</code> was moved into the table library
10302and therefore must be called as <a href="#pdf-table.unpack"><code>table.unpack</code></a>.
10303</li>
10304
10305<li>
10306Character class <code>%z</code> in patterns is deprecated,
10307as now patterns may contain '<code>\0</code>' as a regular character.
10308</li>
10309
10310<li>
10311The table <code>package.loaders</code> was renamed <code>package.searchers</code>.
10312</li>
10313
10314<li>
10315Lua does not have bytecode verification anymore.
10316So, all functions that load code
10317(<a href="#pdf-load"><code>load</code></a> and <a href="#pdf-loadfile"><code>loadfile</code></a>)
10318are potentially insecure when loading untrusted binary data.
10319(Actually, those functions were already insecure because
10320of flaws in the verification algorithm.)
10321When in doubt,
10322use the <code>mode</code> argument of those functions
10323to restrict them to loading textual chunks.
10324</li>
10325
10326<li>
10327The standard paths in the official distribution may
10328change between versions.
10329</li>
10330
1033110644</ul>
1033210645
1033310646
1033410647
1033510648
1033610649<h2>8.3 &ndash; <a name="8.3">Changes in the API</a></h2>
10337<ul>
1033810650
10339<li>
10340Pseudoindex <code>LUA_GLOBALSINDEX</code> was removed.
10341You must get the global environment from the registry
10342(see <a href="#4.5">&sect;4.5</a>).
10343</li>
1034410651
10345<li>
10346Pseudoindex <code>LUA_ENVIRONINDEX</code>
10347and functions <code>lua_getfenv</code>/<code>lua_setfenv</code>
10348were removed,
10349as C&nbsp;functions no longer have environments.
10350</li>
10652<ul>
1035110653
1035210654<li>
10353Function <code>luaL_register</code> is deprecated.
10354Use <a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a> so that your module does not create globals.
10355(Modules are not expected to set global variables anymore.)
10655Continuation functions now receive as parameters what they needed
10656to get through <code>lua_getctx</code>,
10657so <code>lua_getctx</code> has been removed.
10658Adapt your code accordingly.
1035610659</li>
1035710660
1035810661<li>
10359The <code>osize</code> argument to the allocation function
10360may not be zero when creating a new block,
10361that is, when <code>ptr</code> is <code>NULL</code>
10362(see <a href="#lua_Alloc"><code>lua_Alloc</code></a>).
10363Use only the test <code>ptr == NULL</code> to check whether
10364the block is new.
10662Function <a href="#lua_dump"><code>lua_dump</code></a> has an extra parameter, <code>strip</code>.
10663Use 0 as the value of this parameter to get the old behavior.
1036510664</li>
1036610665
1036710666<li>
10368Finalizers (<code>__gc</code> metamethods) for userdata are called in the
10369reverse order that they were marked for finalization,
10370not that they were created (see <a href="#2.5.1">&sect;2.5.1</a>).
10371(Most userdata are marked immediately after they are created.)
10372Moreover,
10373if the metatable does not have a <code>__gc</code> field when set,
10374the finalizer will not be called,
10375even if it is set later.
10667Functions to inject/project unsigned integers
10668(<code>lua_pushunsigned</code>, <code>lua_tounsigned</code>, <code>lua_tounsignedx</code>,
10669<code>luaL_checkunsigned</code>, <code>luaL_optunsigned</code>)
10670were deprecated.
10671Use their signed equivalents with a type cast.
1037610672</li>
1037710673
1037810674<li>
10379<code>luaL_typerror</code> was removed.
10380Write your own version if you need it.
10675Macros to project non-default integer types
10676(<code>luaL_checkint</code>, <code>luaL_optint</code>, <code>luaL_checklong</code>, <code>luaL_optlong</code>)
10677were deprecated.
10678Use their equivalent over <a href="#lua_Integer"><code>lua_Integer</code></a> with a type cast
10679(or, when possible, use <a href="#lua_Integer"><code>lua_Integer</code></a> in your code).
1038110680</li>
1038210681
10383<li>
10384Function <code>lua_cpcall</code> is deprecated.
10385You can simply push the function with <a href="#lua_pushcfunction"><code>lua_pushcfunction</code></a>
10386and call it with <a href="#lua_pcall"><code>lua_pcall</code></a>.
10387</li>
10388
10389<li>
10390Functions <code>lua_equal</code> and <code>lua_lessthan</code> are deprecated.
10391Use the new <a href="#lua_compare"><code>lua_compare</code></a> with appropriate options instead.
10392</li>
10393
10394<li>
10395Function <code>lua_objlen</code> was renamed <a href="#lua_rawlen"><code>lua_rawlen</code></a>.
10396</li>
10397
10398<li>
10399Function <a href="#lua_load"><code>lua_load</code></a> has an extra parameter, <code>mode</code>.
10400Pass <code>NULL</code> to simulate the old behavior.
10401</li>
10402
10403<li>
10404Function <a href="#lua_resume"><code>lua_resume</code></a> has an extra parameter, <code>from</code>.
10405Pass <code>NULL</code> or the thread doing the call.
10406</li>
10407
1040810682</ul>
1040910683
1041010684
r242885r242886
1041410688
1041510689<p>
1041610690Here is the complete syntax of Lua in extended BNF.
10417(It does not describe operator precedences.)
10691As usual in extended BNF,
10692{A} means 0 or more As,
10693and [A] means an optional A.
10694(For operator precedences, see <a href="#3.4.8">&sect;3.4.8</a>;
10695for a description of the terminals
10696Name, Numeral,
10697and LiteralString, see <a href="#3.1">&sect;3.1</a>.)
1041810698
1041910699
1042010700
r242885r242886
1045510735
1045610736   explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1045710737
10458   exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | &lsquo;<b>...</b>&rsquo; | functiondef |
10738   exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef |
1045910739       prefixexp | tableconstructor | exp binop exp | unop exp
1046010740
1046110741   prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
1046210742
1046310743   functioncall ::=  prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
1046410744
10465   args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | String
10745   args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString
1046610746
1046710747   functiondef ::= <b>function</b> funcbody
1046810748
r242885r242886
1047810758
1047910759   fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
1048010760
10481   binop ::= &lsquo;<b>+</b>&rsquo; | &lsquo;<b>-</b>&rsquo; | &lsquo;<b>*</b>&rsquo; | &lsquo;<b>/</b>&rsquo; | &lsquo;<b>^</b>&rsquo; | &lsquo;<b>%</b>&rsquo; | &lsquo;<b>..</b>&rsquo; |
10761   binop ::=  &lsquo;<b>+</b>&rsquo; | &lsquo;<b>-</b>&rsquo; | &lsquo;<b>*</b>&rsquo; | &lsquo;<b>/</b>&rsquo; | &lsquo;<b>//</b>&rsquo; | &lsquo;<b>^</b>&rsquo; | &lsquo;<b>%</b>&rsquo; |
10762       &lsquo;<b>&amp;</b>&rsquo; | &lsquo;<b>~</b>&rsquo; | &lsquo;<b>|</b>&rsquo; | &lsquo;<b>&gt;&gt;</b>&rsquo; | &lsquo;<b>&lt;&lt;</b>&rsquo; | &lsquo;<b>..</b>&rsquo; |
1048210763       &lsquo;<b>&lt;</b>&rsquo; | &lsquo;<b>&lt;=</b>&rsquo; | &lsquo;<b>&gt;</b>&rsquo; | &lsquo;<b>&gt;=</b>&rsquo; | &lsquo;<b>==</b>&rsquo; | &lsquo;<b>~=</b>&rsquo; |
1048310764       <b>and</b> | <b>or</b>
1048410765
10485   unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo;
10766   unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
1048610767
1048710768</pre>
1048810769
r242885r242886
1049410775
1049510776
1049610777
10778
1049710779<HR>
1049810780<SMALL CLASS="footer">
1049910781Last update:
10500Thu Mar 21 12:58:59 BRT 2013
10782Tue Jan  6 10:10:50 BRST 2015
1050110783</SMALL>
1050210784<!--
10503Last change: revised for Lua 5.2.2
10785Last change: revised for Lua 5.3.0 (final)
1050410786-->
1050510787
1050610788</body></html>
trunk/3rdparty/lua/doc/readme.html
r242885r242886
11<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
22<HTML>
33<HEAD>
4<TITLE>Lua 5.2 readme</TITLE>
4<TITLE>Lua 5.3 readme</TITLE>
55<LINK REL="stylesheet" TYPE="text/css" HREF="lua.css">
66<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-1">
77<STYLE TYPE="text/css">
88blockquote, .display {
99   border: solid #a0a0a0 2px ;
10   border-radius: 8px ;
1110   padding: 1em ;
1211   margin: 0px ;
12   border-radius: 8px ;
1313}
1414
1515.display {
r242885r242886
3131<HR>
3232<H1>
3333<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A>
34Welcome to Lua 5.2
34Welcome to Lua 5.3.0
3535</H1>
3636
3737<P>
r242885r242886
7070updated
7171<A HREF="http://www.lua.org/docs.html">documentation</A>,
7272especially the
73<A HREF="http://www.lua.org/manual/5.2/">reference manual</A>,
73<A HREF="http://www.lua.org/manual/5.3/">reference manual</A>,
7474which may differ slightly from the
7575<A HREF="contents.html">local copy</A>
7676distributed in this package.
r242885r242886
9898get a binary from
9999<A HREF="http://lua-users.org/wiki/LuaBinaries">LuaBinaries</A>.
100100Try also
101<A HREF="http://luaforwindows.luaforge.net/">Lua for Windows</A>,
102an easy-to-use distribution of Lua that includes many useful libraries.
101<A HREF="http://luadist.org/">LuaDist</A>,
102a multi-platform distribution of Lua that includes batteries.
103103
104104<H3>Building Lua</H3>
105105
r242885r242886
110110<OL>
111111<LI>
112112Open a terminal window and move to
113the top-level directory, which is named <TT>lua-5.2.3</TT>.
114The Makefile there controls both the build process and the installation process.
113the top-level directory, which is named <TT>lua-5.3.0</TT>.
114The <TT>Makefile</TT> there controls both the build process and the installation process.
115115<P>
116116<LI>
117117  Do "<KBD>make</KBD>" and see if your platform is listed.
118118  The platforms currently supported are:
119119<P>
120120<P CLASS="display">
121   aix ansi bsd freebsd generic linux macosx mingw posix solaris
121   aix bsd c89 freebsd generic linux macosx mingw posix solaris
122122</P>
123123<P>
124124  If your platform is listed, just do "<KBD>make xxx</KBD>", where xxx
125125  is your platform name.
126126<P>
127127  If your platform is not listed, try the closest one or posix, generic,
128  ansi, in this order.
128  c89, in this order.
129129<P>
130130<LI>
131131The compilation takes only a few moments
r242885r242886
136136<P>
137137<LI>
138138  To check that Lua has been built correctly, do "<KBD>make test</KBD>"
139  after building Lua. This will run the interpreter and print its version string.
139  after building Lua. This will run the interpreter and print its version.
140140</OL>
141141<P>
142142If you're running Linux and get compilation errors,
r242885r242886
148148<P>
149149  Once you have built Lua, you may want to install it in an official
150150  place in your system. In this case, do "<KBD>make install</KBD>". The official
151  place and the way to install files are defined in the Makefile. You'll
151  place and the way to install files are defined in the <TT>Makefile</TT>. You'll
152152  probably need the right permissions to install files.
153153
154154<P>
r242885r242886
158158<P>
159159  To install Lua locally, do "<KBD>make local</KBD>".
160160  This will create a directory <TT>install</TT> with subdirectories
161  <TT>bin</TT>, <TT>include</TT>, <TT>lib</TT>, <TT>man</TT>,
161  <TT>bin</TT>, <TT>include</TT>, <TT>lib</TT>, <TT>man</TT>, <TT>share</TT>,
162162  and install Lua as listed below.
163163
164164  To install Lua locally, but in some other directory, do
165165  "<KBD>make install INSTALL_TOP=xxx</KBD>", where xxx is your chosen directory.
166  The installation starts in the <TT>src</TT> and <TT>doc</TT> directories,
167  so take care if <TT>INSTALL_TOP</TT> is not an absolute path.
166168
167169<DL CLASS="display">
168170<DT>
r242885r242886
172174<DT>
173175    include:
174176<DD>
175    lua.h luaconf.h lualib.h lauxlib.h lua.hpp
177    lauxlib.h lua.h lua.hpp luaconf.h lualib.h
176178<DT>
177179    lib:
178180<DD>
r242885r242886
186188<P>
187189  These are the only directories you need for development.
188190  If you only want to run Lua programs,
189  you only need the files in bin and man.
190  The files in include and lib are needed for
191  you only need the files in <TT>bin</TT> and <TT>man</TT>.
192  The files in <TT>include</TT> and <TT>lib</TT> are needed for
191193  embedding Lua in C or C++ programs.
192194
193195<H3><A NAME="customization">Customization</A></H3>
r242885r242886
203205  You don't actually need to edit the Makefiles because you may set the
204206  relevant variables in the command line when invoking make.
205207  Nevertheless, it's probably best to edit and save the Makefiles to
206  record the changes you need.
208  record the changes you've made.
207209
208210<P>
209211  On the other hand, if you need to customize some Lua features, you'll need
r242885r242886
212214  it will be used by any Lua clients that you build, to ensure consistency.
213215  Further customization is available to experts by editing the Lua sources.
214216
215<P>
216  We strongly recommend that you enable dynamic loading in <TT>src/luaconf.h</TT>.
217  This is done automatically for all platforms listed above that have
218  this feature and also for Windows.
219
220217<H3><A NAME="other">Building Lua on other systems</A></H3>
221218
222219<P>
r242885r242886
233230lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c ltable.c
234231ltm.c lundump.c lvm.c lzio.c
235232lauxlib.c lbaselib.c lbitlib.c lcorolib.c ldblib.c liolib.c
236lmathlib.c loslib.c lstrlib.c ltablib.c loadlib.c linit.c
233lmathlib.c loslib.c lstrlib.c ltablib.c lutf8lib.c loadlib.c linit.c
237234<DT>
238235interpreter:
239236<DD>
r242885r242886
254251  be linked statically into the host program and its symbols exported for
255252  dynamic linking; <TT>src/Makefile</TT> does this for the Lua interpreter.
256253  For Windows, we recommend that the Lua library be a DLL.
254  In all cases, the compiler luac should be linked statically.
257255
258256<P>
259257  As mentioned above, you may edit <TT>src/luaconf.h</TT> to customize
260258  some features before building Lua.
261259
262<H2><A NAME="changes">Changes since Lua 5.1</A></H2>
260<H2><A NAME="changes">Changes since Lua 5.2</A></H2>
263261
264262<P>
265Here are the main changes introduced in Lua 5.2.
263Here are the main changes introduced in Lua 5.3.
266264The
267265<A HREF="contents.html">reference manual</A>
268266lists the
r242885r242886
270268
271269<H3>Main changes</H3>
272270<UL>
273<LI> yieldable pcall and metamethods
274<LI> new lexical scheme for globals
275<LI> ephemeron tables
276<LI> new library for bitwise operations
277<LI> light C functions
278<LI> emergency garbage collector
279<LI> <CODE>goto</CODE> statement
280<LI> finalizers for tables
271<LI> integers (64-bit by default)
272<LI> official support for 32-bit numbers
273<LI> bitwise operators
274<LI> basic utf-8 support
275<LI> functions for packing and unpacking values
276
281277</UL>
282278
283Here are the other changes introduced in Lua 5.2:
279Here are the other changes introduced in Lua 5.3:
284280<H3>Language</H3>
285281<UL>
286<LI> no more fenv for threads or functions
287<LI> tables honor the <CODE>__len</CODE> metamethod
288<LI> hex and <CODE>\z</CODE> escapes in strings
289<LI> support for hexadecimal floats
290<LI> order metamethods work for different types
291<LI> no more verification of opcode consistency
292<LI> hook event "tail return" replaced by "tail call"
293<LI> empty statement
294<LI> <CODE>break</CODE> statement may appear in the middle of a block
282<LI> userdata can have any Lua value as uservalue
283<LI> integer division
284<LI> more flexible rules for some metamethods
295285</UL>
296286
297287<H3>Libraries</H3>
298288<UL>
299<LI> arguments for function called through <CODE>xpcall</CODE>
300<LI> optional 'mode' argument to load and loadfile (to control binary x text)
301<LI> optional 'env' argument to load and loadfile (environment for loaded chunk)
302<LI> <CODE>loadlib</CODE> may load libraries with global names (RTLD_GLOBAL)
303<LI> new function <CODE>package.searchpath</CODE>
304<LI> modules receive their paths when loaded
305<LI> optional base in <CODE>math.log</CODE>
306<LI> optional separator in <CODE>string.rep</CODE>
307<LI> <CODE>file:write</CODE> returns <CODE>file</CODE>
308<LI> closing a pipe returns exit status
309<LI> <CODE>os.exit</CODE> may close state
310<LI> new metamethods <CODE>__pairs</CODE> and <CODE>__ipairs</CODE>
311<LI> new option 'isrunning' for <CODE>collectgarbage</CODE> and <CODE>lua_gc</CODE>
312<LI> frontier patterns
313<LI> <CODE>\0</CODE> in patterns
314<LI> new option <CODE>*L</CODE> for <CODE>io.read</CODE>
315<LI> options for <CODE>io.lines</CODE>
316<LI> <CODE>debug.getlocal</CODE> can access function varargs
289<LI> <CODE>ipairs</CODE> and the table library respect metamethods
290<LI> strip option in <CODE>string.dump</CODE>
291<LI> table library respects metamethods
292<LI> new function <CODE>table.move</CODE>
293<LI> new function <CODE>string.pack</CODE>
294<LI> new function <CODE>string.unpack</CODE>
295<LI> new function <CODE>string.packsize</CODE>
317296</UL>
318297
319298<H3>C API</H3>
320299<UL>
321<LI> main thread predefined in the registry
322<LI> new functions
323<CODE>lua_absindex</CODE>,
324<CODE>lua_arith</CODE>,
325<CODE>lua_compare</CODE>,
326<CODE>lua_copy</CODE>,
327<CODE>lua_len</CODE>,
328<CODE>lua_rawgetp</CODE>,
329<CODE>lua_rawsetp</CODE>,
330<CODE>lua_upvalueid</CODE>,
331<CODE>lua_upvaluejoin</CODE>,
332<CODE>lua_version</CODE>.
333<LI> new functions
334<CODE>luaL_checkversion</CODE>,
335<CODE>luaL_setmetatable</CODE>,
336<CODE>luaL_testudata</CODE>,
337<CODE>luaL_tolstring</CODE>.
338<LI> <CODE>lua_pushstring</CODE> and <CODE>pushlstring</CODE> return string
339<LI> <CODE>nparams</CODE> and <CODE>isvararg</CODE> available in debug API
340<LI> new <CODE>lua_Unsigned</CODE>
300<LI> simpler API for continuation functions in C
301<LI> <CODE>lua_gettable</CODE> and similar functions return type of resulted value
302<LI> strip option in <CODE>lua_dump</CODE>
303<LI> new function: <CODE>lua_geti</CODE>
304<LI> new function: <CODE>lua_seti</CODE>
305<LI> new function: <CODE>lua_isyieldable</CODE>
306<LI> new function: <CODE>lua_numbertointeger</CODE>
307<LI> new function: <CODE>lua_rotate</CODE>
308<LI> new function: <CODE>lua_stringtonumber</CODE>
341309</UL>
342310
343<H3>Implementation</H3>
344<UL>
345<LI> max constants per function raised to 2<SUP>26</SUP>
346<LI> generational mode for garbage collection (experimental)
347<LI> NaN trick (experimental)
348<LI> internal (immutable) version of ctypes
349<LI> simpler implementation for string buffers
350<LI> parser uses much less C-stack space (no more auto arrays)
351</UL>
352
353311<H3>Lua standalone interpreter</H3>
354312<UL>
355<LI> new <CODE>-E</CODE> option to avoid environment variables
356<LI> handling of non-string error messages
313<LI> can be used as calculator; no need to prefix with '='
314<LI> <CODE>arg</CODE> table available to all code
357315</UL>
358316
359317<H2><A NAME="license">License</A></H2>
r242885r242886
375333<A HREF="http://www.lua.org/license.html">this</A>.
376334
377335<BLOCKQUOTE STYLE="padding-bottom: 0em">
378Copyright &copy; 1994&ndash;2013 Lua.org, PUC-Rio.
336Copyright &copy; 1994&ndash;2015 Lua.org, PUC-Rio.
379337
380338<P>
381339Permission is hereby granted, free of charge, to any person obtaining a copy
r242885r242886
403361<HR>
404362<SMALL CLASS="footer">
405363Last update:
406Sat Nov  9 22:39:16 BRST 2013
364Fri Dec 12 09:58:42 BRST 2014
407365</SMALL>
408366<!--
409Last change: revised for Lua 5.2.3
367Last change: updated for Lua 5.3.0 (final)
410368-->
411369
412370</BODY>
trunk/3rdparty/lua/src/Makefile
r242885r242886
66# Your platform. See PLATS for possible values.
77PLAT= none
88
9CC= gcc
10CFLAGS= -O2 -Wall -DLUA_COMPAT_ALL $(SYSCFLAGS) $(MYCFLAGS)
9CC= gcc -std=gnu99
10CFLAGS= -O2 -Wall -Wextra -DLUA_COMPAT_5_2 $(SYSCFLAGS) $(MYCFLAGS)
1111LDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS)
1212LIBS= -lm $(SYSLIBS) $(MYLIBS)
1313
r242885r242886
2626
2727# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
2828
29PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris
29PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
3030
3131LUA_A=   liblua.a
3232CORE_O=   lapi.o lcode.o lctype.o ldebug.o ldo.o ldump.o lfunc.o lgc.o llex.o \
3333   lmem.o lobject.o lopcodes.o lparser.o lstate.o lstring.o ltable.o \
3434   ltm.o lundump.o lvm.o lzio.o
3535LIB_O=   lauxlib.o lbaselib.o lbitlib.o lcorolib.o ldblib.o liolib.o \
36   lmathlib.o loslib.o lstrlib.o ltablib.o loadlib.o linit.o
36   lmathlib.o loslib.o lstrlib.o ltablib.o lutf8lib.o loadlib.o linit.o
3737BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS)
3838
3939LUA_T=   lua
r242885r242886
9191aix:
9292   $(MAKE) $(ALL) CC="xlc" CFLAGS="-O2 -DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-ldl" SYSLDFLAGS="-brtl -bexpall"
9393
94ansi:
95   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_ANSI"
96
9794bsd:
9895   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-Wl,-E"
9996
97c89:
98   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_C89" CC="gcc -std=c89"
99   @echo ''
100   @echo '*** C89 does not guarantee 64-bit integers for Lua.'
101   @echo ''
102
103
100104freebsd:
101105   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -lreadline"
102106
r242885r242886
109113   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_MACOSX" SYSLIBS="-lreadline" CC=cc
110114
111115mingw:
112   $(MAKE) "LUA_A=lua52.dll" "LUA_T=lua.exe" \
116   $(MAKE) "LUA_A=lua53.dll" "LUA_T=lua.exe" \
113117   "AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \
114118   "SYSCFLAGS=-DLUA_BUILD_AS_DLL" "SYSLIBS=" "SYSLDFLAGS=-s" lua.exe
115119   $(MAKE) "LUAC_T=luac.exe" luac.exe
r242885r242886
118122   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX"
119123
120124solaris:
121   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-ldl"
125   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN -D_REENTRANT" SYSLIBS="-ldl"
122126
123127# list targets that do not create files (but not all makes understand .PHONY)
124128.PHONY: all $(PLATS) default o a clean depend echo none
125129
126130# DO NOT DELETE
127131
128lapi.o: lapi.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \
129 lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h ltable.h lundump.h \
130 lvm.h
131lauxlib.o: lauxlib.c lua.h luaconf.h lauxlib.h
132lbaselib.o: lbaselib.c lua.h luaconf.h lauxlib.h lualib.h
133lbitlib.o: lbitlib.c lua.h luaconf.h lauxlib.h lualib.h
134lcode.o: lcode.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \
135 lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lgc.h \
136 lstring.h ltable.h lvm.h
137lcorolib.o: lcorolib.c lua.h luaconf.h lauxlib.h lualib.h
138lctype.o: lctype.c lctype.h lua.h luaconf.h llimits.h
139ldblib.o: ldblib.c lua.h luaconf.h lauxlib.h lualib.h
140ldebug.o: ldebug.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h \
141 ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h ldebug.h ldo.h \
142 lfunc.h lstring.h lgc.h ltable.h lvm.h
143ldo.o: ldo.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h ltm.h \
144 lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h lparser.h \
145 lstring.h ltable.h lundump.h lvm.h
146ldump.o: ldump.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h \
147 lzio.h lmem.h lundump.h
148lfunc.o: lfunc.c lua.h luaconf.h lfunc.h lobject.h llimits.h lgc.h \
149 lstate.h ltm.h lzio.h lmem.h
150lgc.o: lgc.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
151 lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
152linit.o: linit.c lua.h luaconf.h lualib.h lauxlib.h
153liolib.o: liolib.c lua.h luaconf.h lauxlib.h lualib.h
154llex.o: llex.c lua.h luaconf.h lctype.h llimits.h ldo.h lobject.h \
155 lstate.h ltm.h lzio.h lmem.h llex.h lparser.h lstring.h lgc.h ltable.h
156lmathlib.o: lmathlib.c lua.h luaconf.h lauxlib.h lualib.h
157lmem.o: lmem.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
158 ltm.h lzio.h lmem.h ldo.h lgc.h
159loadlib.o: loadlib.c lua.h luaconf.h lauxlib.h lualib.h
160lobject.o: lobject.c lua.h luaconf.h lctype.h llimits.h ldebug.h lstate.h \
161 lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h lvm.h
162lopcodes.o: lopcodes.c lopcodes.h llimits.h lua.h luaconf.h
163loslib.o: loslib.c lua.h luaconf.h lauxlib.h lualib.h
164lparser.o: lparser.c lua.h luaconf.h lcode.h llex.h lobject.h llimits.h \
165 lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h ldo.h lfunc.h \
166 lstring.h lgc.h ltable.h
167lstate.o: lstate.c lua.h luaconf.h lapi.h llimits.h lstate.h lobject.h \
168 ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h lstring.h \
169 ltable.h
170lstring.o: lstring.c lua.h luaconf.h lmem.h llimits.h lobject.h lstate.h \
171 ltm.h lzio.h lstring.h lgc.h
172lstrlib.o: lstrlib.c lua.h luaconf.h lauxlib.h lualib.h
173ltable.o: ltable.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h \
174 ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
175ltablib.o: ltablib.c lua.h luaconf.h lauxlib.h lualib.h
176ltm.o: ltm.c lua.h luaconf.h lobject.h llimits.h lstate.h ltm.h lzio.h \
177 lmem.h lstring.h lgc.h ltable.h
178lua.o: lua.c lua.h luaconf.h lauxlib.h lualib.h
179luac.o: luac.c lua.h luaconf.h lauxlib.h lobject.h llimits.h lstate.h \
180 ltm.h lzio.h lmem.h lundump.h ldebug.h lopcodes.h
181lundump.o: lundump.c lua.h luaconf.h ldebug.h lstate.h lobject.h \
182 llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h lundump.h
183lvm.o: lvm.c lua.h luaconf.h ldebug.h lstate.h lobject.h llimits.h ltm.h \
184 lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h ltable.h lvm.h
185lzio.o: lzio.c lua.h luaconf.h llimits.h lmem.h lstate.h lobject.h ltm.h \
186 lzio.h
132lapi.o: lapi.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
133  lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lstring.h \
134  ltable.h lundump.h lvm.h
135lauxlib.o: lauxlib.c lprefix.h lua.h luaconf.h lauxlib.h
136lbaselib.o: lbaselib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
137lbitlib.o: lbitlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
138lcode.o: lcode.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
139  llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
140  ldo.h lgc.h lstring.h ltable.h lvm.h
141lcorolib.o: lcorolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
142lctype.o: lctype.c lprefix.h lctype.h lua.h luaconf.h llimits.h
143ldblib.o: ldblib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
144ldebug.o: ldebug.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
145  lobject.h ltm.h lzio.h lmem.h lcode.h llex.h lopcodes.h lparser.h \
146  ldebug.h ldo.h lfunc.h lstring.h lgc.h ltable.h lvm.h
147ldo.o: ldo.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
148  lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h lopcodes.h \
149  lparser.h lstring.h ltable.h lundump.h lvm.h
150ldump.o: ldump.c lprefix.h lua.h luaconf.h lobject.h llimits.h lstate.h \
151  ltm.h lzio.h lmem.h lundump.h
152lfunc.o: lfunc.c lprefix.h lua.h luaconf.h lfunc.h lobject.h llimits.h \
153  lgc.h lstate.h ltm.h lzio.h lmem.h
154lgc.o: lgc.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
155  llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lstring.h ltable.h
156linit.o: linit.c lprefix.h lua.h luaconf.h lualib.h lauxlib.h
157liolib.o: liolib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
158llex.o: llex.c lprefix.h lua.h luaconf.h lctype.h llimits.h ldo.h \
159  lobject.h lstate.h ltm.h lzio.h lmem.h lgc.h llex.h lparser.h lstring.h \
160  ltable.h
161lmathlib.o: lmathlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
162lmem.o: lmem.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
163  llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h
164loadlib.o: loadlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
165lobject.o: lobject.c lprefix.h lua.h luaconf.h lctype.h llimits.h \
166  ldebug.h lstate.h lobject.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h \
167  lvm.h
168lopcodes.o: lopcodes.c lprefix.h lopcodes.h llimits.h lua.h luaconf.h
169loslib.o: loslib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
170lparser.o: lparser.c lprefix.h lua.h luaconf.h lcode.h llex.h lobject.h \
171  llimits.h lzio.h lmem.h lopcodes.h lparser.h ldebug.h lstate.h ltm.h \
172  ldo.h lfunc.h lstring.h lgc.h ltable.h
173lstate.o: lstate.c lprefix.h lua.h luaconf.h lapi.h llimits.h lstate.h \
174  lobject.h ltm.h lzio.h lmem.h ldebug.h ldo.h lfunc.h lgc.h llex.h \
175  lstring.h ltable.h
176lstring.o: lstring.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
177  lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h
178lstrlib.o: lstrlib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
179ltable.o: ltable.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
180  llimits.h ltm.h lzio.h lmem.h ldo.h lgc.h lstring.h ltable.h lvm.h
181ltablib.o: ltablib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
182ltm.o: ltm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
183  llimits.h ltm.h lzio.h lmem.h ldo.h lstring.h lgc.h ltable.h lvm.h
184lua.o: lua.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
185luac.o: luac.c lprefix.h lua.h luaconf.h lauxlib.h lobject.h llimits.h \
186  lstate.h ltm.h lzio.h lmem.h lundump.h ldebug.h lopcodes.h
187lundump.o: lundump.c lprefix.h lua.h luaconf.h ldebug.h lstate.h \
188  lobject.h llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lstring.h lgc.h \
189  lundump.h
190lutf8lib.o: lutf8lib.c lprefix.h lua.h luaconf.h lauxlib.h lualib.h
191lvm.o: lvm.c lprefix.h lua.h luaconf.h ldebug.h lstate.h lobject.h \
192  llimits.h ltm.h lzio.h lmem.h ldo.h lfunc.h lgc.h lopcodes.h lstring.h \
193  ltable.h lvm.h
194lzio.o: lzio.c lprefix.h lua.h luaconf.h llimits.h lmem.h lstate.h \
195  lobject.h ltm.h lzio.h
187196
197# (end of Makefile)
trunk/3rdparty/lua/src/lapi.c
r242885r242886
11/*
2** $Id: lapi.c,v 2.171.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lapi.c,v 2.244 2014/12/26 14:43:45 roberto Exp $
33** Lua API
44** See Copyright Notice in lua.h
55*/
66
7#define lapi_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <stdarg.h>
914#include <string.h>
1015
11#define lapi_c
12#define LUA_CORE
13
1416#include "lua.h"
1517
1618#include "lapi.h"
r242885r242886
4345/* test for pseudo index */
4446#define ispseudo(i)      ((i) <= LUA_REGISTRYINDEX)
4547
48/* test for upvalue */
49#define isupvalue(i)      ((i) < LUA_REGISTRYINDEX)
50
4651/* test for valid but not pseudo index */
4752#define isstackindex(i, o)   (isvalid(o) && !ispseudo(i))
4853
49#define api_checkvalidindex(L, o)  api_check(L, isvalid(o), "invalid index")
54#define api_checkvalidindex(o)  api_check(isvalid(o), "invalid index")
5055
51#define api_checkstackindex(L, i, o)  \
52   api_check(L, isstackindex(i, o), "index not in the stack")
56#define api_checkstackindex(i, o)  \
57   api_check(isstackindex(i, o), "index not in the stack")
5358
5459
5560static TValue *index2addr (lua_State *L, int idx) {
5661  CallInfo *ci = L->ci;
5762  if (idx > 0) {
5863    TValue *o = ci->func + idx;
59    api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index");
64    api_check(idx <= ci->top - (ci->func + 1), "unacceptable index");
6065    if (o >= L->top) return NONVALIDVALUE;
6166    else return o;
6267  }
6368  else if (!ispseudo(idx)) {  /* negative index */
64    api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
69    api_check(idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
6570    return L->top + idx;
6671  }
6772  else if (idx == LUA_REGISTRYINDEX)
6873    return &G(L)->l_registry;
6974  else {  /* upvalues */
7075    idx = LUA_REGISTRYINDEX - idx;
71    api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
76    api_check(idx <= MAXUPVAL + 1, "upvalue index too large");
7277    if (ttislcf(ci->func))  /* light C function? */
7378      return NONVALIDVALUE;  /* it has no upvalues */
7479    else {
r242885r242886
8994}
9095
9196
92LUA_API int lua_checkstack (lua_State *L, int size) {
97LUA_API int lua_checkstack (lua_State *L, int n) {
9398  int res;
9499  CallInfo *ci = L->ci;
95100  lua_lock(L);
96  if (L->stack_last - L->top > size)  /* stack large enough? */
101  api_check(n >= 0, "negative 'n'");
102  if (L->stack_last - L->top > n)  /* stack large enough? */
97103    res = 1;  /* yes; check is OK */
98104  else {  /* no; need to grow stack */
99105    int inuse = cast_int(L->top - L->stack) + EXTRA_STACK;
100    if (inuse > LUAI_MAXSTACK - size)  /* can grow without overflow? */
106    if (inuse > LUAI_MAXSTACK - n)  /* can grow without overflow? */
101107      res = 0;  /* no */
102108    else  /* try to grow stack */
103      res = (luaD_rawrunprotected(L, &growstack, &size) == LUA_OK);
109      res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK);
104110  }
105  if (res && ci->top < L->top + size)
106    ci->top = L->top + size;  /* adjust frame top */
111  if (res && ci->top < L->top + n)
112    ci->top = L->top + n;  /* adjust frame top */
107113  lua_unlock(L);
108114  return res;
109115}
r242885r242886
114120  if (from == to) return;
115121  lua_lock(to);
116122  api_checknelems(from, n);
117  api_check(from, G(from) == G(to), "moving among independent states");
118  api_check(from, to->ci->top - to->top >= n, "not enough elements to move");
123  api_check(G(from) == G(to), "moving among independent states");
124  api_check(to->ci->top - to->top >= n, "not enough elements to move");
119125  from->top -= n;
120126  for (i = 0; i < n; i++) {
121127    setobj2s(to, to->top++, from->top + i);
r242885r242886
166172  StkId func = L->ci->func;
167173  lua_lock(L);
168174  if (idx >= 0) {
169    api_check(L, idx <= L->stack_last - (func + 1), "new top too large");
175    api_check(idx <= L->stack_last - (func + 1), "new top too large");
170176    while (L->top < (func + 1) + idx)
171177      setnilvalue(L->top++);
172178    L->top = (func + 1) + idx;
173179  }
174180  else {
175    api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top");
176    L->top += idx+1;  /* `subtract' index (index is negative) */
181    api_check(-(idx+1) <= (L->top - (func + 1)), "invalid new top");
182    L->top += idx+1;  /* 'subtract' index (index is negative) */
177183  }
178184  lua_unlock(L);
179185}
180186
181187
182LUA_API void lua_remove (lua_State *L, int idx) {
183  StkId p;
184  lua_lock(L);
185  p = index2addr(L, idx);
186  api_checkstackindex(L, idx, p);
187  while (++p < L->top) setobjs2s(L, p-1, p);
188  L->top--;
189  lua_unlock(L);
188/*
189** Reverse the stack segment from 'from' to 'to'
190** (auxiliary to 'lua_rotate')
191*/
192static void reverse (lua_State *L, StkId from, StkId to) {
193  for (; from < to; from++, to--) {
194    TValue temp;
195    setobj(L, &temp, from);
196    setobjs2s(L, from, to);
197    setobj2s(L, to, &temp);
198  }
190199}
191200
192201
193LUA_API void lua_insert (lua_State *L, int idx) {
194  StkId p;
195  StkId q;
202/*
203** Let x = AB, where A is a prefix of length 'n'. Then,
204** rotate x n == BA. But BA == (A^r . B^r)^r.
205*/
206LUA_API void lua_rotate (lua_State *L, int idx, int n) {
207  StkId p, t, m;
196208  lua_lock(L);
197  p = index2addr(L, idx);
198  api_checkstackindex(L, idx, p);
199  for (q = L->top; q > p; q--)  /* use L->top as a temporary */
200    setobjs2s(L, q, q - 1);
201  setobjs2s(L, p, L->top);
209  t = L->top - 1;  /* end of stack segment being rotated */
210  p = index2addr(L, idx);  /* start of segment */
211  api_checkstackindex(idx, p);
212  api_check((n >= 0 ? n : -n) <= (t - p + 1), "invalid 'n'");
213  m = (n >= 0 ? t - n : p - n - 1);  /* end of prefix */
214  reverse(L, p, m);  /* reverse the prefix with length 'n' */
215  reverse(L, m + 1, t);  /* reverse the suffix */
216  reverse(L, p, t);  /* reverse the entire segment */
202217  lua_unlock(L);
203218}
204219
205220
206static void moveto (lua_State *L, TValue *fr, int idx) {
207  TValue *to = index2addr(L, idx);
208  api_checkvalidindex(L, to);
221LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
222  TValue *fr, *to;
223  lua_lock(L);
224  fr = index2addr(L, fromidx);
225  to = index2addr(L, toidx);
226  api_checkvalidindex(to);
209227  setobj(L, to, fr);
210  if (idx < LUA_REGISTRYINDEX)  /* function upvalue? */
228  if (isupvalue(toidx))  /* function upvalue? */
211229    luaC_barrier(L, clCvalue(L->ci->func), fr);
212230  /* LUA_REGISTRYINDEX does not need gc barrier
213231     (collector revisits it before finishing collection) */
214}
215
216
217LUA_API void lua_replace (lua_State *L, int idx) {
218  lua_lock(L);
219  api_checknelems(L, 1);
220  moveto(L, L->top - 1, idx);
221  L->top--;
222232  lua_unlock(L);
223233}
224234
225235
226LUA_API void lua_copy (lua_State *L, int fromidx, int toidx) {
227  TValue *fr;
228  lua_lock(L);
229  fr = index2addr(L, fromidx);
230  moveto(L, fr, toidx);
231  lua_unlock(L);
232}
233
234
235236LUA_API void lua_pushvalue (lua_State *L, int idx) {
236237  lua_lock(L);
237238  setobj2s(L, L->top, index2addr(L, idx));
r242885r242886
248249
249250LUA_API int lua_type (lua_State *L, int idx) {
250251  StkId o = index2addr(L, idx);
251  return (isvalid(o) ? ttypenv(o) : LUA_TNONE);
252  return (isvalid(o) ? ttnov(o) : LUA_TNONE);
252253}
253254
254255
255256LUA_API const char *lua_typename (lua_State *L, int t) {
256257  UNUSED(L);
258  api_check(LUA_TNONE <= t && t < LUA_NUMTAGS, "invalid tag");
257259  return ttypename(t);
258260}
259261
r242885r242886
264266}
265267
266268
269LUA_API int lua_isinteger (lua_State *L, int idx) {
270  StkId o = index2addr(L, idx);
271  return ttisinteger(o);
272}
273
274
267275LUA_API int lua_isnumber (lua_State *L, int idx) {
268  TValue n;
276  lua_Number n;
269277  const TValue *o = index2addr(L, idx);
270278  return tonumber(o, &n);
271279}
272280
273281
274282LUA_API int lua_isstring (lua_State *L, int idx) {
275  int t = lua_type(L, idx);
276  return (t == LUA_TSTRING || t == LUA_TNUMBER);
283  const TValue *o = index2addr(L, idx);
284  return (ttisstring(o) || cvt2str(o));
277285}
278286
279287
280288LUA_API int lua_isuserdata (lua_State *L, int idx) {
281289  const TValue *o = index2addr(L, idx);
282  return (ttisuserdata(o) || ttislightuserdata(o));
290  return (ttisfulluserdata(o) || ttislightuserdata(o));
283291}
284292
285293
r242885r242886
291299
292300
293301LUA_API void lua_arith (lua_State *L, int op) {
294  StkId o1;  /* 1st operand */
295  StkId o2;  /* 2nd operand */
296302  lua_lock(L);
297  if (op != LUA_OPUNM) /* all other operations expect two operands */
298    api_checknelems(L, 2);
299  else {  /* for unary minus, add fake 2nd operand */
303  if (op != LUA_OPUNM && op != LUA_OPBNOT)
304    api_checknelems(L, 2);  /* all other operations expect two operands */
305  else {  /* for unary operations, add fake 2nd operand */
300306    api_checknelems(L, 1);
301307    setobjs2s(L, L->top, L->top - 1);
302308    L->top++;
303309  }
304  o1 = L->top - 2;
305  o2 = L->top - 1;
306  if (ttisnumber(o1) && ttisnumber(o2)) {
307    setnvalue(o1, luaO_arith(op, nvalue(o1), nvalue(o2)));
308  }
309  else
310    luaV_arith(L, o1, o1, o2, cast(TMS, op - LUA_OPADD + TM_ADD));
311  L->top--;
310  /* first operand at top - 2, second at top - 1; result go to top - 2 */
311  luaO_arith(L, op, L->top - 2, L->top - 1, L->top - 2);
312  L->top--;  /* remove second operand */
312313  lua_unlock(L);
313314}
314315
r242885r242886
321322  o2 = index2addr(L, index2);
322323  if (isvalid(o1) && isvalid(o2)) {
323324    switch (op) {
324      case LUA_OPEQ: i = equalobj(L, o1, o2); break;
325      case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;
325326      case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
326327      case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
327      default: api_check(L, 0, "invalid option");
328      default: api_check(0, "invalid option");
328329    }
329330  }
330331  lua_unlock(L);
r242885r242886
332333}
333334
334335
335LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *isnum) {
336  TValue n;
337  const TValue *o = index2addr(L, idx);
338  if (tonumber(o, &n)) {
339    if (isnum) *isnum = 1;
340    return nvalue(o);
341  }
342  else {
343    if (isnum) *isnum = 0;
344    return 0;
345  }
336LUA_API size_t lua_stringtonumber (lua_State *L, const char *s) {
337  size_t sz = luaO_str2num(s, L->top);
338  if (sz != 0)
339    api_incr_top(L);
340  return sz;
346341}
347342
348343
349LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum) {
350  TValue n;
344LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
345  lua_Number n;
351346  const TValue *o = index2addr(L, idx);
352  if (tonumber(o, &n)) {
353    lua_Integer res;
354    lua_Number num = nvalue(o);
355    lua_number2integer(res, num);
356    if (isnum) *isnum = 1;
357    return res;
358  }
359  else {
360    if (isnum) *isnum = 0;
361    return 0;
362  }
347  int isnum = tonumber(o, &n);
348  if (!isnum)
349    n = 0;  /* call to 'tonumber' may change 'n' even if it fails */
350  if (pisnum) *pisnum = isnum;
351  return n;
363352}
364353
365354
366LUA_API lua_Unsigned lua_tounsignedx (lua_State *L, int idx, int *isnum) {
367  TValue n;
355LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
356  lua_Integer res;
368357  const TValue *o = index2addr(L, idx);
369  if (tonumber(o, &n)) {
370    lua_Unsigned res;
371    lua_Number num = nvalue(o);
372    lua_number2unsigned(res, num);
373    if (isnum) *isnum = 1;
374    return res;
375  }
376  else {
377    if (isnum) *isnum = 0;
378    return 0;
379  }
358  int isnum = tointeger(o, &res);
359  if (!isnum)
360    res = 0;  /* call to 'tointeger' may change 'n' even if it fails */
361  if (pisnum) *pisnum = isnum;
362  return res;
380363}
381364
382365
r242885r242886
389372LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
390373  StkId o = index2addr(L, idx);
391374  if (!ttisstring(o)) {
392    lua_lock(L);  /* `luaV_tostring' may create a new string */
393    if (!luaV_tostring(L, o)) {  /* conversion failed? */
375    if (!cvt2str(o)) {  /* not convertible? */
394376      if (len != NULL) *len = 0;
395      lua_unlock(L);
396377      return NULL;
397378    }
379    lua_lock(L);  /* 'luaO_tostring' may create a new string */
398380    luaC_checkGC(L);
399381    o = index2addr(L, idx);  /* previous call may reallocate the stack */
382    luaO_tostring(L, o);
400383    lua_unlock(L);
401384  }
402385  if (len != NULL) *len = tsvalue(o)->len;
r242885r242886
406389
407390LUA_API size_t lua_rawlen (lua_State *L, int idx) {
408391  StkId o = index2addr(L, idx);
409  switch (ttypenv(o)) {
392  switch (ttnov(o)) {
410393    case LUA_TSTRING: return tsvalue(o)->len;
411394    case LUA_TUSERDATA: return uvalue(o)->len;
412395    case LUA_TTABLE: return luaH_getn(hvalue(o));
r242885r242886
426409
427410LUA_API void *lua_touserdata (lua_State *L, int idx) {
428411  StkId o = index2addr(L, idx);
429  switch (ttypenv(o)) {
430    case LUA_TUSERDATA: return (rawuvalue(o) + 1);
412  switch (ttnov(o)) {
413    case LUA_TUSERDATA: return getudatamem(uvalue(o));
431414    case LUA_TLIGHTUSERDATA: return pvalue(o);
432415    default: return NULL;
433416  }
r242885r242886
472455
473456LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
474457  lua_lock(L);
475  setnvalue(L->top, n);
476  luai_checknum(L, L->top,
477    luaG_runerror(L, "C API - attempt to push a signaling NaN"));
458  setfltvalue(L->top, n);
478459  api_incr_top(L);
479460  lua_unlock(L);
480461}
r242885r242886
482463
483464LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
484465  lua_lock(L);
485  setnvalue(L->top, cast_num(n));
466  setivalue(L->top, n);
486467  api_incr_top(L);
487468  lua_unlock(L);
488469}
489470
490471
491LUA_API void lua_pushunsigned (lua_State *L, lua_Unsigned u) {
492  lua_Number n;
493  lua_lock(L);
494  n = lua_unsigned2number(u);
495  setnvalue(L->top, n);
496  api_incr_top(L);
497  lua_unlock(L);
498}
499
500
501472LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {
502473  TString *ts;
503474  lua_lock(L);
r242885r242886
558529    setfvalue(L->top, fn);
559530  }
560531  else {
561    Closure *cl;
532    CClosure *cl;
562533    api_checknelems(L, n);
563    api_check(L, n <= MAXUPVAL, "upvalue index too large");
534    api_check(n <= MAXUPVAL, "upvalue index too large");
564535    luaC_checkGC(L);
565536    cl = luaF_newCclosure(L, n);
566    cl->c.f = fn;
537    cl->f = fn;
567538    L->top -= n;
568    while (n--)
569      setobj2n(L, &cl->c.upvalue[n], L->top + n);
539    while (n--) {
540      setobj2n(L, &cl->upvalue[n], L->top + n);
541      /* does not need barrier because closure is white */
542    }
570543    setclCvalue(L, L->top, cl);
571544  }
572545  api_incr_top(L);
r242885r242886
605578*/
606579
607580
608LUA_API void lua_getglobal (lua_State *L, const char *var) {
581LUA_API int lua_getglobal (lua_State *L, const char *name) {
609582  Table *reg = hvalue(&G(L)->l_registry);
610583  const TValue *gt;  /* global table */
611584  lua_lock(L);
612585  gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
613  setsvalue2s(L, L->top++, luaS_new(L, var));
586  setsvalue2s(L, L->top++, luaS_new(L, name));
614587  luaV_gettable(L, gt, L->top - 1, L->top - 1);
615588  lua_unlock(L);
589  return ttnov(L->top - 1);
616590}
617591
618592
619LUA_API void lua_gettable (lua_State *L, int idx) {
593LUA_API int lua_gettable (lua_State *L, int idx) {
620594  StkId t;
621595  lua_lock(L);
622596  t = index2addr(L, idx);
623597  luaV_gettable(L, t, L->top - 1, L->top - 1);
624598  lua_unlock(L);
599  return ttnov(L->top - 1);
625600}
626601
627602
628LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
603LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
629604  StkId t;
630605  lua_lock(L);
631606  t = index2addr(L, idx);
r242885r242886
633608  api_incr_top(L);
634609  luaV_gettable(L, t, L->top - 1, L->top - 1);
635610  lua_unlock(L);
611  return ttnov(L->top - 1);
636612}
637613
638614
639LUA_API void lua_rawget (lua_State *L, int idx) {
615LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
640616  StkId t;
641617  lua_lock(L);
642618  t = index2addr(L, idx);
643  api_check(L, ttistable(t), "table expected");
619  setivalue(L->top, n);
620  api_incr_top(L);
621  luaV_gettable(L, t, L->top - 1, L->top - 1);
622  lua_unlock(L);
623  return ttnov(L->top - 1);
624}
625
626
627LUA_API int lua_rawget (lua_State *L, int idx) {
628  StkId t;
629  lua_lock(L);
630  t = index2addr(L, idx);
631  api_check(ttistable(t), "table expected");
644632  setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
645633  lua_unlock(L);
634  return ttnov(L->top - 1);
646635}
647636
648637
649LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {
638LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
650639  StkId t;
651640  lua_lock(L);
652641  t = index2addr(L, idx);
653  api_check(L, ttistable(t), "table expected");
642  api_check(ttistable(t), "table expected");
654643  setobj2s(L, L->top, luaH_getint(hvalue(t), n));
655644  api_incr_top(L);
656645  lua_unlock(L);
646  return ttnov(L->top - 1);
657647}
658648
659649
660LUA_API void lua_rawgetp (lua_State *L, int idx, const void *p) {
650LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
661651  StkId t;
662652  TValue k;
663653  lua_lock(L);
664654  t = index2addr(L, idx);
665  api_check(L, ttistable(t), "table expected");
655  api_check(ttistable(t), "table expected");
666656  setpvalue(&k, cast(void *, p));
667657  setobj2s(L, L->top, luaH_get(hvalue(t), &k));
668658  api_incr_top(L);
669659  lua_unlock(L);
660  return ttnov(L->top - 1);
670661}
671662
672663
r242885r242886
685676
686677LUA_API int lua_getmetatable (lua_State *L, int objindex) {
687678  const TValue *obj;
688  Table *mt = NULL;
689  int res;
679  Table *mt;
680  int res = 0;
690681  lua_lock(L);
691682  obj = index2addr(L, objindex);
692  switch (ttypenv(obj)) {
683  switch (ttnov(obj)) {
693684    case LUA_TTABLE:
694685      mt = hvalue(obj)->metatable;
695686      break;
r242885r242886
697688      mt = uvalue(obj)->metatable;
698689      break;
699690    default:
700      mt = G(L)->mt[ttypenv(obj)];
691      mt = G(L)->mt[ttnov(obj)];
701692      break;
702693  }
703  if (mt == NULL)
704    res = 0;
705  else {
694  if (mt != NULL) {
706695    sethvalue(L, L->top, mt);
707696    api_incr_top(L);
708697    res = 1;
r242885r242886
712701}
713702
714703
715LUA_API void lua_getuservalue (lua_State *L, int idx) {
704LUA_API int lua_getuservalue (lua_State *L, int idx) {
716705  StkId o;
717706  lua_lock(L);
718707  o = index2addr(L, idx);
719  api_check(L, ttisuserdata(o), "userdata expected");
720  if (uvalue(o)->env) {
721    sethvalue(L, L->top, uvalue(o)->env);
722  } else
723    setnilvalue(L->top);
708  api_check(ttisfulluserdata(o), "full userdata expected");
709  getuservalue(L, uvalue(o), L->top);
724710  api_incr_top(L);
725711  lua_unlock(L);
712  return ttnov(L->top - 1);
726713}
727714
728715
r242885r242886
731718*/
732719
733720
734LUA_API void lua_setglobal (lua_State *L, const char *var) {
721LUA_API void lua_setglobal (lua_State *L, const char *name) {
735722  Table *reg = hvalue(&G(L)->l_registry);
736723  const TValue *gt;  /* global table */
737724  lua_lock(L);
738725  api_checknelems(L, 1);
739726  gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
740  setsvalue2s(L, L->top++, luaS_new(L, var));
727  setsvalue2s(L, L->top++, luaS_new(L, name));
741728  luaV_settable(L, gt, L->top - 1, L->top - 2);
742729  L->top -= 2;  /* pop value and key */
743730  lua_unlock(L);
r242885r242886
767754}
768755
769756
770LUA_API void lua_rawset (lua_State *L, int idx) {
757LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
771758  StkId t;
772759  lua_lock(L);
773  api_checknelems(L, 2);
760  api_checknelems(L, 1);
774761  t = index2addr(L, idx);
775  api_check(L, ttistable(t), "table expected");
776  setobj2t(L, luaH_set(L, hvalue(t), L->top-2), L->top-1);
777  invalidateTMcache(hvalue(t));
778  luaC_barrierback(L, gcvalue(t), L->top-1);
762  setivalue(L->top++, n);
763  luaV_settable(L, t, L->top - 1, L->top - 2);
764  L->top -= 2;  /* pop value and key */
765  lua_unlock(L);
766}
767
768
769LUA_API void lua_rawset (lua_State *L, int idx) {
770  StkId o;
771  Table *t;
772  lua_lock(L);
773  api_checknelems(L, 2);
774  o = index2addr(L, idx);
775  api_check(ttistable(o), "table expected");
776  t = hvalue(o);
777  setobj2t(L, luaH_set(L, t, L->top-2), L->top-1);
778  invalidateTMcache(t);
779  luaC_barrierback(L, t, L->top-1);
779780  L->top -= 2;
780781  lua_unlock(L);
781782}
782783
783784
784LUA_API void lua_rawseti (lua_State *L, int idx, int n) {
785  StkId t;
785LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
786  StkId o;
787  Table *t;
786788  lua_lock(L);
787789  api_checknelems(L, 1);
788  t = index2addr(L, idx);
789  api_check(L, ttistable(t), "table expected");
790  luaH_setint(L, hvalue(t), n, L->top - 1);
791  luaC_barrierback(L, gcvalue(t), L->top-1);
790  o = index2addr(L, idx);
791  api_check(ttistable(o), "table expected");
792  t = hvalue(o);
793  luaH_setint(L, t, n, L->top - 1);
794  luaC_barrierback(L, t, L->top-1);
792795  L->top--;
793796  lua_unlock(L);
794797}
795798
796799
797800LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
798  StkId t;
801  StkId o;
802  Table *t;
799803  TValue k;
800804  lua_lock(L);
801805  api_checknelems(L, 1);
802  t = index2addr(L, idx);
803  api_check(L, ttistable(t), "table expected");
806  o = index2addr(L, idx);
807  api_check(ttistable(o), "table expected");
808  t = hvalue(o);
804809  setpvalue(&k, cast(void *, p));
805  setobj2t(L, luaH_set(L, hvalue(t), &k), L->top - 1);
806  luaC_barrierback(L, gcvalue(t), L->top - 1);
810  setobj2t(L, luaH_set(L, t, &k), L->top - 1);
811  luaC_barrierback(L, t, L->top - 1);
807812  L->top--;
808813  lua_unlock(L);
809814}
r242885r242886
818823  if (ttisnil(L->top - 1))
819824    mt = NULL;
820825  else {
821    api_check(L, ttistable(L->top - 1), "table expected");
826    api_check(ttistable(L->top - 1), "table expected");
822827    mt = hvalue(L->top - 1);
823828  }
824  switch (ttypenv(obj)) {
829  switch (ttnov(obj)) {
825830    case LUA_TTABLE: {
826831      hvalue(obj)->metatable = mt;
827832      if (mt) {
828        luaC_objbarrierback(L, gcvalue(obj), mt);
833        luaC_objbarrier(L, gcvalue(obj), mt);
829834        luaC_checkfinalizer(L, gcvalue(obj), mt);
830835      }
831836      break;
r242885r242886
833838    case LUA_TUSERDATA: {
834839      uvalue(obj)->metatable = mt;
835840      if (mt) {
836        luaC_objbarrier(L, rawuvalue(obj), mt);
841        luaC_objbarrier(L, uvalue(obj), mt);
837842        luaC_checkfinalizer(L, gcvalue(obj), mt);
838843      }
839844      break;
840845    }
841846    default: {
842      G(L)->mt[ttypenv(obj)] = mt;
847      G(L)->mt[ttnov(obj)] = mt;
843848      break;
844849    }
845850  }
r242885r242886
854859  lua_lock(L);
855860  api_checknelems(L, 1);
856861  o = index2addr(L, idx);
857  api_check(L, ttisuserdata(o), "userdata expected");
858  if (ttisnil(L->top - 1))
859    uvalue(o)->env = NULL;
860  else {
861    api_check(L, ttistable(L->top - 1), "table expected");
862    uvalue(o)->env = hvalue(L->top - 1);
863    luaC_objbarrier(L, gcvalue(o), hvalue(L->top - 1));
864  }
862  api_check(ttisfulluserdata(o), "full userdata expected");
863  setuservalue(L, uvalue(o), L->top - 1);
864  luaC_barrier(L, gcvalue(o), L->top - 1);
865865  L->top--;
866866  lua_unlock(L);
867867}
868868
869869
870870/*
871** `load' and `call' functions (run Lua code)
871** 'load' and 'call' functions (run Lua code)
872872*/
873873
874874
875875#define checkresults(L,na,nr) \
876     api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
876     api_check((nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
877877   "results from function overflow current stack size")
878878
879879
880LUA_API int lua_getctx (lua_State *L, int *ctx) {
881  if (L->ci->callstatus & CIST_YIELDED) {
882    if (ctx) *ctx = L->ci->u.c.ctx;
883    return L->ci->u.c.status;
884  }
885  else return LUA_OK;
886}
887
888
889LUA_API void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
890                        lua_CFunction k) {
880LUA_API void lua_callk (lua_State *L, int nargs, int nresults,
881                        lua_KContext ctx, lua_KFunction k) {
891882  StkId func;
892883  lua_lock(L);
893  api_check(L, k == NULL || !isLua(L->ci),
884  api_check(k == NULL || !isLua(L->ci),
894885    "cannot use continuations inside hooks");
895886  api_checknelems(L, nargs+1);
896  api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
887  api_check(L->status == LUA_OK, "cannot do calls on non-normal thread");
897888  checkresults(L, nargs, nresults);
898889  func = L->top - (nargs+1);
899890  if (k != NULL && L->nny == 0) {  /* need to prepare continuation? */
r242885r242886
912903/*
913904** Execute a protected call.
914905*/
915struct CallS {  /* data to `f_call' */
906struct CallS {  /* data to 'f_call' */
916907  StkId func;
917908  int nresults;
918909};
r242885r242886
926917
927918
928919LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
929                        int ctx, lua_CFunction k) {
920                        lua_KContext ctx, lua_KFunction k) {
930921  struct CallS c;
931922  int status;
932923  ptrdiff_t func;
933924  lua_lock(L);
934  api_check(L, k == NULL || !isLua(L->ci),
925  api_check(k == NULL || !isLua(L->ci),
935926    "cannot use continuations inside hooks");
936927  api_checknelems(L, nargs+1);
937  api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
928  api_check(L->status == LUA_OK, "cannot do calls on non-normal thread");
938929  checkresults(L, nargs, nresults);
939930  if (errfunc == 0)
940931    func = 0;
941932  else {
942933    StkId o = index2addr(L, errfunc);
943    api_checkstackindex(L, errfunc, o);
934    api_checkstackindex(errfunc, o);
944935    func = savestack(L, o);
945936  }
946937  c.func = L->top - (nargs+1);  /* function to be called */
r242885r242886
954945    ci->u.c.ctx = ctx;  /* save context */
955946    /* save information for error recovery */
956947    ci->extra = savestack(L, c.func);
957    ci->u.c.old_allowhook = L->allowhook;
958948    ci->u.c.old_errfunc = L->errfunc;
959949    L->errfunc = func;
960    /* mark that function may do error recovery */
961    ci->callstatus |= CIST_YPCALL;
950    setoah(ci->callstatus, L->allowhook);  /* save value of 'allowhook' */
951    ci->callstatus |= CIST_YPCALL;  /* function can do error recovery */
962952    luaD_call(L, c.func, nresults, 1);  /* do the call */
963953    ci->callstatus &= ~CIST_YPCALL;
964954    L->errfunc = ci->u.c.old_errfunc;
r242885r242886
980970  status = luaD_protectedparser(L, &z, chunkname, mode);
981971  if (status == LUA_OK) {  /* no errors? */
982972    LClosure *f = clLvalue(L->top - 1);  /* get newly created function */
983    if (f->nupvalues == 1) {  /* does it have one upvalue? */
973    if (f->nupvalues >= 1) {  /* does it have an upvalue? */
984974      /* get global table from registry */
985975      Table *reg = hvalue(&G(L)->l_registry);
986976      const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
987977      /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
988978      setobj(L, f->upvals[0]->v, gt);
989      luaC_barrier(L, f->upvals[0], gt);
979      luaC_upvalbarrier(L, f->upvals[0]);
990980    }
991981  }
992982  lua_unlock(L);
r242885r242886
994984}
995985
996986
997LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {
987LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {
998988  int status;
999989  TValue *o;
1000990  lua_lock(L);
1001991  api_checknelems(L, 1);
1002992  o = L->top - 1;
1003993  if (isLfunction(o))
1004    status = luaU_dump(L, getproto(o), writer, data, 0);
994    status = luaU_dump(L, getproto(o), writer, data, strip);
1005995  else
1006996    status = 1;
1007997  lua_unlock(L);
r242885r242886
10471037      break;
10481038    }
10491039    case LUA_GCSTEP: {
1050      if (g->gckind == KGC_GEN) {  /* generational mode? */
1051        res = (g->GCestimate == 0);  /* true if it will do major collection */
1052        luaC_forcestep(L);  /* do a single step */
1040      l_mem debt = 1;  /* =1 to signal that it did an actual step */
1041      int oldrunning = g->gcrunning;
1042      g->gcrunning = 1;  /* allow GC to run */
1043      if (data == 0) {
1044        luaE_setdebt(g, -GCSTEPSIZE);  /* to do a "small" step */
1045        luaC_step(L);
10531046      }
1054      else {
1055       lu_mem debt = cast(lu_mem, data) * 1024 - GCSTEPSIZE;
1056       if (g->gcrunning)
1057         debt += g->GCdebt;  /* include current debt */
1058       luaE_setdebt(g, debt);
1059       luaC_forcestep(L);
1060       if (g->gcstate == GCSpause)  /* end of cycle? */
1061         res = 1;  /* signal it */
1047      else {  /* add 'data' to total debt */
1048        debt = cast(l_mem, data) * 1024 + g->GCdebt;
1049        luaE_setdebt(g, debt);
1050        luaC_checkGC(L);
10621051      }
1052      g->gcrunning = oldrunning;  /* restore previous state */
1053      if (debt > 0 && g->gcstate == GCSpause)  /* end of cycle? */
1054        res = 1;  /* signal it */
10631055      break;
10641056    }
10651057    case LUA_GCSETPAUSE: {
r242885r242886
10671059      g->gcpause = data;
10681060      break;
10691061    }
1070    case LUA_GCSETMAJORINC: {
1071      res = g->gcmajorinc;
1072      g->gcmajorinc = data;
1073      break;
1074    }
10751062    case LUA_GCSETSTEPMUL: {
10761063      res = g->gcstepmul;
1064      if (data < 40) data = 40;  /* avoid ridiculous low values (and 0) */
10771065      g->gcstepmul = data;
10781066      break;
10791067    }
r242885r242886
10811069      res = g->gcrunning;
10821070      break;
10831071    }
1084    case LUA_GCGEN: {  /* change collector to generational mode */
1085      luaC_changemode(L, KGC_GEN);
1086      break;
1087    }
1088    case LUA_GCINC: {  /* change collector to incremental mode */
1089      luaC_changemode(L, KGC_NORMAL);
1090      break;
1091    }
10921072    default: res = -1;  /* invalid option */
10931073  }
10941074  lua_unlock(L);
r242885r242886
11161096  int more;
11171097  lua_lock(L);
11181098  t = index2addr(L, idx);
1119  api_check(L, ttistable(t), "table expected");
1099  api_check(ttistable(t), "table expected");
11201100  more = luaH_next(L, hvalue(t), L->top - 1);
11211101  if (more) {
11221102    api_incr_top(L);
r242885r242886
11761156  Udata *u;
11771157  lua_lock(L);
11781158  luaC_checkGC(L);
1179  u = luaS_newudata(L, size, NULL);
1159  u = luaS_newudata(L, size);
11801160  setuvalue(L, L->top, u);
11811161  api_incr_top(L);
11821162  lua_unlock(L);
1183  return u + 1;
1163  return getudatamem(u);
11841164}
11851165
11861166
11871167
11881168static const char *aux_upvalue (StkId fi, int n, TValue **val,
1189                                GCObject **owner) {
1169                                CClosure **owner, UpVal **uv) {
11901170  switch (ttype(fi)) {
11911171    case LUA_TCCL: {  /* C closure */
11921172      CClosure *f = clCvalue(fi);
11931173      if (!(1 <= n && n <= f->nupvalues)) return NULL;
11941174      *val = &f->upvalue[n-1];
1195      if (owner) *owner = obj2gco(f);
1175      if (owner) *owner = f;
11961176      return "";
11971177    }
11981178    case LUA_TLCL: {  /* Lua closure */
r242885r242886
12011181      Proto *p = f->p;
12021182      if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
12031183      *val = f->upvals[n-1]->v;
1204      if (owner) *owner = obj2gco(f->upvals[n - 1]);
1184      if (uv) *uv = f->upvals[n - 1];
12051185      name = p->upvalues[n-1].name;
1206      return (name == NULL) ? "" : getstr(name);
1186      return (name == NULL) ? "(*no name)" : getstr(name);
12071187    }
12081188    default: return NULL;  /* not a closure */
12091189  }
r242885r242886
12141194  const char *name;
12151195  TValue *val = NULL;  /* to avoid warnings */
12161196  lua_lock(L);
1217  name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL);
1197  name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL, NULL);
12181198  if (name) {
12191199    setobj2s(L, L->top, val);
12201200    api_incr_top(L);
r242885r242886
12271207LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
12281208  const char *name;
12291209  TValue *val = NULL;  /* to avoid warnings */
1230  GCObject *owner = NULL;  /* to avoid warnings */
1210  CClosure *owner = NULL;
1211  UpVal *uv = NULL;
12311212  StkId fi;
12321213  lua_lock(L);
12331214  fi = index2addr(L, funcindex);
12341215  api_checknelems(L, 1);
1235  name = aux_upvalue(fi, n, &val, &owner);
1216  name = aux_upvalue(fi, n, &val, &owner, &uv);
12361217  if (name) {
12371218    L->top--;
12381219    setobj(L, val, L->top);
1239    luaC_barrier(L, owner, L->top);
1220    if (owner) { luaC_barrier(L, owner, L->top); }
1221    else if (uv) { luaC_upvalbarrier(L, uv); }
12401222  }
12411223  lua_unlock(L);
12421224  return name;
r242885r242886
12461228static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
12471229  LClosure *f;
12481230  StkId fi = index2addr(L, fidx);
1249  api_check(L, ttisLclosure(fi), "Lua function expected");
1231  api_check(ttisLclosure(fi), "Lua function expected");
12501232  f = clLvalue(fi);
1251  api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
1233  api_check((1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
12521234  if (pf) *pf = f;
12531235  return &f->upvals[n - 1];  /* get its upvalue pointer */
12541236}
r242885r242886
12621244    }
12631245    case LUA_TCCL: {  /* C closure */
12641246      CClosure *f = clCvalue(fi);
1265      api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
1247      api_check(1 <= n && n <= f->nupvalues, "invalid upvalue index");
12661248      return &f->upvalue[n - 1];
12671249    }
12681250    default: {
1269      api_check(L, 0, "closure expected");
1251      api_check(0, "closure expected");
12701252      return NULL;
12711253    }
12721254  }
r242885r242886
12781260  LClosure *f1;
12791261  UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
12801262  UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
1263  luaC_upvdeccount(L, *up1);
12811264  *up1 = *up2;
1282  luaC_objbarrier(L, f1, *up2);
1265  (*up1)->refcount++;
1266  if (upisopen(*up1)) (*up1)->u.open.touched = 1;
1267  luaC_upvalbarrier(L, *up1);
12831268}
12841269
1270
trunk/3rdparty/lua/src/lapi.h
r242885r242886
11/*
2** $Id: lapi.h,v 2.7.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lapi.h,v 2.8 2014/07/15 21:26:50 roberto Exp $
33** Auxiliary functions from Lua API
44** See Copyright Notice in lua.h
55*/
r242885r242886
1111#include "llimits.h"
1212#include "lstate.h"
1313
14#define api_incr_top(L)   {L->top++; api_check(L, L->top <= L->ci->top, \
14#define api_incr_top(L)   {L->top++; api_check(L->top <= L->ci->top, \
1515            "stack overflow");}
1616
1717#define adjustresults(L,nres) \
1818    { if ((nres) == LUA_MULTRET && L->ci->top < L->top) L->ci->top = L->top; }
1919
20#define api_checknelems(L,n)   api_check(L, (n) < (L->top - L->ci->func), \
20#define api_checknelems(L,n)   api_check((n) < (L->top - L->ci->func), \
2121              "not enough elements in the stack")
2222
2323
trunk/3rdparty/lua/src/lauxlib.c
r242885r242886
11/*
2** $Id: lauxlib.c,v 1.248.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lauxlib.c,v 1.279 2014/12/14 18:32:26 roberto Exp $
33** Auxiliary functions for building Lua libraries
44** See Copyright Notice in lua.h
55*/
66
7#define lauxlib_c
8#define LUA_LIB
79
10#include "lprefix.h"
11
12
813#include <errno.h>
914#include <stdarg.h>
1015#include <stdio.h>
r242885r242886
1621** Any function declared here could be written as an application function.
1722*/
1823
19#define lauxlib_c
20#define LUA_LIB
21
2224#include "lua.h"
2325
2426#include "lauxlib.h"
r242885r242886
6466}
6567
6668
69/*
70** Search for a name for a function in all loaded modules
71** (registry._LOADED).
72*/
6773static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
6874  int top = lua_gettop(L);
6975  lua_getinfo(L, "f", ar);  /* push function */
70  lua_pushglobaltable(L);
76  lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
7177  if (findfield(L, top + 1, 2)) {
78    const char *name = lua_tostring(L, -1);
79    if (strncmp(name, "_G.", 3) == 0) {  /* name start with '_G.'? */
80      lua_pushstring(L, name + 3);  /* push name without prefix */
81      lua_remove(L, -2);  /* remove original name */
82    }
7283    lua_copy(L, -1, top + 1);  /* move name to proper place */
7384    lua_pop(L, 2);  /* remove pushed values */
7485    return 1;
r242885r242886
8192
8293
8394static void pushfuncname (lua_State *L, lua_Debug *ar) {
84  if (*ar->namewhat != '\0')  /* is there a name? */
85    lua_pushfstring(L, "function " LUA_QS, ar->name);
95  if (pushglobalfuncname(L, ar)) {  /* try first a global name */
96    lua_pushfstring(L, "function '%s'", lua_tostring(L, -1));
97    lua_remove(L, -2);  /* remove name */
98  }
99  else if (*ar->namewhat != '\0')  /* is there a name from code? */
100    lua_pushfstring(L, "%s '%s'", ar->namewhat, ar->name);  /* use it */
86101  else if (*ar->what == 'm')  /* main? */
87102      lua_pushliteral(L, "main chunk");
88  else if (*ar->what == 'C') {
89    if (pushglobalfuncname(L, ar)) {
90      lua_pushfstring(L, "function " LUA_QS, lua_tostring(L, -1));
91      lua_remove(L, -2);  /* remove name */
92    }
93    else
94      lua_pushliteral(L, "?");
95  }
96  else
103  else if (*ar->what != 'C')  /* for Lua functions, use <file:line> */
97104    lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
105  else  /* nothing left... */
106    lua_pushliteral(L, "?");
98107}
99108
100109
r242885r242886
150159** =======================================================
151160*/
152161
153LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
162LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
154163  lua_Debug ar;
155164  if (!lua_getstack(L, 0, &ar))  /* no stack frame? */
156    return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
165    return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
157166  lua_getinfo(L, "n", &ar);
158167  if (strcmp(ar.namewhat, "method") == 0) {
159    narg--;  /* do not count `self' */
160    if (narg == 0)  /* error is in the self argument itself? */
161      return luaL_error(L, "calling " LUA_QS " on bad self (%s)",
168    arg--;  /* do not count 'self' */
169    if (arg == 0)  /* error is in the self argument itself? */
170      return luaL_error(L, "calling '%s' on bad self (%s)",
162171                           ar.name, extramsg);
163172  }
164173  if (ar.name == NULL)
165174    ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
166  return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
167                        narg, ar.name, extramsg);
175  return luaL_error(L, "bad argument #%d to '%s' (%s)",
176                        arg, ar.name, extramsg);
168177}
169178
170179
171static int typeerror (lua_State *L, int narg, const char *tname) {
172  const char *msg = lua_pushfstring(L, "%s expected, got %s",
173                                    tname, luaL_typename(L, narg));
174  return luaL_argerror(L, narg, msg);
180static int typeerror (lua_State *L, int arg, const char *tname) {
181  const char *msg;
182  const char *typearg;  /* name for the type of the actual argument */
183  if (luaL_getmetafield(L, arg, "__name") == LUA_TSTRING)
184    typearg = lua_tostring(L, -1);  /* use the given type name */
185  else if (lua_type(L, arg) == LUA_TLIGHTUSERDATA)
186    typearg = "light userdata";  /* special name for messages */
187  else
188    typearg = luaL_typename(L, arg);  /* standard name */
189  msg = lua_pushfstring(L, "%s expected, got %s", tname, typearg);
190  return luaL_argerror(L, arg, msg);
175191}
176192
177193
178static void tag_error (lua_State *L, int narg, int tag) {
179  typeerror(L, narg, lua_typename(L, tag));
194static void tag_error (lua_State *L, int arg, int tag) {
195  typeerror(L, arg, lua_typename(L, tag));
180196}
181197
182198
r242885r242886
222238}
223239
224240
225#if !defined(inspectstat)   /* { */
241#if !defined(l_inspectstat)   /* { */
226242
227243#if defined(LUA_USE_POSIX)
228244
r242885r242886
231247/*
232248** use appropriate macros to interpret 'pclose' return status
233249*/
234#define inspectstat(stat,what)  \
250#define l_inspectstat(stat,what)  \
235251   if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
236252   else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
237253
238254#else
239255
240#define inspectstat(stat,what)  /* no op */
256#define l_inspectstat(stat,what)  /* no op */
241257
242258#endif
243259
r242885r242886
249265  if (stat == -1)  /* error? */
250266    return luaL_fileresult(L, 0, NULL);
251267  else {
252    inspectstat(stat, what);  /* interpret result */
268    l_inspectstat(stat, what);  /* interpret result */
253269    if (*what == 'e' && stat == 0)  /* successful termination? */
254270      lua_pushboolean(L, 1);
255271    else
r242885r242886
270286*/
271287
272288LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
273  luaL_getmetatable(L, tname);  /* try to get metatable */
274  if (!lua_isnil(L, -1))  /* name already in use? */
289  if (luaL_getmetatable(L, tname))  /* name already in use? */
275290    return 0;  /* leave previous value on top, but return 0 */
276291  lua_pop(L, 1);
277292  lua_newtable(L);  /* create metatable */
293  lua_pushstring(L, tname);
294  lua_setfield(L, -2, "__name");  /* metatable.__name = tname */
278295  lua_pushvalue(L, -1);
279296  lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */
280297  return 1;
r242885r242886
317334** =======================================================
318335*/
319336
320LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
337LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
321338                                 const char *const lst[]) {
322  const char *name = (def) ? luaL_optstring(L, narg, def) :
323                             luaL_checkstring(L, narg);
339  const char *name = (def) ? luaL_optstring(L, arg, def) :
340                             luaL_checkstring(L, arg);
324341  int i;
325342  for (i=0; lst[i]; i++)
326343    if (strcmp(lst[i], name) == 0)
327344      return i;
328  return luaL_argerror(L, narg,
329                       lua_pushfstring(L, "invalid option " LUA_QS, name));
345  return luaL_argerror(L, arg,
346                       lua_pushfstring(L, "invalid option '%s'", name));
330347}
331348
332349
r242885r242886
342359}
343360
344361
345LUALIB_API void luaL_checktype (lua_State *L, int narg, int t) {
346  if (lua_type(L, narg) != t)
347    tag_error(L, narg, t);
362LUALIB_API void luaL_checktype (lua_State *L, int arg, int t) {
363  if (lua_type(L, arg) != t)
364    tag_error(L, arg, t);
348365}
349366
350367
351LUALIB_API void luaL_checkany (lua_State *L, int narg) {
352  if (lua_type(L, narg) == LUA_TNONE)
353    luaL_argerror(L, narg, "value expected");
368LUALIB_API void luaL_checkany (lua_State *L, int arg) {
369  if (lua_type(L, arg) == LUA_TNONE)
370    luaL_argerror(L, arg, "value expected");
354371}
355372
356373
357LUALIB_API const char *luaL_checklstring (lua_State *L, int narg, size_t *len) {
358  const char *s = lua_tolstring(L, narg, len);
359  if (!s) tag_error(L, narg, LUA_TSTRING);
374LUALIB_API const char *luaL_checklstring (lua_State *L, int arg, size_t *len) {
375  const char *s = lua_tolstring(L, arg, len);
376  if (!s) tag_error(L, arg, LUA_TSTRING);
360377  return s;
361378}
362379
363380
364LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
381LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
365382                                        const char *def, size_t *len) {
366  if (lua_isnoneornil(L, narg)) {
383  if (lua_isnoneornil(L, arg)) {
367384    if (len)
368385      *len = (def ? strlen(def) : 0);
369386    return def;
370387  }
371  else return luaL_checklstring(L, narg, len);
388  else return luaL_checklstring(L, arg, len);
372389}
373390
374391
375LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
392LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
376393  int isnum;
377  lua_Number d = lua_tonumberx(L, narg, &isnum);
394  lua_Number d = lua_tonumberx(L, arg, &isnum);
378395  if (!isnum)
379    tag_error(L, narg, LUA_TNUMBER);
396    tag_error(L, arg, LUA_TNUMBER);
380397  return d;
381398}
382399
383400
384LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
385  return luaL_opt(L, luaL_checknumber, narg, def);
401LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
402  return luaL_opt(L, luaL_checknumber, arg, def);
386403}
387404
388405
389LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int narg) {
390  int isnum;
391  lua_Integer d = lua_tointegerx(L, narg, &isnum);
392  if (!isnum)
393    tag_error(L, narg, LUA_TNUMBER);
394  return d;
406static void interror (lua_State *L, int arg) {
407  if (lua_isnumber(L, arg))
408    luaL_argerror(L, arg, "number has no integer representation");
409  else
410    tag_error(L, arg, LUA_TNUMBER);
395411}
396412
397413
398LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {
414LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
399415  int isnum;
400  lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);
401  if (!isnum)
402    tag_error(L, narg, LUA_TNUMBER);
416  lua_Integer d = lua_tointegerx(L, arg, &isnum);
417  if (!isnum) {
418    interror(L, arg);
419  }
403420  return d;
404421}
405422
406423
407LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
424LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
408425                                                      lua_Integer def) {
409  return luaL_opt(L, luaL_checkinteger, narg, def);
426  return luaL_opt(L, luaL_checkinteger, arg, def);
410427}
411428
412
413LUALIB_API lua_Unsigned luaL_optunsigned (lua_State *L, int narg,
414                                                        lua_Unsigned def) {
415  return luaL_opt(L, luaL_checkunsigned, narg, def);
416}
417
418429/* }====================================================== */
419430
420431
r242885r242886
523534  int ref;
524535  if (lua_isnil(L, -1)) {
525536    lua_pop(L, 1);  /* remove from stack */
526    return LUA_REFNIL;  /* `nil' has a unique fixed reference */
537    return LUA_REFNIL;  /* 'nil' has a unique fixed reference */
527538  }
528539  t = lua_absindex(L, t);
529540  lua_rawgeti(L, t, freelist);  /* get first free element */
r242885r242886
562573typedef struct LoadF {
563574  int n;  /* number of pre-read characters */
564575  FILE *f;  /* file being read */
565  char buff[LUAL_BUFFERSIZE];  /* area for reading file */
576  char buff[BUFSIZ];  /* area for reading file */
566577} LoadF;
567578
568579
r242885r242886
655666  readstatus = ferror(lf.f);
656667  if (filename) fclose(lf.f);  /* close file (even in case of errors) */
657668  if (readstatus) {
658    lua_settop(L, fnameindex);  /* ignore results from `lua_load' */
669    lua_settop(L, fnameindex);  /* ignore results from 'lua_load' */
659670    return errfile(L, "read", fnameindex);
660671  }
661672  lua_remove(L, fnameindex);
r242885r242886
698709
699710LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
700711  if (!lua_getmetatable(L, obj))  /* no metatable? */
701    return 0;
702  lua_pushstring(L, event);
703  lua_rawget(L, -2);
704  if (lua_isnil(L, -1)) {
705    lua_pop(L, 2);  /* remove metatable and metafield */
706    return 0;
707  }
712    return LUA_TNIL;
708713  else {
709    lua_remove(L, -2);  /* remove only metatable */
710    return 1;
714    int tt;
715    lua_pushstring(L, event);
716    tt = lua_rawget(L, -2);
717    if (tt == LUA_TNIL)  /* is metafield nil? */
718      lua_pop(L, 2);  /* remove metatable and metafield */
719    else
720      lua_remove(L, -2);  /* remove only metatable */
721    return tt;  /* return metafield type */
711722  }
712723}
713724
714725
715726LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
716727  obj = lua_absindex(L, obj);
717  if (!luaL_getmetafield(L, obj, event))  /* no metafield? */
728  if (luaL_getmetafield(L, obj, event) == LUA_TNIL)  /* no metafield? */
718729    return 0;
719730  lua_pushvalue(L, obj);
720731  lua_call(L, 1, 1);
r242885r242886
722733}
723734
724735
725LUALIB_API int luaL_len (lua_State *L, int idx) {
726  int l;
736LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
737  lua_Integer l;
727738  int isnum;
728739  lua_len(L, idx);
729  l = (int)lua_tointegerx(L, -1, &isnum);
740  l = lua_tointegerx(L, -1, &isnum);
730741  if (!isnum)
731    luaL_error(L, "object length is not a number");
742    luaL_error(L, "object length is not an integer");
732743  lua_pop(L, 1);  /* remove object */
733744  return l;
734745}
r242885r242886
737748LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
738749  if (!luaL_callmeta(L, idx, "__tostring")) {  /* no metafield? */
739750    switch (lua_type(L, idx)) {
740      case LUA_TNUMBER:
751      case LUA_TNUMBER: {
752        if (lua_isinteger(L, idx))
753          lua_pushfstring(L, "%I", lua_tointeger(L, idx));
754        else
755          lua_pushfstring(L, "%f", lua_tonumber(L, idx));
756        break;
757      }
741758      case LUA_TSTRING:
742759        lua_pushvalue(L, idx);
743760        break;
r242885r242886
772789    e = strchr(fname, '.');
773790    if (e == NULL) e = fname + strlen(fname);
774791    lua_pushlstring(L, fname, e - fname);
775    lua_rawget(L, -2);
776    if (lua_isnil(L, -1)) {  /* no such field? */
792    if (lua_rawget(L, -2) == LUA_TNIL) {  /* no such field? */
777793      lua_pop(L, 1);  /* remove this nil */
778794      lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
779795      lua_pushlstring(L, fname, e - fname);
r242885r242886
810826LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
811827                                 int sizehint) {
812828  luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);  /* get _LOADED table */
813  lua_getfield(L, -1, modname);  /* get _LOADED[modname] */
814  if (!lua_istable(L, -1)) {  /* not found? */
829  if (lua_getfield(L, -1, modname) != LUA_TTABLE) {  /* no _LOADED[modname]? */
815830    lua_pop(L, 1);  /* remove previous result */
816831    /* try global variable (and create one if it does not exist) */
817832    lua_pushglobaltable(L);
818833    if (luaL_findtable(L, 0, modname, sizehint) != NULL)
819      luaL_error(L, "name conflict for module " LUA_QS, modname);
834      luaL_error(L, "name conflict for module '%s'", modname);
820835    lua_pushvalue(L, -1);
821836    lua_setfield(L, -3, modname);  /* _LOADED[modname] = new table */
822837  }
r242885r242886
846861** Returns with only the table at the stack.
847862*/
848863LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
849  luaL_checkversion(L);
850864  luaL_checkstack(L, nup, "too many upvalues");
851865  for (; l->name != NULL; l++) {  /* fill the table with given functions */
852866    int i;
r242885r242886
864878** into the stack
865879*/
866880LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
867  lua_getfield(L, idx, fname);
868  if (lua_istable(L, -1)) return 1;  /* table already there */
881  if (lua_getfield(L, idx, fname) == LUA_TTABLE)
882    return 1;  /* table already there */
869883  else {
870884    lua_pop(L, 1);  /* remove previous result */
871885    idx = lua_absindex(L, idx);
r242885r242886
878892
879893
880894/*
881** stripped-down 'require'. Calls 'openf' to open a module,
882** registers the result in 'package.loaded' table and, if 'glb'
883** is true, also registers the result in the global table.
895** Stripped-down 'require': After checking "loaded" table, calls 'openf'
896** to open a module, registers the result in 'package.loaded' table and,
897** if 'glb' is true, also registers the result in the global table.
884898** Leaves resulting module on the top.
885899*/
886900LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
887901                               lua_CFunction openf, int glb) {
888  lua_pushcfunction(L, openf);
889  lua_pushstring(L, modname);  /* argument to open function */
890  lua_call(L, 1, 1);  /* open module */
891902  luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
892  lua_pushvalue(L, -2);  /* make copy of module (call result) */
893  lua_setfield(L, -2, modname);  /* _LOADED[modname] = module */
894  lua_pop(L, 1);  /* remove _LOADED table */
903  lua_getfield(L, -1, modname);  /* _LOADED[modname] */
904  if (!lua_toboolean(L, -1)) {  /* package not already loaded? */
905    lua_pop(L, 1);  /* remove field */
906    lua_pushcfunction(L, openf);
907    lua_pushstring(L, modname);  /* argument to open function */
908    lua_call(L, 1, 1);  /* call 'openf' to open module */
909    lua_pushvalue(L, -1);  /* make copy of module (call result) */
910    lua_setfield(L, -3, modname);  /* _LOADED[modname] = module */
911  }
912  lua_remove(L, -2);  /* remove _LOADED table */
895913  if (glb) {
896    lua_pushvalue(L, -1);  /* copy of 'mod' */
914    lua_pushvalue(L, -1);  /* copy of module */
897915    lua_setglobal(L, modname);  /* _G[modname] = module */
898916  }
899917}
r242885r242886
908926  while ((wild = strstr(s, p)) != NULL) {
909927    luaL_addlstring(&b, s, wild - s);  /* push prefix */
910928    luaL_addstring(&b, r);  /* push replacement in place of pattern */
911    s = wild + l;  /* continue after `p' */
929    s = wild + l;  /* continue after 'p' */
912930  }
913931  luaL_addstring(&b, s);  /* push last suffix */
914932  luaL_pushresult(&b);
r242885r242886
928946
929947
930948static int panic (lua_State *L) {
931  luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
932                   lua_tostring(L, -1));
949  lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
950                        lua_tostring(L, -1));
933951  return 0;  /* return to Lua to abort */
934952}
935953
r242885r242886
941959}
942960
943961
944LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
962LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
945963  const lua_Number *v = lua_version(L);
964  if (sz != LUAL_NUMSIZES)  /* check numeric types */
965    luaL_error(L, "core and library have incompatible numeric types");
946966  if (v != lua_version(NULL))
947967    luaL_error(L, "multiple Lua VMs detected");
948968  else if (*v != ver)
949969    luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
950970                  ver, *v);
951  /* check conversions number -> integer types */
952  lua_pushnumber(L, -(lua_Number)0x1234);
953  if (lua_tointeger(L, -1) != -0x1234 ||
954      lua_tounsigned(L, -1) != (lua_Unsigned)-0x1234)
955    luaL_error(L, "bad conversion number->int;"
956                  " must recompile Lua with proper settings");
957  lua_pop(L, 1);
958971}
959972
trunk/3rdparty/lua/src/lauxlib.h
r242885r242886
11/*
2** $Id: lauxlib.h,v 1.120.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lauxlib.h,v 1.128 2014/10/29 16:11:17 roberto Exp $
33** Auxiliary functions for building Lua libraries
44** See Copyright Notice in lua.h
55*/
r242885r242886
1616
1717
1818
19/* extra error code for `luaL_load' */
19/* extra error code for 'luaL_load' */
2020#define LUA_ERRFILE     (LUA_ERRERR+1)
2121
2222
r242885r242886
2626} luaL_Reg;
2727
2828
29LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver);
30#define luaL_checkversion(L)   luaL_checkversion_(L, LUA_VERSION_NUM)
29#define LUAL_NUMSIZES   (sizeof(lua_Integer)*16 + sizeof(lua_Number))
3130
31LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver, size_t sz);
32#define luaL_checkversion(L)  \
33     luaL_checkversion_(L, LUA_VERSION_NUM, LUAL_NUMSIZES)
34
3235LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
3336LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
3437LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
35LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
36LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg,
38LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);
39LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,
3740                                                          size_t *l);
38LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg,
41LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
3942                                          const char *def, size_t *l);
40LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int numArg);
41LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int nArg, lua_Number def);
43LUALIB_API lua_Number (luaL_checknumber) (lua_State *L, int arg);
44LUALIB_API lua_Number (luaL_optnumber) (lua_State *L, int arg, lua_Number def);
4245
43LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg);
44LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg,
46LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);
47LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,
4548                                          lua_Integer def);
46LUALIB_API lua_Unsigned (luaL_checkunsigned) (lua_State *L, int numArg);
47LUALIB_API lua_Unsigned (luaL_optunsigned) (lua_State *L, int numArg,
48                                            lua_Unsigned def);
4949
5050LUALIB_API void (luaL_checkstack) (lua_State *L, int sz, const char *msg);
51LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t);
52LUALIB_API void (luaL_checkany) (lua_State *L, int narg);
51LUALIB_API void (luaL_checktype) (lua_State *L, int arg, int t);
52LUALIB_API void (luaL_checkany) (lua_State *L, int arg);
5353
5454LUALIB_API int   (luaL_newmetatable) (lua_State *L, const char *tname);
5555LUALIB_API void  (luaL_setmetatable) (lua_State *L, const char *tname);
r242885r242886
5959LUALIB_API void (luaL_where) (lua_State *L, int lvl);
6060LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
6161
62LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
62LUALIB_API int (luaL_checkoption) (lua_State *L, int arg, const char *def,
6363                                   const char *const lst[]);
6464
6565LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
r242885r242886
8383
8484LUALIB_API lua_State *(luaL_newstate) (void);
8585
86LUALIB_API int (luaL_len) (lua_State *L, int idx);
86LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);
8787
8888LUALIB_API const char *(luaL_gsub) (lua_State *L, const char *s, const char *p,
8989                                                  const char *r);
r242885r242886
108108#define luaL_newlibtable(L,l)   \
109109  lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)
110110
111#define luaL_newlib(L,l)   (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
111#define luaL_newlib(L,l)  \
112  (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
112113
113#define luaL_argcheck(L, cond,numarg,extramsg)   \
114      ((void)((cond) || luaL_argerror(L, (numarg), (extramsg))))
114#define luaL_argcheck(L, cond,arg,extramsg)   \
115      ((void)((cond) || luaL_argerror(L, (arg), (extramsg))))
115116#define luaL_checkstring(L,n)   (luaL_checklstring(L, (n), NULL))
116117#define luaL_optstring(L,n,d)   (luaL_optlstring(L, (n), (d), NULL))
117#define luaL_checkint(L,n)   ((int)luaL_checkinteger(L, (n)))
118#define luaL_optint(L,n,d)   ((int)luaL_optinteger(L, (n), (d)))
119#define luaL_checklong(L,n)   ((long)luaL_checkinteger(L, (n)))
120#define luaL_optlong(L,n,d)   ((long)luaL_optinteger(L, (n), (d)))
121118
122119#define luaL_typename(L,i)   lua_typename(L, lua_type(L,(i)))
123120
r242885r242886
207204#endif
208205
209206
207/*
208** {==================================================================
209** "Abstraction Layer" for basic report of messages and errors
210** ===================================================================
211*/
212
213/* print a string */
214#if !defined(lua_writestring)
215#define lua_writestring(s,l)   fwrite((s), sizeof(char), (l), stdout)
210216#endif
211217
218/* print a newline and flush the output */
219#if !defined(lua_writeline)
220#define lua_writeline()        (lua_writestring("\n", 1), fflush(stdout))
221#endif
212222
223/* print an error message */
224#if !defined(lua_writestringerror)
225#define lua_writestringerror(s,p) \
226        (fprintf(stderr, (s), (p)), fflush(stderr))
227#endif
228
229/* }================================================================== */
230
231
232/*
233** {============================================================
234** Compatibility with deprecated conversions
235** =============================================================
236*/
237#if defined(LUA_COMPAT_APIINTCASTS)
238
239#define luaL_checkunsigned(L,a)   ((lua_Unsigned)luaL_checkinteger(L,a))
240#define luaL_optunsigned(L,a,d)   \
241   ((lua_Unsigned)luaL_optinteger(L,a,(lua_Integer)(d)))
242
243#define luaL_checkint(L,n)   ((int)luaL_checkinteger(L, (n)))
244#define luaL_optint(L,n,d)   ((int)luaL_optinteger(L, (n), (d)))
245
246#define luaL_checklong(L,n)   ((long)luaL_checkinteger(L, (n)))
247#define luaL_optlong(L,n,d)   ((long)luaL_optinteger(L, (n), (d)))
248
249#endif
250/* }============================================================ */
251
252
253
254#endif
255
256
trunk/3rdparty/lua/src/lbaselib.c
r242885r242886
11/*
2** $Id: lbaselib.c,v 1.276.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lbaselib.c,v 1.309 2014/12/10 12:26:42 roberto Exp $
33** Basic library
44** See Copyright Notice in lua.h
55*/
66
7#define lbaselib_c
8#define LUA_LIB
79
10#include "lprefix.h"
811
12
913#include <ctype.h>
1014#include <stdio.h>
1115#include <stdlib.h>
1216#include <string.h>
1317
14#define lbaselib_c
15#define LUA_LIB
16
1718#include "lua.h"
1819
1920#include "lauxlib.h"
r242885r242886
3233    lua_call(L, 1, 1);
3334    s = lua_tolstring(L, -1, &l);  /* get result */
3435    if (s == NULL)
35      return luaL_error(L,
36         LUA_QL("tostring") " must return a string to " LUA_QL("print"));
37    if (i>1) luai_writestring("\t", 1);
38    luai_writestring(s, l);
36      return luaL_error(L, "'tostring' must return a string to 'print'");
37    if (i>1) lua_writestring("\t", 1);
38    lua_writestring(s, l);
3939    lua_pop(L, 1);  /* pop result */
4040  }
41  luai_writeline();
41  lua_writeline();
4242  return 0;
4343}
4444
4545
4646#define SPACECHARS   " \f\n\r\t\v"
4747
48static const char *b_str2int (const char *s, int base, lua_Integer *pn) {
49  lua_Unsigned n = 0;
50  int neg = 0;
51  s += strspn(s, SPACECHARS);  /* skip initial spaces */
52  if (*s == '-') { s++; neg = 1; }  /* handle signal */
53  else if (*s == '+') s++;
54  if (!isalnum((unsigned char)*s))  /* no digit? */
55    return NULL;
56  do {
57    int digit = (isdigit((unsigned char)*s)) ? *s - '0'
58                   : toupper((unsigned char)*s) - 'A' + 10;
59    if (digit >= base) return NULL;  /* invalid numeral */
60    n = n * base + digit;
61    s++;
62  } while (isalnum((unsigned char)*s));
63  s += strspn(s, SPACECHARS);  /* skip trailing spaces */
64  *pn = (lua_Integer)((neg) ? (0u - n) : n);
65  return s;
66}
67
68
4869static int luaB_tonumber (lua_State *L) {
49  if (lua_isnoneornil(L, 2)) {  /* standard conversion */
50    int isnum;
51    lua_Number n = lua_tonumberx(L, 1, &isnum);
52    if (isnum) {
53      lua_pushnumber(L, n);
70  if (lua_isnoneornil(L, 2)) {  /* standard conversion? */
71    luaL_checkany(L, 1);
72    if (lua_type(L, 1) == LUA_TNUMBER) {  /* already a number? */
73      lua_settop(L, 1);  /* yes; return it */
5474      return 1;
55    }  /* else not a number; must be something */
56    luaL_checkany(L, 1);
75    }
76    else {
77      size_t l;
78      const char *s = lua_tolstring(L, 1, &l);
79      if (s != NULL && lua_stringtonumber(L, s) == l + 1)
80        return 1;  /* successful conversion to number */
81      /* else not a number */
82    }
5783  }
5884  else {
5985    size_t l;
60    const char *s = luaL_checklstring(L, 1, &l);
61    const char *e = s + l;  /* end point for 's' */
62    int base = luaL_checkint(L, 2);
63    int neg = 0;
86    const char *s;
87    lua_Integer n = 0;  /* to avoid warnings */
88    lua_Integer base = luaL_checkinteger(L, 2);
89    luaL_checktype(L, 1, LUA_TSTRING);  /* before 'luaL_checklstring'! */
90    s = luaL_checklstring(L, 1, &l);
6491    luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
65    s += strspn(s, SPACECHARS);  /* skip initial spaces */
66    if (*s == '-') { s++; neg = 1; }  /* handle signal */
67    else if (*s == '+') s++;
68    if (isalnum((unsigned char)*s)) {
69      lua_Number n = 0;
70      do {
71        int digit = (isdigit((unsigned char)*s)) ? *s - '0'
72                       : toupper((unsigned char)*s) - 'A' + 10;
73        if (digit >= base) break;  /* invalid numeral; force a fail */
74        n = n * (lua_Number)base + (lua_Number)digit;
75        s++;
76      } while (isalnum((unsigned char)*s));
77      s += strspn(s, SPACECHARS);  /* skip trailing spaces */
78      if (s == e) {  /* no invalid trailing characters? */
79        lua_pushnumber(L, (neg) ? -n : n);
80        return 1;
81      }  /* else not a number */
92    if (b_str2int(s, (int)base, &n) == s + l) {
93      lua_pushinteger(L, n);
94      return 1;
8295    }  /* else not a number */
83  }
96  }  /* else not a number */
8497  lua_pushnil(L);  /* not a number */
8598  return 1;
8699}
87100
88101
89102static int luaB_error (lua_State *L) {
90  int level = luaL_optint(L, 2, 1);
103  int level = (int)luaL_optinteger(L, 2, 1);
91104  lua_settop(L, 1);
92105  if (lua_isstring(L, 1) && level > 0) {  /* add extra information? */
93106    luaL_where(L, level);
r242885r242886
114127  luaL_checktype(L, 1, LUA_TTABLE);
115128  luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
116129                    "nil or table expected");
117  if (luaL_getmetafield(L, 1, "__metatable"))
130  if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
118131    return luaL_error(L, "cannot change a protected metatable");
119132  lua_settop(L, 2);
120133  lua_setmetatable(L, 1);
r242885r242886
160173static int luaB_collectgarbage (lua_State *L) {
161174  static const char *const opts[] = {"stop", "restart", "collect",
162175    "count", "step", "setpause", "setstepmul",
163    "setmajorinc", "isrunning", "generational", "incremental", NULL};
176    "isrunning", NULL};
164177  static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
165178    LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
166    LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
179    LUA_GCISRUNNING};
167180  int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
168  int ex = luaL_optint(L, 2, 0);
181  int ex = (int)luaL_optinteger(L, 2, 0);
169182  int res = lua_gc(L, o, ex);
170183  switch (o) {
171184    case LUA_GCCOUNT: {
172185      int b = lua_gc(L, LUA_GCCOUNTB, 0);
173      lua_pushnumber(L, res + ((lua_Number)b/1024));
174      lua_pushinteger(L, b);
175      return 2;
186      lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));
187      return 1;
176188    }
177189    case LUA_GCSTEP: case LUA_GCISRUNNING: {
178190      lua_pushboolean(L, res);
r242885r242886
186198}
187199
188200
201/*
202** This function has all type names as upvalues, to maximize performance.
203*/
189204static int luaB_type (lua_State *L) {
190205  luaL_checkany(L, 1);
191  lua_pushstring(L, luaL_typename(L, 1));
206  lua_pushvalue(L, lua_upvalueindex(lua_type(L, 1) + 1));
192207  return 1;
193208}
194209
195210
196211static int pairsmeta (lua_State *L, const char *method, int iszero,
197212                      lua_CFunction iter) {
198  if (!luaL_getmetafield(L, 1, method)) {  /* no metamethod? */
213  if (luaL_getmetafield(L, 1, method) == LUA_TNIL) {  /* no metamethod? */
199214    luaL_checktype(L, 1, LUA_TTABLE);  /* argument must be a table */
200215    lua_pushcfunction(L, iter);  /* will return generator, */
201216    lua_pushvalue(L, 1);  /* state, */
r242885r242886
227242}
228243
229244
230static int ipairsaux (lua_State *L) {
231  int i = luaL_checkint(L, 2);
245/*
246** Traversal function for 'ipairs' for raw tables
247*/
248static int ipairsaux_raw (lua_State *L) {
249  lua_Integer i = luaL_checkinteger(L, 2) + 1;
232250  luaL_checktype(L, 1, LUA_TTABLE);
233  i++;  /* next value */
234251  lua_pushinteger(L, i);
235  lua_rawgeti(L, 1, i);
236  return (lua_isnil(L, -1)) ? 1 : 2;
252  return (lua_rawgeti(L, 1, i) == LUA_TNIL) ? 1 : 2;
237253}
238254
239255
256/*
257** Traversal function for 'ipairs' for tables with metamethods
258*/
259static int ipairsaux (lua_State *L) {
260  lua_Integer i = luaL_checkinteger(L, 2) + 1;
261  lua_pushinteger(L, i);
262  return (lua_geti(L, 1, i) == LUA_TNIL) ? 1 : 2;
263}
264
265
266/*
267** This function will use either 'ipairsaux' or 'ipairsaux_raw' to
268** traverse a table, depending on whether the table has metamethods
269** that can affect the traversal.
270*/
240271static int luaB_ipairs (lua_State *L) {
241  return pairsmeta(L, "__ipairs", 1, ipairsaux);
272  lua_CFunction iter = (luaL_getmetafield(L, 1, "__index") != LUA_TNIL)
273                       ? ipairsaux : ipairsaux_raw;
274#if defined(LUA_COMPAT_IPAIRS)
275  return pairsmeta(L, "__ipairs", 1, iter);
276#else
277  luaL_checkany(L, 1);
278  lua_pushcfunction(L, iter);  /* iteration function */
279  lua_pushvalue(L, 1);  /* state */
280  lua_pushinteger(L, 0);  /* initial value */
281  return 3;
282#endif
242283}
243284
244285
r242885r242886
284325
285326
286327/*
287** Reader for generic `load' function: `lua_load' uses the
328** Reader for generic 'load' function: 'lua_load' uses the
288329** stack for internal stuff, so the reader cannot change the
289330** stack top. Instead, it keeps its resulting string in a
290331** reserved slot inside the stack.
r242885r242886
328369/* }====================================================== */
329370
330371
331static int dofilecont (lua_State *L) {
372static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
373  (void)d1;  (void)d2;  /* only to match 'lua_Kfunction' prototype */
332374  return lua_gettop(L) - 1;
333375}
334376
r242885r242886
339381  if (luaL_loadfile(L, fname) != LUA_OK)
340382    return lua_error(L);
341383  lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
342  return dofilecont(L);
384  return dofilecont(L, 0, 0);
343385}
344386
345387
346388static int luaB_assert (lua_State *L) {
347  if (!lua_toboolean(L, 1))
348    return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
349  return lua_gettop(L);
389  if (lua_toboolean(L, 1))  /* condition is true? */
390    return lua_gettop(L);  /* return all arguments */
391  else {  /* error */
392    luaL_checkany(L, 1);  /* there must be a condition */
393    lua_remove(L, 1);  /* remove it */
394    lua_pushliteral(L, "assertion failed!");  /* default message */
395    lua_settop(L, 1);  /* leave only message (default if no other one) */
396    return luaB_error(L);  /* call 'error' */
397  }
350398}
351399
352400
r242885r242886
357405    return 1;
358406  }
359407  else {
360    int i = luaL_checkint(L, 1);
408    lua_Integer i = luaL_checkinteger(L, 1);
361409    if (i < 0) i = n + i;
362410    else if (i > n) i = n;
363411    luaL_argcheck(L, 1 <= i, 1, "index out of range");
364    return n - i;
412    return n - (int)i;
365413  }
366414}
367415
368416
369static int finishpcall (lua_State *L, int status) {
370  if (!lua_checkstack(L, 1)) {  /* no space for extra boolean? */
371    lua_settop(L, 0);  /* create space for return values */
372    lua_pushboolean(L, 0);
373    lua_pushstring(L, "stack overflow");
417/*
418** Continuation function for 'pcall' and 'xpcall'. Both functions
419** already pushed a 'true' before doing the call, so in case of success
420** 'finishpcall' only has to return everything in the stack minus
421** 'extra' values (where 'extra' is exactly the number of items to be
422** ignored).
423*/
424static int finishpcall (lua_State *L, int status, lua_KContext extra) {
425  if (status != LUA_OK && status != LUA_YIELD) {  /* error? */
426    lua_pushboolean(L, 0);  /* first result (false) */
427    lua_pushvalue(L, -2);  /* error message */
374428    return 2;  /* return false, msg */
375429  }
376  lua_pushboolean(L, status);  /* first result (status) */
377  lua_replace(L, 1);  /* put first result in first slot */
378  return lua_gettop(L);
430  else
431    return lua_gettop(L) - (int)extra;  /* return all results */
379432}
380433
381434
382static int pcallcont (lua_State *L) {
383  int status = lua_getctx(L, NULL);
384  return finishpcall(L, (status == LUA_YIELD));
385}
386
387
388435static int luaB_pcall (lua_State *L) {
389436  int status;
390437  luaL_checkany(L, 1);
391  lua_pushnil(L);
392  lua_insert(L, 1);  /* create space for status result */
393  status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, pcallcont);
394  return finishpcall(L, (status == LUA_OK));
438  lua_pushboolean(L, 1);  /* first result if no errors */
439  lua_insert(L, 1);  /* put it in place */
440  status = lua_pcallk(L, lua_gettop(L) - 2, LUA_MULTRET, 0, 0, finishpcall);
441  return finishpcall(L, status, 0);
395442}
396443
397444
445/*
446** Do a protected call with error handling. After 'lua_rotate', the
447** stack will have <f, err, true, f, [args...]>; so, the function passes
448** 2 to 'finishpcall' to skip the 2 first values when returning results.
449*/
398450static int luaB_xpcall (lua_State *L) {
399451  int status;
400452  int n = lua_gettop(L);
401  luaL_argcheck(L, n >= 2, 2, "value expected");
402  lua_pushvalue(L, 1);  /* exchange function... */
403  lua_copy(L, 2, 1);  /* ...and error handler */
404  lua_replace(L, 2);
405  status = lua_pcallk(L, n - 2, LUA_MULTRET, 1, 0, pcallcont);
406  return finishpcall(L, (status == LUA_OK));
453  luaL_checktype(L, 2, LUA_TFUNCTION);  /* check error function */
454  lua_pushboolean(L, 1);  /* first result */
455  lua_pushvalue(L, 1);  /* function */
456  lua_rotate(L, 3, 2);  /* move them below function's arguments */
457  status = lua_pcallk(L, n - 2, LUA_MULTRET, 2, 2, finishpcall);
458  return finishpcall(L, status, 2);
407459}
408460
409461
r242885r242886
438490  {"setmetatable", luaB_setmetatable},
439491  {"tonumber", luaB_tonumber},
440492  {"tostring", luaB_tostring},
441  {"type", luaB_type},
442493  {"xpcall", luaB_xpcall},
494  /* placeholders */
495  {"type", NULL},
496  {"_G", NULL},
497  {"_VERSION", NULL},
443498  {NULL, NULL}
444499};
445500
446501
447502LUAMOD_API int luaopen_base (lua_State *L) {
503  int i;
504  /* open lib into global table */
505  lua_pushglobaltable(L);
506  luaL_setfuncs(L, base_funcs, 0);
448507  /* set global _G */
449  lua_pushglobaltable(L);
450  lua_pushglobaltable(L);
508  lua_pushvalue(L, -1);
451509  lua_setfield(L, -2, "_G");
452  /* open lib into global table */
453  luaL_setfuncs(L, base_funcs, 0);
510  /* set global _VERSION */
454511  lua_pushliteral(L, LUA_VERSION);
455  lua_setfield(L, -2, "_VERSION");  /* set global _VERSION */
512  lua_setfield(L, -2, "_VERSION");
513  /* set function 'type' with proper upvalues */
514  for (i = 0; i < LUA_NUMTAGS; i++)  /* push all type names as upvalues */
515    lua_pushstring(L, lua_typename(L, i));
516  lua_pushcclosure(L, luaB_type, LUA_NUMTAGS);
517  lua_setfield(L, -2, "type");
456518  return 1;
457519}
458520
trunk/3rdparty/lua/src/lbitlib.c
r242885r242886
11/*
2** $Id: lbitlib.c,v 1.18.1.2 2013/07/09 18:01:41 roberto Exp $
2** $Id: lbitlib.c,v 1.28 2014/11/02 19:19:04 roberto Exp $
33** Standard library for bitwise operations
44** See Copyright Notice in lua.h
55*/
r242885r242886
77#define lbitlib_c
88#define LUA_LIB
99
10#include "lprefix.h"
11
12
1013#include "lua.h"
1114
1215#include "lauxlib.h"
1316#include "lualib.h"
1417
1518
19#if defined(LUA_COMPAT_BITLIB)      /* { */
20
21
1622/* number of bits to consider in a number */
1723#if !defined(LUA_NBITS)
1824#define LUA_NBITS   32
1925#endif
2026
2127
28/*
29** a lua_Unsigned with its first LUA_NBITS bits equal to 1. (Shift must
30** be made in two parts to avoid problems when LUA_NBITS is equal to the
31** number of bits in a lua_Unsigned.)
32*/
2233#define ALLONES      (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))
2334
35
2436/* macro to trim extra bits */
2537#define trim(x)      ((x) & ALLONES)
2638
r242885r242886
2941#define mask(n)      (~((ALLONES << 1) << ((n) - 1)))
3042
3143
32typedef lua_Unsigned b_uint;
3344
34
35
36static b_uint andaux (lua_State *L) {
45static lua_Unsigned andaux (lua_State *L) {
3746  int i, n = lua_gettop(L);
38  b_uint r = ~(b_uint)0;
47  lua_Unsigned r = ~(lua_Unsigned)0;
3948  for (i = 1; i <= n; i++)
4049    r &= luaL_checkunsigned(L, i);
4150  return trim(r);
r242885r242886
4352
4453
4554static int b_and (lua_State *L) {
46  b_uint r = andaux(L);
55  lua_Unsigned r = andaux(L);
4756  lua_pushunsigned(L, r);
4857  return 1;
4958}
5059
5160
5261static int b_test (lua_State *L) {
53  b_uint r = andaux(L);
62  lua_Unsigned r = andaux(L);
5463  lua_pushboolean(L, r != 0);
5564  return 1;
5665}
r242885r242886
5867
5968static int b_or (lua_State *L) {
6069  int i, n = lua_gettop(L);
61  b_uint r = 0;
70  lua_Unsigned r = 0;
6271  for (i = 1; i <= n; i++)
6372    r |= luaL_checkunsigned(L, i);
6473  lua_pushunsigned(L, trim(r));
r242885r242886
6877
6978static int b_xor (lua_State *L) {
7079  int i, n = lua_gettop(L);
71  b_uint r = 0;
80  lua_Unsigned r = 0;
7281  for (i = 1; i <= n; i++)
7382    r ^= luaL_checkunsigned(L, i);
7483  lua_pushunsigned(L, trim(r));
r242885r242886
7786
7887
7988static int b_not (lua_State *L) {
80  b_uint r = ~luaL_checkunsigned(L, 1);
89  lua_Unsigned r = ~luaL_checkunsigned(L, 1);
8190  lua_pushunsigned(L, trim(r));
8291  return 1;
8392}
8493
8594
86static int b_shift (lua_State *L, b_uint r, int i) {
95static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) {
8796  if (i < 0) {  /* shift right? */
8897    i = -i;
8998    r = trim(r);
r242885r242886
101110
102111
103112static int b_lshift (lua_State *L) {
104  return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkint(L, 2));
113  return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkinteger(L, 2));
105114}
106115
107116
108117static int b_rshift (lua_State *L) {
109  return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkint(L, 2));
118  return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkinteger(L, 2));
110119}
111120
112121
113122static int b_arshift (lua_State *L) {
114  b_uint r = luaL_checkunsigned(L, 1);
115  int i = luaL_checkint(L, 2);
116  if (i < 0 || !(r & ((b_uint)1 << (LUA_NBITS - 1))))
123  lua_Unsigned r = luaL_checkunsigned(L, 1);
124  lua_Integer i = luaL_checkinteger(L, 2);
125  if (i < 0 || !(r & ((lua_Unsigned)1 << (LUA_NBITS - 1))))
117126    return b_shift(L, r, -i);
118127  else {  /* arithmetic shift for 'negative' number */
119128    if (i >= LUA_NBITS) r = ALLONES;
120129    else
121      r = trim((r >> i) | ~(~(b_uint)0 >> i));  /* add signal bit */
130      r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i));  /* add signal bit */
122131    lua_pushunsigned(L, r);
123132    return 1;
124133  }
125134}
126135
127136
128static int b_rot (lua_State *L, int i) {
129  b_uint r = luaL_checkunsigned(L, 1);
130  i &= (LUA_NBITS - 1);  /* i = i % NBITS */
137static int b_rot (lua_State *L, lua_Integer d) {
138  lua_Unsigned r = luaL_checkunsigned(L, 1);
139  int i = d & (LUA_NBITS - 1);  /* i = d % NBITS */
131140  r = trim(r);
132141  if (i != 0)  /* avoid undefined shift of LUA_NBITS when i == 0 */
133142    r = (r << i) | (r >> (LUA_NBITS - i));
r242885r242886
137146
138147
139148static int b_lrot (lua_State *L) {
140  return b_rot(L, luaL_checkint(L, 2));
149  return b_rot(L, luaL_checkinteger(L, 2));
141150}
142151
143152
144153static int b_rrot (lua_State *L) {
145  return b_rot(L, -luaL_checkint(L, 2));
154  return b_rot(L, -luaL_checkinteger(L, 2));
146155}
147156
148157
r242885r242886
153162** 'width' being used uninitialized.)
154163*/
155164static int fieldargs (lua_State *L, int farg, int *width) {
156  int f = luaL_checkint(L, farg);
157  int w = luaL_optint(L, farg + 1, 1);
165  lua_Integer f = luaL_checkinteger(L, farg);
166  lua_Integer w = luaL_optinteger(L, farg + 1, 1);
158167  luaL_argcheck(L, 0 <= f, farg, "field cannot be negative");
159168  luaL_argcheck(L, 0 < w, farg + 1, "width must be positive");
160169  if (f + w > LUA_NBITS)
161170    luaL_error(L, "trying to access non-existent bits");
162  *width = w;
163  return f;
171  *width = (int)w;
172  return (int)f;
164173}
165174
166175
167176static int b_extract (lua_State *L) {
168177  int w;
169  b_uint r = luaL_checkunsigned(L, 1);
178  lua_Unsigned r = trim(luaL_checkunsigned(L, 1));
170179  int f = fieldargs(L, 2, &w);
171180  r = (r >> f) & mask(w);
172181  lua_pushunsigned(L, r);
r242885r242886
176185
177186static int b_replace (lua_State *L) {
178187  int w;
179  b_uint r = luaL_checkunsigned(L, 1);
180  b_uint v = luaL_checkunsigned(L, 2);
188  lua_Unsigned r = trim(luaL_checkunsigned(L, 1));
189  lua_Unsigned v = luaL_checkunsigned(L, 2);
181190  int f = fieldargs(L, 3, &w);
182191  int m = mask(w);
183192  v &= m;  /* erase bits outside given width */
r242885r242886
210219  return 1;
211220}
212221
222
223#else               /* }{ */
224
225
226LUAMOD_API int luaopen_bit32 (lua_State *L) {
227  return luaL_error(L, "library 'bit32' has been deprecated");
228}
229
230#endif               /* } */
trunk/3rdparty/lua/src/lcode.c
r242885r242886
11/*
2** $Id: lcode.c,v 2.62.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lcode.c,v 2.99 2014/12/29 16:49:25 roberto Exp $
33** Code generator for Lua
44** See Copyright Notice in lua.h
55*/
66
7#define lcode_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
13#include <math.h>
814#include <stdlib.h>
915
10#define lcode_c
11#define LUA_CORE
12
1316#include "lua.h"
1417
1518#include "lcode.h"
r242885r242886
2629#include "lvm.h"
2730
2831
32/* Maximum number of registers in a Lua function */
33#define MAXREGS      250
34
35
2936#define hasjumps(e)   ((e)->t != (e)->f)
3037
3138
32static int isnumeral(expdesc *e) {
33  return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP);
39static int tonumeral(expdesc *e, TValue *v) {
40  if (e->t != NO_JUMP || e->f != NO_JUMP)
41    return 0;  /* not a numeral */
42  switch (e->k) {
43    case VKINT:
44      if (v) setivalue(v, e->u.ival);
45      return 1;
46    case VKFLT:
47      if (v) setfltvalue(v, e->u.nval);
48      return 1;
49    default: return 0;
50  }
3451}
3552
3653
r242885r242886
88105
89106
90107/*
91** returns current `pc' and marks it as a jump target (to avoid wrong
108** returns current 'pc' and marks it as a jump target (to avoid wrong
92109** optimizations with consecutive instructions not in the same basic block).
93110*/
94111int luaK_getlabel (FuncState *fs) {
r242885r242886
176193}
177194
178195
179LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level) {
196void luaK_patchclose (FuncState *fs, int list, int level) {
180197  level++;  /* argument is +1 to reserve 0 as non-op */
181198  while (list != NO_JUMP) {
182199    int next = getjump(fs, list);
r242885r242886
211228
212229static int luaK_code (FuncState *fs, Instruction i) {
213230  Proto *f = fs->f;
214  dischargejpc(fs);  /* `pc' will change */
231  dischargejpc(fs);  /* 'pc' will change */
215232  /* put new instruction in code array */
216233  luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
217234                  MAX_INT, "opcodes");
r242885r242886
261278void luaK_checkstack (FuncState *fs, int n) {
262279  int newstack = fs->freereg + n;
263280  if (newstack > fs->f->maxstacksize) {
264    if (newstack >= MAXSTACK)
281    if (newstack >= MAXREGS)
265282      luaX_syntaxerror(fs->ls, "function or expression too complex");
266283    fs->f->maxstacksize = cast_byte(newstack);
267284  }
r242885r242886
288305}
289306
290307
308/*
309** Use scanner's table to cache position of constants in constant list
310** and try to reuse constants
311*/
291312static int addk (FuncState *fs, TValue *key, TValue *v) {
292313  lua_State *L = fs->ls->L;
293  TValue *idx = luaH_set(L, fs->h, key);
294314  Proto *f = fs->f;
315  TValue *idx = luaH_set(L, fs->ls->h, key);  /* index scanner table */
295316  int k, oldsize;
296  if (ttisnumber(idx)) {
297    lua_Number n = nvalue(idx);
298    lua_number2int(k, n);
299    if (luaV_rawequalobj(&f->k[k], v))
300      return k;
301    /* else may be a collision (e.g., between 0.0 and "\0\0\0\0\0\0\0\0");
302       go through and create a new entry for this value */
317  if (ttisinteger(idx)) {  /* is there an index there? */
318    k = cast_int(ivalue(idx));
319    /* correct value? (warning: must distinguish floats from integers!) */
320    if (k < fs->nk && ttype(&f->k[k]) == ttype(v) &&
321                      luaV_rawequalobj(&f->k[k], v))
322      return k;  /* reuse index */
303323  }
304324  /* constant not found; create a new entry */
305325  oldsize = f->sizek;
306326  k = fs->nk;
307327  /* numerical value does not need GC barrier;
308328     table has no metatable, so it does not need to invalidate cache */
309  setnvalue(idx, cast_num(k));
329  setivalue(idx, k);
310330  luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
311331  while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
312332  setobj(L, &f->k[k], v);
r242885r242886
323343}
324344
325345
326int luaK_numberK (FuncState *fs, lua_Number r) {
327  int n;
328  lua_State *L = fs->ls->L;
346/*
347** Integers use userdata as keys to avoid collision with floats with same
348** value; conversion to 'void*' used only for hashing, no "precision"
349** problems
350*/
351int luaK_intK (FuncState *fs, lua_Integer n) {
352  TValue k, o;
353  setpvalue(&k, cast(void*, cast(size_t, n)));
354  setivalue(&o, n);
355  return addk(fs, &k, &o);
356}
357
358
359static int luaK_numberK (FuncState *fs, lua_Number r) {
329360  TValue o;
330  setnvalue(&o, r);
331  if (r == 0 || luai_numisnan(NULL, r)) {  /* handle -0 and NaN */
332    /* use raw representation as key to avoid numeric problems */
333    setsvalue(L, L->top++, luaS_newlstr(L, (char *)&r, sizeof(r)));
334    n = addk(fs, L->top - 1, &o);
335    L->top--;
336  }
337  else
338    n = addk(fs, &o, &o);  /* regular case */
339  return n;
361  setfltvalue(&o, r);
362  return addk(fs, &o, &o);
340363}
341364
342365
r242885r242886
351374  TValue k, v;
352375  setnilvalue(&v);
353376  /* cannot use nil as key; instead use table itself to represent nil */
354  sethvalue(fs->ls->L, &k, fs->h);
377  sethvalue(fs->ls->L, &k, fs->ls->h);
355378  return addk(fs, &k, &v);
356379}
357380
r242885r242886
433456      luaK_codek(fs, reg, e->u.info);
434457      break;
435458    }
436    case VKNUM: {
459    case VKFLT: {
437460      luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval));
438461      break;
439462    }
463    case VKINT: {
464      luaK_codek(fs, reg, luaK_intK(fs, e->u.ival));
465      break;
466    }
440467    case VRELOCABLE: {
441468      Instruction *pc = &getcode(fs, e);
442469      SETARG_A(*pc, reg);
r242885r242886
468495static void exp2reg (FuncState *fs, expdesc *e, int reg) {
469496  discharge2reg(fs, e, reg);
470497  if (e->k == VJMP)
471    luaK_concat(fs, &e->t, e->u.info);  /* put this jump in `t' list */
498    luaK_concat(fs, &e->t, e->u.info);  /* put this jump in 't' list */
472499  if (hasjumps(e)) {
473500    int final;  /* position after whole expression */
474501    int p_f = NO_JUMP;  /* position of an eventual LOAD false */
r242885r242886
538565      }
539566      else break;
540567    }
541    case VKNUM: {
568    case VKINT: {
569      e->u.info = luaK_intK(fs, e->u.ival);
570      e->k = VK;
571      goto vk;
572    }
573    case VKFLT: {
542574      e->u.info = luaK_numberK(fs, e->u.nval);
543575      e->k = VK;
544576      /* go through */
545577    }
546578    case VK: {
547      if (e->u.info <= MAXINDEXRK)  /* constant fits in argC? */
579     vk:
580      if (e->u.info <= MAXINDEXRK)  /* constant fits in 'argC'? */
548581        return RKASK(e->u.info);
549582      else break;
550583    }
r242885r242886
627660      pc = e->u.info;
628661      break;
629662    }
630    case VK: case VKNUM: case VTRUE: {
663    case VK: case VKFLT: case VKINT: case VTRUE: {
631664      pc = NO_JUMP;  /* always true; do nothing */
632665      break;
633666    }
r242885r242886
636669      break;
637670    }
638671  }
639  luaK_concat(fs, &e->f, pc);  /* insert last jump in `f' list */
672  luaK_concat(fs, &e->f, pc);  /* insert last jump in 'f' list */
640673  luaK_patchtohere(fs, e->t);
641674  e->t = NO_JUMP;
642675}
r242885r242886
659692      break;
660693    }
661694  }
662  luaK_concat(fs, &e->t, pc);  /* insert last jump in `t' list */
695  luaK_concat(fs, &e->t, pc);  /* insert last jump in 't' list */
663696  luaK_patchtohere(fs, e->f);
664697  e->f = NO_JUMP;
665698}
r242885r242886
672705      e->k = VTRUE;
673706      break;
674707    }
675    case VK: case VKNUM: case VTRUE: {
708    case VK: case VKFLT: case VKINT: case VTRUE: {
676709      e->k = VFALSE;
677710      break;
678711    }
r242885r242886
710743}
711744
712745
713static int constfolding (OpCode op, expdesc *e1, expdesc *e2) {
714  lua_Number r;
715  if (!isnumeral(e1) || !isnumeral(e2)) return 0;
716  if ((op == OP_DIV || op == OP_MOD) && e2->u.nval == 0)
717    return 0;  /* do not attempt to divide by 0 */
718  r = luaO_arith(op - OP_ADD + LUA_OPADD, e1->u.nval, e2->u.nval);
719  e1->u.nval = r;
746/*
747** return false if folding can raise an error
748*/
749static int validop (int op, TValue *v1, TValue *v2) {
750  switch (op) {
751    case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
752    case LUA_OPSHL: case LUA_OPSHR: case LUA_OPBNOT: {  /* conversion errors */
753      lua_Integer i;
754      return (tointeger(v1, &i) && tointeger(v2, &i));
755    }
756    case LUA_OPDIV: case LUA_OPIDIV: case LUA_OPMOD:  /* division by 0 */
757      return (nvalue(v2) != 0);
758    default: return 1;  /* everything else is valid */
759  }
760}
761
762
763/*
764** Try to "constant-fold" an operation; return 1 iff successful
765*/
766static int constfolding (FuncState *fs, int op, expdesc *e1, expdesc *e2) {
767  TValue v1, v2, res;
768  if (!tonumeral(e1, &v1) || !tonumeral(e2, &v2) || !validop(op, &v1, &v2))
769    return 0;  /* non-numeric operands or not safe to fold */
770  luaO_arith(fs->ls->L, op, &v1, &v2, &res);  /* does operation */
771  if (ttisinteger(&res)) {
772    e1->k = VKINT;
773    e1->u.ival = ivalue(&res);
774  }
775  else {  /* folds neither NaN nor 0.0 (to avoid collapsing with -0.0) */
776    lua_Number n = fltvalue(&res);
777    if (luai_numisnan(n) || n == 0)
778      return 0;
779    e1->k = VKFLT;
780    e1->u.nval = n;
781  }
720782  return 1;
721783}
722784
723785
724static void codearith (FuncState *fs, OpCode op,
725                       expdesc *e1, expdesc *e2, int line) {
726  if (constfolding(op, e1, e2))
727    return;
786/*
787** Code for binary and unary expressions that "produce values"
788** (arithmetic operations, bitwise operations, concat, length). First
789** try to do constant folding (only for numeric [arithmetic and
790** bitwise] operations, which is what 'lua_arith' accepts).
791** Expression to produce final result will be encoded in 'e1'.
792*/
793static void codeexpval (FuncState *fs, OpCode op,
794                        expdesc *e1, expdesc *e2, int line) {
795  lua_assert(op >= OP_ADD);
796  if (op <= OP_BNOT && constfolding(fs, op - OP_ADD + LUA_OPADD, e1, e2))
797    return;  /* result has been folded */
728798  else {
729    int o2 = (op != OP_UNM && op != OP_LEN) ? luaK_exp2RK(fs, e2) : 0;
730    int o1 = luaK_exp2RK(fs, e1);
731    if (o1 > o2) {
799    int o1, o2;
800    /* move operands to registers (if needed) */
801    if (op == OP_UNM || op == OP_BNOT || op == OP_LEN) {  /* unary op? */
802      o2 = 0;  /* no second expression */
803      o1 = luaK_exp2anyreg(fs, e1);  /* cannot operate on constants */
804    }
805    else {  /* regular case (binary operators) */
806      o2 = luaK_exp2RK(fs, e2);  /* both operands are "RK" */
807      o1 = luaK_exp2RK(fs, e1);
808    }
809    if (o1 > o2) {  /* free registers in proper order */
732810      freeexp(fs, e1);
733811      freeexp(fs, e2);
734812    }
r242885r242886
736814      freeexp(fs, e2);
737815      freeexp(fs, e1);
738816    }
739    e1->u.info = luaK_codeABC(fs, op, 0, o1, o2);
740    e1->k = VRELOCABLE;
817    e1->u.info = luaK_codeABC(fs, op, 0, o1, o2);  /* generate opcode */
818    e1->k = VRELOCABLE;  /* all those operations are relocable */
741819    luaK_fixline(fs, line);
742820  }
743821}
r242885r242886
750828  freeexp(fs, e2);
751829  freeexp(fs, e1);
752830  if (cond == 0 && op != OP_EQ) {
753    int temp;  /* exchange args to replace by `<' or `<=' */
831    int temp;  /* exchange args to replace by '<' or '<=' */
754832    temp = o1; o1 = o2; o2 = temp;  /* o1 <==> o2 */
755833    cond = 1;
756834  }
r242885r242886
761839
762840void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
763841  expdesc e2;
764  e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0;
842  e2.t = e2.f = NO_JUMP; e2.k = VKINT; e2.u.ival = 0;
765843  switch (op) {
766    case OPR_MINUS: {
767      if (isnumeral(e))  /* minus constant? */
768        e->u.nval = luai_numunm(NULL, e->u.nval);  /* fold it */
769      else {
770        luaK_exp2anyreg(fs, e);
771        codearith(fs, OP_UNM, e, &e2, line);
772      }
844    case OPR_MINUS: case OPR_BNOT: case OPR_LEN: {
845      codeexpval(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line);
773846      break;
774847    }
775848    case OPR_NOT: codenot(fs, e); break;
776    case OPR_LEN: {
777      luaK_exp2anyreg(fs, e);  /* cannot operate on constants */
778      codearith(fs, OP_LEN, e, &e2, line);
779      break;
780    }
781849    default: lua_assert(0);
782850  }
783851}
r242885r242886
794862      break;
795863    }
796864    case OPR_CONCAT: {
797      luaK_exp2nextreg(fs, v);  /* operand must be on the `stack' */
865      luaK_exp2nextreg(fs, v);  /* operand must be on the 'stack' */
798866      break;
799867    }
800    case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
801    case OPR_MOD: case OPR_POW: {
802      if (!isnumeral(v)) luaK_exp2RK(fs, v);
868    case OPR_ADD: case OPR_SUB:
869    case OPR_MUL: case OPR_DIV: case OPR_IDIV:
870    case OPR_MOD: case OPR_POW:
871    case OPR_BAND: case OPR_BOR: case OPR_BXOR:
872    case OPR_SHL: case OPR_SHR: {
873      if (!tonumeral(v, NULL)) luaK_exp2RK(fs, v);
803874      break;
804875    }
805876    default: {
r242885r242886
837908      }
838909      else {
839910        luaK_exp2nextreg(fs, e2);  /* operand must be on the 'stack' */
840        codearith(fs, OP_CONCAT, e1, e2, line);
911        codeexpval(fs, OP_CONCAT, e1, e2, line);
841912      }
842913      break;
843914    }
844915    case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
845    case OPR_MOD: case OPR_POW: {
846      codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2, line);
916    case OPR_IDIV: case OPR_MOD: case OPR_POW:
917    case OPR_BAND: case OPR_BOR: case OPR_BXOR:
918    case OPR_SHL: case OPR_SHR: {
919      codeexpval(fs, cast(OpCode, (op - OPR_ADD) + OP_ADD), e1, e2, line);
847920      break;
848921    }
849922    case OPR_EQ: case OPR_LT: case OPR_LE: {
trunk/3rdparty/lua/src/lcode.h
r242885r242886
11/*
2** $Id: lcode.h,v 1.58.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lcode.h,v 1.63 2013/12/30 20:47:58 roberto Exp $
33** Code generator for Lua
44** See Copyright Notice in lua.h
55*/
r242885r242886
2424** grep "ORDER OPR" if you change these enums  (ORDER OP)
2525*/
2626typedef enum BinOpr {
27  OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW,
27  OPR_ADD, OPR_SUB, OPR_MUL, OPR_MOD, OPR_POW,
28  OPR_DIV,
29  OPR_IDIV,
30  OPR_BAND, OPR_BOR, OPR_BXOR,
31  OPR_SHL, OPR_SHR,
2832  OPR_CONCAT,
2933  OPR_EQ, OPR_LT, OPR_LE,
3034  OPR_NE, OPR_GT, OPR_GE,
r242885r242886
3337} BinOpr;
3438
3539
36typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
40typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
3741
3842
3943#define getcode(fs,e)   ((fs)->f->code[(e)->u.info])
r242885r242886
5256LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
5357LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);
5458LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);
55LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r);
59LUAI_FUNC int luaK_intK (FuncState *fs, lua_Integer n);
5660LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
5761LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);
5862LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e);
trunk/3rdparty/lua/src/lcorolib.c
r242885r242886
11/*
2** $Id: lcorolib.c,v 1.5.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lcorolib.c,v 1.9 2014/11/02 19:19:04 roberto Exp $
33** Coroutine Library
44** See Copyright Notice in lua.h
55*/
66
7#define lcorolib_c
8#define LUA_LIB
79
8#include <stdlib.h>
10#include "lprefix.h"
911
1012
11#define lcorolib_c
12#define LUA_LIB
13#include <stdlib.h>
1314
1415#include "lua.h"
1516
r242885r242886
1718#include "lualib.h"
1819
1920
21static lua_State *getco (lua_State *L) {
22  lua_State *co = lua_tothread(L, 1);
23  luaL_argcheck(L, co, 1, "thread expected");
24  return co;
25}
26
27
2028static int auxresume (lua_State *L, lua_State *co, int narg) {
2129  int status;
2230  if (!lua_checkstack(co, narg)) {
r242885r242886
4755
4856
4957static int luaB_coresume (lua_State *L) {
50  lua_State *co = lua_tothread(L, 1);
58  lua_State *co = getco(L);
5159  int r;
52  luaL_argcheck(L, co, 1, "coroutine expected");
5360  r = auxresume(L, co, lua_gettop(L) - 1);
5461  if (r < 0) {
5562    lua_pushboolean(L, 0);
r242885r242886
5966  else {
6067    lua_pushboolean(L, 1);
6168    lua_insert(L, -(r + 1));
62    return r + 1;  /* return true + `resume' returns */
69    return r + 1;  /* return true + 'resume' returns */
6370  }
6471}
6572
r242885r242886
102109
103110
104111static int luaB_costatus (lua_State *L) {
105  lua_State *co = lua_tothread(L, 1);
106  luaL_argcheck(L, co, 1, "coroutine expected");
112  lua_State *co = getco(L);
107113  if (L == co) lua_pushliteral(L, "running");
108114  else {
109115    switch (lua_status(co)) {
r242885r242886
129135}
130136
131137
138static int luaB_yieldable (lua_State *L) {
139  lua_pushboolean(L, lua_isyieldable(L));
140  return 1;
141}
142
143
132144static int luaB_corunning (lua_State *L) {
133145  int ismain = lua_pushthread(L);
134146  lua_pushboolean(L, ismain);
r242885r242886
143155  {"status", luaB_costatus},
144156  {"wrap", luaB_cowrap},
145157  {"yield", luaB_yield},
158  {"isyieldable", luaB_yieldable},
146159  {NULL, NULL}
147160};
148161
trunk/3rdparty/lua/src/lctype.c
r242885r242886
11/*
2** $Id: lctype.c,v 1.11.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lctype.c,v 1.12 2014/11/02 19:19:04 roberto Exp $
33** 'ctype' functions for Lua
44** See Copyright Notice in lua.h
55*/
r242885r242886
77#define lctype_c
88#define LUA_CORE
99
10#include "lprefix.h"
11
12
1013#include "lctype.h"
1114
1215#if !LUA_USE_CTYPE   /* { */
trunk/3rdparty/lua/src/lctype.h
r242885r242886
11/*
2** $Id: lctype.h,v 1.12.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lctype.h,v 1.12 2011/07/15 12:50:29 roberto Exp $
33** 'ctype' functions for Lua
44** See Copyright Notice in lua.h
55*/
trunk/3rdparty/lua/src/ldblib.c
r242885r242886
11/*
2** $Id: ldblib.c,v 1.132.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: ldblib.c,v 1.148 2015/01/02 12:52:22 roberto Exp $
33** Interface from Lua to its debug API
44** See Copyright Notice in lua.h
55*/
66
7#define ldblib_c
8#define LUA_LIB
79
10#include "lprefix.h"
11
12
813#include <stdio.h>
914#include <stdlib.h>
1015#include <string.h>
1116
12#define ldblib_c
13#define LUA_LIB
14
1517#include "lua.h"
1618
1719#include "lauxlib.h"
1820#include "lualib.h"
1921
2022
21#define HOOKKEY      "_HKEY"
23/*
24** The hook table at registry[&HOOKKEY] maps threads to their current
25** hook function. (We only need the unique address of 'HOOKKEY'.)
26*/
27static const int HOOKKEY = 0;
2228
2329
24
2530static int db_getregistry (lua_State *L) {
2631  lua_pushvalue(L, LUA_REGISTRYINDEX);
2732  return 1;
r242885r242886
5762
5863
5964static int db_setuservalue (lua_State *L) {
60  if (lua_type(L, 1) == LUA_TLIGHTUSERDATA)
61    luaL_argerror(L, 1, "full userdata expected, got light userdata");
6265  luaL_checktype(L, 1, LUA_TUSERDATA);
63  if (!lua_isnoneornil(L, 2))
64    luaL_checktype(L, 2, LUA_TTABLE);
66  luaL_checkany(L, 2);
6567  lua_settop(L, 2);
6668  lua_setuservalue(L, 1);
6769  return 1;
6870}
6971
7072
71static void settabss (lua_State *L, const char *i, const char *v) {
72  lua_pushstring(L, v);
73  lua_setfield(L, -2, i);
74}
75
76
77static void settabsi (lua_State *L, const char *i, int v) {
78  lua_pushinteger(L, v);
79  lua_setfield(L, -2, i);
80}
81
82
83static void settabsb (lua_State *L, const char *i, int v) {
84  lua_pushboolean(L, v);
85  lua_setfield(L, -2, i);
86}
87
88
73/*
74** Auxiliary function used by several library functions: check for
75** an optional thread as function's first argument and set 'arg' with
76** 1 if this argument is present (so that functions can skip it to
77** access their other arguments)
78*/
8979static lua_State *getthread (lua_State *L, int *arg) {
9080  if (lua_isthread(L, 1)) {
9181    *arg = 1;
r242885r242886
9383  }
9484  else {
9585    *arg = 0;
96    return L;
86    return L;  /* function will operate over current thread */
9787  }
9888}
9989
10090
91/*
92** Variations of 'lua_settable', used by 'db_getinfo' to put results
93** from 'lua_getinfo' into result table. Key is always a string;
94** value can be a string, an int, or a boolean.
95*/
96static void settabss (lua_State *L, const char *k, const char *v) {
97  lua_pushstring(L, v);
98  lua_setfield(L, -2, k);
99}
100
101static void settabsi (lua_State *L, const char *k, int v) {
102  lua_pushinteger(L, v);
103  lua_setfield(L, -2, k);
104}
105
106static void settabsb (lua_State *L, const char *k, int v) {
107  lua_pushboolean(L, v);
108  lua_setfield(L, -2, k);
109}
110
111
112/*
113** In function 'db_getinfo', the call to 'lua_getinfo' may push
114** results on the stack; later it creates the result table to put
115** these objects. Function 'treatstackoption' puts the result from
116** 'lua_getinfo' on top of the result table so that it can call
117** 'lua_setfield'.
118*/
101119static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) {
102  if (L == L1) {
103    lua_pushvalue(L, -2);
104    lua_remove(L, -3);
105  }
120  if (L == L1)
121    lua_rotate(L, -2, 1);  /* exchange object and table */
106122  else
107    lua_xmove(L1, L, 1);
108  lua_setfield(L, -2, fname);
123    lua_xmove(L1, L, 1);  /* move object to the "main" stack */
124  lua_setfield(L, -2, fname);  /* put object into table */
109125}
110126
111127
128/*
129** Calls 'lua_getinfo' and collects all results in a new table.
130*/
112131static int db_getinfo (lua_State *L) {
113132  lua_Debug ar;
114133  int arg;
115134  lua_State *L1 = getthread(L, &arg);
116135  const char *options = luaL_optstring(L, arg+2, "flnStu");
117  if (lua_isnumber(L, arg+1)) {
118    if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) {
136  if (lua_isfunction(L, arg + 1)) {  /* info about a function? */
137    options = lua_pushfstring(L, ">%s", options);  /* add '>' to 'options' */
138    lua_pushvalue(L, arg + 1);  /* move function to 'L1' stack */
139    lua_xmove(L, L1, 1);
140  }
141  else {  /* stack level */
142    if (!lua_getstack(L1, (int)luaL_checkinteger(L, arg + 1), &ar)) {
119143      lua_pushnil(L);  /* level out of range */
120144      return 1;
121145    }
122146  }
123  else if (lua_isfunction(L, arg+1)) {
124    lua_pushfstring(L, ">%s", options);
125    options = lua_tostring(L, -1);
126    lua_pushvalue(L, arg+1);
127    lua_xmove(L, L1, 1);
128  }
129  else
130    return luaL_argerror(L, arg+1, "function or level expected");
131147  if (!lua_getinfo(L1, options, &ar))
132148    return luaL_argerror(L, arg+2, "invalid option");
133  lua_createtable(L, 0, 2);
149  lua_newtable(L);  /* table to collect results */
134150  if (strchr(options, 'S')) {
135151    settabss(L, "source", ar.source);
136152    settabss(L, "short_src", ar.short_src);
r242885r242886
164180  lua_State *L1 = getthread(L, &arg);
165181  lua_Debug ar;
166182  const char *name;
167  int nvar = luaL_checkint(L, arg+2);  /* local-variable index */
183  int nvar = (int)luaL_checkinteger(L, arg + 2);  /* local-variable index */
168184  if (lua_isfunction(L, arg + 1)) {  /* function argument? */
169185    lua_pushvalue(L, arg + 1);  /* push function */
170186    lua_pushstring(L, lua_getlocal(L, NULL, nvar));  /* push local name */
171    return 1;
187    return 1;  /* return only name (there is no value) */
172188  }
173189  else {  /* stack-level argument */
174    if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar))  /* out of range? */
190    int level = (int)luaL_checkinteger(L, arg + 1);
191    if (!lua_getstack(L1, level, &ar))  /* out of range? */
175192      return luaL_argerror(L, arg+1, "level out of range");
176193    name = lua_getlocal(L1, &ar, nvar);
177194    if (name) {
178      lua_xmove(L1, L, 1);  /* push local value */
195      lua_xmove(L1, L, 1);  /* move local value */
179196      lua_pushstring(L, name);  /* push name */
180      lua_pushvalue(L, -2);  /* re-order */
197      lua_rotate(L, -2, 1);  /* re-order */
181198      return 2;
182199    }
183200    else {
r242885r242886
190207
191208static int db_setlocal (lua_State *L) {
192209  int arg;
210  const char *name;
193211  lua_State *L1 = getthread(L, &arg);
194212  lua_Debug ar;
195  if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar))  /* out of range? */
213  int level = (int)luaL_checkinteger(L, arg + 1);
214  int nvar = (int)luaL_checkinteger(L, arg + 2);
215  if (!lua_getstack(L1, level, &ar))  /* out of range? */
196216    return luaL_argerror(L, arg+1, "level out of range");
197217  luaL_checkany(L, arg+3);
198218  lua_settop(L, arg+3);
199219  lua_xmove(L, L1, 1);
200  lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2)));
220  name = lua_setlocal(L1, &ar, nvar);
221  if (name == NULL)
222    lua_pop(L1, 1);  /* pop value (if not popped by 'lua_setlocal') */
223  lua_pushstring(L, name);
201224  return 1;
202225}
203226
204227
228/*
229** get (if 'get' is true) or set an upvalue from a closure
230*/
205231static int auxupvalue (lua_State *L, int get) {
206232  const char *name;
207  int n = luaL_checkint(L, 2);
208  luaL_checktype(L, 1, LUA_TFUNCTION);
233  int n = (int)luaL_checkinteger(L, 2);  /* upvalue index */
234  luaL_checktype(L, 1, LUA_TFUNCTION);  /* closure */
209235  name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
210236  if (name == NULL) return 0;
211237  lua_pushstring(L, name);
212  lua_insert(L, -(get+1));
238  lua_insert(L, -(get+1));  /* no-op if get is false */
213239  return get + 1;
214240}
215241
r242885r242886
225251}
226252
227253
254/*
255** Check whether a given upvalue from a given closure exists and
256** returns its index
257*/
228258static int checkupval (lua_State *L, int argf, int argnup) {
229  lua_Debug ar;
230  int nup = luaL_checkint(L, argnup);
231  luaL_checktype(L, argf, LUA_TFUNCTION);
232  lua_pushvalue(L, argf);
233  lua_getinfo(L, ">u", &ar);
234  luaL_argcheck(L, 1 <= nup && nup <= ar.nups, argnup, "invalid upvalue index");
259  int nup = (int)luaL_checkinteger(L, argnup);  /* upvalue index */
260  luaL_checktype(L, argf, LUA_TFUNCTION);  /* closure */
261  luaL_argcheck(L, (lua_getupvalue(L, argf, nup) != NULL), argnup,
262                   "invalid upvalue index");
235263  return nup;
236264}
237265
r242885r242886
253281}
254282
255283
256#define gethooktable(L)   luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)
257
258
284/*
285** Call hook function registered at hook table for the current
286** thread (if there is one)
287*/
259288static void hookf (lua_State *L, lua_Debug *ar) {
260289  static const char *const hooknames[] =
261290    {"call", "return", "line", "count", "tail call"};
262  gethooktable(L);
291  lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
263292  lua_pushthread(L);
264  lua_rawget(L, -2);
265  if (lua_isfunction(L, -1)) {
266    lua_pushstring(L, hooknames[(int)ar->event]);
293  if (lua_rawget(L, -2) == LUA_TFUNCTION) {  /* is there a hook function? */
294    lua_pushstring(L, hooknames[(int)ar->event]);  /* push event name */
267295    if (ar->currentline >= 0)
268      lua_pushinteger(L, ar->currentline);
296      lua_pushinteger(L, ar->currentline);  /* push current line */
269297    else lua_pushnil(L);
270298    lua_assert(lua_getinfo(L, "lS", ar));
271    lua_call(L, 2, 0);
299    lua_call(L, 2, 0);  /* call hook function */
272300  }
273301}
274302
275303
304/*
305** Convert a string mask (for 'sethook') into a bit mask
306*/
276307static int makemask (const char *smask, int count) {
277308  int mask = 0;
278309  if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
r242885r242886
283314}
284315
285316
317/*
318** Convert a bit mask (for 'gethook') into a string mask
319*/
286320static char *unmakemask (int mask, char *smask) {
287321  int i = 0;
288322  if (mask & LUA_MASKCALL) smask[i++] = 'c';
r242885r242886
297331  int arg, mask, count;
298332  lua_Hook func;
299333  lua_State *L1 = getthread(L, &arg);
300  if (lua_isnoneornil(L, arg+1)) {
334  if (lua_isnoneornil(L, arg+1)) {  /* no hook? */
301335    lua_settop(L, arg+1);
302336    func = NULL; mask = 0; count = 0;  /* turn off hooks */
303337  }
304338  else {
305339    const char *smask = luaL_checkstring(L, arg+2);
306340    luaL_checktype(L, arg+1, LUA_TFUNCTION);
307    count = luaL_optint(L, arg+3, 0);
341    count = (int)luaL_optinteger(L, arg + 3, 0);
308342    func = hookf; mask = makemask(smask, count);
309343  }
310  if (gethooktable(L) == 0) {  /* creating hook table? */
344  if (lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY) == LUA_TNIL) {
345    lua_createtable(L, 0, 2);  /* create a hook table */
346    lua_pushvalue(L, -1);
347    lua_rawsetp(L, LUA_REGISTRYINDEX, &HOOKKEY);  /* set it in position */
311348    lua_pushstring(L, "k");
312349    lua_setfield(L, -2, "__mode");  /** hooktable.__mode = "k" */
313350    lua_pushvalue(L, -1);
314351    lua_setmetatable(L, -2);  /* setmetatable(hooktable) = hooktable */
315352  }
316  lua_pushthread(L1); lua_xmove(L1, L, 1);
317  lua_pushvalue(L, arg+1);
318  lua_rawset(L, -3);  /* set new hook */
319  lua_sethook(L1, func, mask, count);  /* set hooks */
353  lua_pushthread(L1); lua_xmove(L1, L, 1);  /* key (thread) */
354  lua_pushvalue(L, arg + 1);  /* value (hook function) */
355  lua_rawset(L, -3);  /* hooktable[L1] = new Lua hook */
356  lua_sethook(L1, func, mask, count);
320357  return 0;
321358}
322359
r242885r242886
327364  char buff[5];
328365  int mask = lua_gethookmask(L1);
329366  lua_Hook hook = lua_gethook(L1);
330  if (hook != NULL && hook != hookf)  /* external hook? */
367  if (hook == NULL)  /* no hook? */
368    lua_pushnil(L);
369  else if (hook != hookf)  /* external hook? */
331370    lua_pushliteral(L, "external hook");
332  else {
333    gethooktable(L);
371  else {  /* hook table must exist */
372    lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
334373    lua_pushthread(L1); lua_xmove(L1, L, 1);
335    lua_rawget(L, -2);   /* get hook */
374    lua_rawget(L, -2);   /* 1st result = hooktable[L1] */
336375    lua_remove(L, -2);  /* remove hook table */
337376  }
338  lua_pushstring(L, unmakemask(mask, buff));
339  lua_pushinteger(L, lua_gethookcount(L1));
377  lua_pushstring(L, unmakemask(mask, buff));  /* 2nd result = mask */
378  lua_pushinteger(L, lua_gethookcount(L1));  /* 3rd result = count */
340379  return 3;
341380}
342381
r242885r242886
344383static int db_debug (lua_State *L) {
345384  for (;;) {
346385    char buffer[250];
347    luai_writestringerror("%s", "lua_debug> ");
386    lua_writestringerror("%s", "lua_debug> ");
348387    if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
349388        strcmp(buffer, "cont\n") == 0)
350389      return 0;
351390    if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
352391        lua_pcall(L, 0, 0, 0))
353      luai_writestringerror("%s\n", lua_tostring(L, -1));
392      lua_writestringerror("%s\n", lua_tostring(L, -1));
354393    lua_settop(L, 0);  /* remove eventual returns */
355394  }
356395}
r242885r242886
363402  if (msg == NULL && !lua_isnoneornil(L, arg + 1))  /* non-string 'msg'? */
364403    lua_pushvalue(L, arg + 1);  /* return it untouched */
365404  else {
366    int level = luaL_optint(L, arg + 2, (L == L1) ? 1 : 0);
405    int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0);
367406    luaL_traceback(L, L1, msg, level);
368407  }
369408  return 1;
trunk/3rdparty/lua/src/ldebug.c
r242885r242886
11/*
2** $Id: ldebug.c,v 2.90.1.3 2013/05/16 16:04:15 roberto Exp $
2** $Id: ldebug.c,v 2.110 2015/01/02 12:52:22 roberto Exp $
33** Debug Interface
44** See Copyright Notice in lua.h
55*/
66
7#define ldebug_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <stdarg.h>
914#include <stddef.h>
1015#include <string.h>
1116
12
13#define ldebug_c
14#define LUA_CORE
15
1617#include "lua.h"
1718
1819#include "lapi.h"
r242885r242886
5051/*
5152** this function can be called asynchronous (e.g. during a signal)
5253*/
53LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
54LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
5455  if (func == NULL || mask == 0) {  /* turn off hooks? */
5556    mask = 0;
5657    func = NULL;
r242885r242886
6162  L->basehookcount = count;
6263  resethookcount(L);
6364  L->hookmask = cast_byte(mask);
64  return 1;
6565}
6666
6767
r242885r242886
167167  StkId pos = 0;  /* to avoid warnings */
168168  const char *name = findlocal(L, ar->i_ci, n, &pos);
169169  lua_lock(L);
170  if (name)
170  if (name) {
171171    setobjs2s(L, pos, L->top - 1);
172  L->top--;  /* pop value */
172    L->top--;  /* pop value */
173  }
173174  lua_unlock(L);
174175  return name;
175176}
r242885r242886
272273  if (*what == '>') {
273274    ci = NULL;
274275    func = L->top - 1;
275    api_check(L, ttisfunction(func), "function expected");
276    api_check(ttisfunction(func), "function expected");
276277    what++;  /* skip the '>' */
277278    L->top--;  /* pop function */
278279  }
r242885r242886
366367      case OP_JMP: {
367368        int b = GETARG_sBx(i);
368369        int dest = pc + 1 + b;
369        /* jump is forward and do not skip `lastpc'? */
370        /* jump is forward and do not skip 'lastpc'? */
370371        if (pc < dest && dest <= lastpc) {
371372          if (dest > jmptarget)
372373            jmptarget = dest;  /* update 'jmptarget' */
373374        }
374375        break;
375376      }
376      case OP_TEST: {
377        if (reg == a)  /* jumped code can change 'a' */
378          setreg = filterpc(pc, jmptarget);
379        break;
380      }
381377      default:
382378        if (testAMode(op) && reg == a)  /* any instruction that set A */
383379          setreg = filterpc(pc, jmptarget);
r242885r242886
443439
444440
445441static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
446  TMS tm;
442  TMS tm = (TMS)0;  /* to avoid warnings */
447443  Proto *p = ci_func(ci)->p;  /* calling function */
448444  int pc = currentpc(ci);  /* calling instruction index */
449445  Instruction i = p->code[pc];  /* calling instruction */
446  if (ci->callstatus & CIST_HOOKED) {  /* was it called inside a hook? */
447    *name = "?";
448    return "hook";
449  }
450450  switch (GET_OPCODE(i)) {
451451    case OP_CALL:
452452    case OP_TAILCALL:  /* get function name */
r242885r242886
456456       return "for iterator";
457457    }
458458    /* all other instructions can call only through metamethods */
459    case OP_SELF:
460    case OP_GETTABUP:
461    case OP_GETTABLE: tm = TM_INDEX; break;
462    case OP_SETTABUP:
463    case OP_SETTABLE: tm = TM_NEWINDEX; break;
464    case OP_EQ: tm = TM_EQ; break;
465    case OP_ADD: tm = TM_ADD; break;
466    case OP_SUB: tm = TM_SUB; break;
467    case OP_MUL: tm = TM_MUL; break;
468    case OP_DIV: tm = TM_DIV; break;
469    case OP_MOD: tm = TM_MOD; break;
470    case OP_POW: tm = TM_POW; break;
459    case OP_SELF: case OP_GETTABUP: case OP_GETTABLE:
460      tm = TM_INDEX;
461      break;
462    case OP_SETTABUP: case OP_SETTABLE:
463      tm = TM_NEWINDEX;
464      break;
465    case OP_ADD: case OP_SUB: case OP_MUL: case OP_MOD:
466    case OP_POW: case OP_DIV: case OP_IDIV: case OP_BAND:
467    case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR: {
468      int offset = cast_int(GET_OPCODE(i)) - cast_int(OP_ADD);  /* ORDER OP */
469      tm = cast(TMS, offset + cast_int(TM_ADD));  /* ORDER TM */
470      break;
471    }
471472    case OP_UNM: tm = TM_UNM; break;
473    case OP_BNOT: tm = TM_BNOT; break;
472474    case OP_LEN: tm = TM_LEN; break;
475    case OP_CONCAT: tm = TM_CONCAT; break;
476    case OP_EQ: tm = TM_EQ; break;
473477    case OP_LT: tm = TM_LT; break;
474478    case OP_LE: tm = TM_LE; break;
475    case OP_CONCAT: tm = TM_CONCAT; break;
476    default:
477      return NULL;  /* else no useful name can be found */
479    default: lua_assert(0);  /* other instructions cannot call a function */
478480  }
479481  *name = getstr(G(L)->tmname[tm]);
480482  return "metamethod";
r242885r242886
485487
486488
487489/*
488** only ANSI way to check whether a pointer points to an array
489** (used only for error messages, so efficiency is not a big concern)
490** The subtraction of two potentially unrelated pointers is
491** not ISO C, but it should not crash a program; the subsequent
492** checks are ISO C and ensure a correct result.
490493*/
491494static int isinstack (CallInfo *ci, const TValue *o) {
492  StkId p;
493  for (p = ci->u.l.base; p < ci->top; p++)
494    if (o == p) return 1;
495  return 0;
495  ptrdiff_t i = o - ci->u.l.base;
496  return (0 <= i && i < (ci->top - ci->u.l.base) && ci->u.l.base + i == o);
496497}
497498
498499
500/*
501** Checks whether value 'o' came from an upvalue. (That can only happen
502** with instructions OP_GETTABUP/OP_SETTABUP, which operate directly on
503** upvalues.)
504*/
499505static const char *getupvalname (CallInfo *ci, const TValue *o,
500506                                 const char **name) {
501507  LClosure *c = ci_func(ci);
r242885r242886
510516}
511517
512518
513l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
519static const char *varinfo (lua_State *L, const TValue *o) {
520  const char *name = NULL;  /* to avoid warnings */
514521  CallInfo *ci = L->ci;
515  const char *name = NULL;
516  const char *t = objtypename(o);
517522  const char *kind = NULL;
518523  if (isLua(ci)) {
519524    kind = getupvalname(ci, o, &name);  /* check whether 'o' is an upvalue */
r242885r242886
521526      kind = getobjname(ci_func(ci)->p, currentpc(ci),
522527                        cast_int(o - ci->u.l.base), &name);
523528  }
524  if (kind)
525    luaG_runerror(L, "attempt to %s %s " LUA_QS " (a %s value)",
526                op, kind, name, t);
527  else
528    luaG_runerror(L, "attempt to %s a %s value", op, t);
529  return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : "";
529530}
530531
531532
532l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2) {
533  if (ttisstring(p1) || ttisnumber(p1)) p1 = p2;
534  lua_assert(!ttisstring(p1) && !ttisnumber(p1));
533l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
534  const char *t = objtypename(o);
535  luaG_runerror(L, "attempt to %s a %s value%s", op, t, varinfo(L, o));
536}
537
538
539l_noret luaG_concaterror (lua_State *L, const TValue *p1, const TValue *p2) {
540  if (ttisstring(p1) || cvt2str(p1)) p1 = p2;
535541  luaG_typeerror(L, p1, "concatenate");
536542}
537543
538544
539l_noret luaG_aritherror (lua_State *L, const TValue *p1, const TValue *p2) {
540  TValue temp;
541  if (luaV_tonumber(p1, &temp) == NULL)
542    p2 = p1;  /* first operand is wrong */
543  luaG_typeerror(L, p2, "perform arithmetic on");
545l_noret luaG_opinterror (lua_State *L, const TValue *p1,
546                         const TValue *p2, const char *msg) {
547  lua_Number temp;
548  if (!tonumber(p1, &temp))  /* first operand is wrong? */
549    p2 = p1;  /* now second is wrong */
550  luaG_typeerror(L, p2, msg);
544551}
545552
546553
554/*
555** Error when both values are convertible to numbers, but not to integers
556*/
557l_noret luaG_tointerror (lua_State *L, const TValue *p1, const TValue *p2) {
558  lua_Integer temp;
559  if (!tointeger(p1, &temp))
560    p2 = p1;
561  luaG_runerror(L, "number%s has no integer representation", varinfo(L, p2));
562}
563
564
547565l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
548566  const char *t1 = objtypename(p1);
549567  const char *t2 = objtypename(p2);
r242885r242886
573591l_noret luaG_errormsg (lua_State *L) {
574592  if (L->errfunc != 0) {  /* is there an error handling function? */
575593    StkId errfunc = restorestack(L, L->errfunc);
576    if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR);
577594    setobjs2s(L, L->top, L->top - 1);  /* move argument */
578595    setobjs2s(L, L->top - 1, errfunc);  /* push function */
579    L->top++;
596    L->top++;  /* assume EXTRA_STACK */
580597    luaD_call(L, L->top - 2, 1, 0);  /* call it */
581598  }
582599  luaD_throw(L, LUA_ERRRUN);
r242885r242886
591608  luaG_errormsg(L);
592609}
593610
611
612void luaG_traceexec (lua_State *L) {
613  CallInfo *ci = L->ci;
614  lu_byte mask = L->hookmask;
615  int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0);
616  if (counthook)
617    resethookcount(L);  /* reset count */
618  if (ci->callstatus & CIST_HOOKYIELD) {  /* called hook last time? */
619    ci->callstatus &= ~CIST_HOOKYIELD;  /* erase mark */
620    return;  /* do not call hook again (VM yielded, so it did not move) */
621  }
622  if (counthook)
623    luaD_hook(L, LUA_HOOKCOUNT, -1);  /* call count hook */
624  if (mask & LUA_MASKLINE) {
625    Proto *p = ci_func(ci)->p;
626    int npc = pcRel(ci->u.l.savedpc, p);
627    int newline = getfuncline(p, npc);
628    if (npc == 0 ||  /* call linehook when enter a new function, */
629        ci->u.l.savedpc <= L->oldpc ||  /* when jump back (loop), or when */
630        newline != getfuncline(p, pcRel(L->oldpc, p)))  /* enter a new line */
631      luaD_hook(L, LUA_HOOKLINE, newline);  /* call line hook */
632  }
633  L->oldpc = ci->u.l.savedpc;
634  if (L->status == LUA_YIELD) {  /* did hook yield? */
635    if (counthook)
636      L->hookcount = 1;  /* undo decrement to zero */
637    ci->u.l.savedpc--;  /* undo increment (resume will increment it again) */
638    ci->callstatus |= CIST_HOOKYIELD;  /* mark that it yielded */
639    ci->func = L->top - 1;  /* protect stack below results */
640    luaD_throw(L, LUA_YIELD);
641  }
642}
643
trunk/3rdparty/lua/src/ldebug.h
r242885r242886
11/*
2** $Id: ldebug.h,v 2.7.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: ldebug.h,v 2.12 2014/11/10 14:46:05 roberto Exp $
33** Auxiliary functions from Debug Interface module
44** See Copyright Notice in lua.h
55*/
r242885r242886
1313
1414#define pcRel(pc, p)   (cast(int, (pc) - (p)->code) - 1)
1515
16#define getfuncline(f,pc)   (((f)->lineinfo) ? (f)->lineinfo[pc] : 0)
16#define getfuncline(f,pc)   (((f)->lineinfo) ? (f)->lineinfo[pc] : -1)
1717
1818#define resethookcount(L)   (L->hookcount = L->basehookcount)
1919
r242885r242886
2323
2424LUAI_FUNC l_noret luaG_typeerror (lua_State *L, const TValue *o,
2525                                                const char *opname);
26LUAI_FUNC l_noret luaG_concaterror (lua_State *L, StkId p1, StkId p2);
27LUAI_FUNC l_noret luaG_aritherror (lua_State *L, const TValue *p1,
26LUAI_FUNC l_noret luaG_concaterror (lua_State *L, const TValue *p1,
27                                                  const TValue *p2);
28LUAI_FUNC l_noret luaG_opinterror (lua_State *L, const TValue *p1,
29                                                 const TValue *p2,
30                                                 const char *msg);
31LUAI_FUNC l_noret luaG_tointerror (lua_State *L, const TValue *p1,
2832                                                 const TValue *p2);
2933LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,
3034                                                 const TValue *p2);
3135LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...);
3236LUAI_FUNC l_noret luaG_errormsg (lua_State *L);
37LUAI_FUNC void luaG_traceexec (lua_State *L);
3338
39
3440#endif
trunk/3rdparty/lua/src/ldo.c
r242885r242886
11/*
2** $Id: ldo.c,v 2.108.1.3 2013/11/08 18:22:50 roberto Exp $
2** $Id: ldo.c,v 2.135 2014/11/11 17:13:39 roberto Exp $
33** Stack and Call structure of Lua
44** See Copyright Notice in lua.h
55*/
66
7#define ldo_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <setjmp.h>
914#include <stdlib.h>
1015#include <string.h>
1116
12#define ldo_c
13#define LUA_CORE
14
1517#include "lua.h"
1618
1719#include "lapi.h"
r242885r242886
3335
3436
3537
38#define errorstatus(s)   ((s) > LUA_YIELD)
3639
40
3741/*
3842** {======================================================
3943** Error-recovery functions
r242885r242886
4650** C++ code, with _longjmp/_setjmp when asked to use them, and with
4751** longjmp/setjmp otherwise.
4852*/
49#if !defined(LUAI_THROW)
53#if !defined(LUAI_THROW)            /* { */
5054
51#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)
55#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)   /* { */
56
5257/* C++ exceptions */
5358#define LUAI_THROW(L,c)      throw(c)
5459#define LUAI_TRY(L,c,a) \
5560   try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
5661#define luai_jmpbuf      int  /* dummy variable */
5762
58#elif defined(LUA_USE_ULONGJMP)
59/* in Unix, try _longjmp/_setjmp (more efficient) */
63#elif defined(LUA_USE_POSIX)            /* }{ */
64
65/* in POSIX, try _longjmp/_setjmp (more efficient) */
6066#define LUAI_THROW(L,c)      _longjmp((c)->b, 1)
6167#define LUAI_TRY(L,c,a)      if (_setjmp((c)->b) == 0) { a }
6268#define luai_jmpbuf      jmp_buf
6369
64#else
65/* default handling with long jumps */
70#else                     /* }{ */
71
72/* ISO C handling with long jumps */
6673#define LUAI_THROW(L,c)      longjmp((c)->b, 1)
6774#define LUAI_TRY(L,c,a)      if (setjmp((c)->b) == 0) { a }
6875#define luai_jmpbuf      jmp_buf
6976
70#endif
77#endif                     /* } */
7178
72#endif
79#endif                     /* } */
7380
7481
7582
r242885r242886
106113    LUAI_THROW(L, L->errorJmp);  /* jump to it */
107114  }
108115  else {  /* thread has no error handler */
116    global_State *g = G(L);
109117    L->status = cast_byte(errcode);  /* mark it as dead */
110    if (G(L)->mainthread->errorJmp) {  /* main thread has a handler? */
111      setobjs2s(L, G(L)->mainthread->top++, L->top - 1);  /* copy error obj. */
112      luaD_throw(G(L)->mainthread, errcode);  /* re-throw in main thread */
118    if (g->mainthread->errorJmp) {  /* main thread has a handler? */
119      setobjs2s(L, g->mainthread->top++, L->top - 1);  /* copy error obj. */
120      luaD_throw(g->mainthread, errcode);  /* re-throw in main thread */
113121    }
114122    else {  /* no handler at all; abort */
115      if (G(L)->panic) {  /* panic function? */
123      if (g->panic) {  /* panic function? */
124        seterrorobj(L, errcode, L->top);  /* assume EXTRA_STACK */
125        if (L->ci->top < L->top)
126          L->ci->top = L->top;  /* pushing msg. can break this invariant */
116127        lua_unlock(L);
117        G(L)->panic(L);  /* call it (last chance to jump out) */
128        g->panic(L);  /* call panic function (last chance to jump out) */
118129      }
119130      abort();
120131    }
r242885r242886
141152
142153static void correctstack (lua_State *L, TValue *oldstack) {
143154  CallInfo *ci;
144  GCObject *up;
155  UpVal *up;
145156  L->top = (L->top - oldstack) + L->stack;
146  for (up = L->openupval; up != NULL; up = up->gch.next)
147    gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
157  for (up = L->openupval; up != NULL; up = up->u.open.next)
158    up->v = (up->v - oldstack) + L->stack;
148159  for (ci = L->ci; ci != NULL; ci = ci->previous) {
149160    ci->top = (ci->top - oldstack) + L->stack;
150161    ci->func = (ci->func - oldstack) + L->stack;
r242885r242886
206217  int inuse = stackinuse(L);
207218  int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
208219  if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;
209  if (inuse > LUAI_MAXSTACK ||  /* handling stack overflow? */
220  if (L->stacksize > LUAI_MAXSTACK)  /* was handling stack overflow? */
221    luaE_freeCI(L);  /* free all CIs (list grew because of an error) */
222  else
223    luaE_shrinkCI(L);  /* shrink list */
224  if (inuse > LUAI_MAXSTACK ||  /* still handling stack overflow? */
210225      goodsize >= L->stacksize)  /* would grow instead of shrink? */
211226    condmovestack(L);  /* don't change stack (change only for debugging) */
212227  else
r242885r242886
271286}
272287
273288
274static StkId tryfuncTM (lua_State *L, StkId func) {
289/*
290** Check whether __call metafield of 'func' is a function. If so, put
291** it in stack below original 'func' so that 'luaD_precall' can call
292** it. Raise an error if __call metafield is not a function.
293*/
294static void tryfuncTM (lua_State *L, StkId func) {
275295  const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
276296  StkId p;
277  ptrdiff_t funcr = savestack(L, func);
278297  if (!ttisfunction(tm))
279298    luaG_typeerror(L, func, "call");
280  /* Open a hole inside the stack at `func' */
281  for (p = L->top; p > func; p--) setobjs2s(L, p, p-1);
282  incr_top(L);
283  func = restorestack(L, funcr);  /* previous call may change stack */
299  /* Open a hole inside the stack at 'func' */
300  for (p = L->top; p > func; p--)
301    setobjs2s(L, p, p-1);
302  L->top++;  /* slot ensured by caller */
284303  setobj2s(L, func, tm);  /* tag method is the new function to be called */
285  return func;
286304}
287305
288306
r242885r242886
352370      return 0;
353371    }
354372    default: {  /* not a function */
355      func = tryfuncTM(L, func);  /* retry with 'function' tag method */
373      luaD_checkstack(L, 1);  /* ensure space for metamethod */
374      func = restorestack(L, funcr);  /* previous call may change stack */
375      tryfuncTM(L, func);  /* try to get '__call' metamethod */
356376      return luaD_precall(L, func, nresults);  /* now it must be a function */
357377    }
358378  }
r242885r242886
405425}
406426
407427
408static void finishCcall (lua_State *L) {
428/*
429** Completes the execution of an interrupted C function, calling its
430** continuation function.
431*/
432static void finishCcall (lua_State *L, int status) {
409433  CallInfo *ci = L->ci;
410434  int n;
411  lua_assert(ci->u.c.k != NULL);  /* must have a continuation */
412  lua_assert(L->nny == 0);
435  /* must have a continuation and must be able to call it */
436  lua_assert(ci->u.c.k != NULL && L->nny == 0);
437  /* error status can only happen in a protected call */
438  lua_assert((ci->callstatus & CIST_YPCALL) || status == LUA_YIELD);
413439  if (ci->callstatus & CIST_YPCALL) {  /* was inside a pcall? */
414440    ci->callstatus &= ~CIST_YPCALL;  /* finish 'lua_pcall' */
415441    L->errfunc = ci->u.c.old_errfunc;
416442  }
417  /* finish 'lua_callk'/'lua_pcall' */
443  /* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
444     handled */
418445  adjustresults(L, ci->nresults);
419446  /* call continuation function */
420  if (!(ci->callstatus & CIST_STAT))  /* no call status? */
421    ci->u.c.status = LUA_YIELD;  /* 'default' status */
422  lua_assert(ci->u.c.status != LUA_OK);
423  ci->callstatus = (ci->callstatus & ~(CIST_YPCALL | CIST_STAT)) | CIST_YIELDED;
424447  lua_unlock(L);
425  n = (*ci->u.c.k)(L);
448  n = (*ci->u.c.k)(L, status, ci->u.c.ctx);
426449  lua_lock(L);
427450  api_checknelems(L, n);
428451  /* finish 'luaD_precall' */
r242885r242886
430453}
431454
432455
456/*
457** Executes "full continuation" (everything in the stack) of a
458** previously interrupted coroutine until the stack is empty (or another
459** interruption long-jumps out of the loop). If the coroutine is
460** recovering from an error, 'ud' points to the error status, which must
461** be passed to the first continuation function (otherwise the default
462** status is LUA_YIELD).
463*/
433464static void unroll (lua_State *L, void *ud) {
434  UNUSED(ud);
435  for (;;) {
436    if (L->ci == &L->base_ci)  /* stack is empty? */
437      return;  /* coroutine finished normally */
465  if (ud != NULL)  /* error status? */
466    finishCcall(L, *(int *)ud);  /* finish 'lua_pcallk' callee */
467  while (L->ci != &L->base_ci) {  /* something in the stack */
438468    if (!isLua(L->ci))  /* C function? */
439      finishCcall(L);
469      finishCcall(L, LUA_YIELD);  /* complete its execution */
440470    else {  /* Lua function */
441471      luaV_finishOp(L);  /* finish interrupted instruction */
442472      luaV_execute(L);  /* execute down to higher C 'boundary' */
r242885r242886
446476
447477
448478/*
449** check whether thread has a suspended protected call
479** Try to find a suspended protected call (a "recover point") for the
480** given thread.
450481*/
451482static CallInfo *findpcall (lua_State *L) {
452483  CallInfo *ci;
r242885r242886
458489}
459490
460491
492/*
493** Recovers from an error in a coroutine. Finds a recover point (if
494** there is one) and completes the execution of the interrupted
495** 'luaD_pcall'. If there is no recover point, returns zero.
496*/
461497static int recover (lua_State *L, int status) {
462498  StkId oldtop;
463499  CallInfo *ci = findpcall(L);
r242885r242886
467503  luaF_close(L, oldtop);
468504  seterrorobj(L, status, oldtop);
469505  L->ci = ci;
470  L->allowhook = ci->u.c.old_allowhook;
506  L->allowhook = getoah(ci->callstatus);  /* restore original 'allowhook' */
471507  L->nny = 0;  /* should be zero to be yieldable */
472508  luaD_shrinkstack(L);
473509  L->errfunc = ci->u.c.old_errfunc;
474  ci->callstatus |= CIST_STAT;  /* call has error status */
475  ci->u.c.status = status;  /* (here it is) */
476510  return 1;  /* continue running the coroutine */
477511}
478512
r242885r242886
491525
492526
493527/*
494** do the work for 'lua_resume' in protected mode
528** Do the work for 'lua_resume' in protected mode. Most of the work
529** depends on the status of the coroutine: initial state, suspended
530** inside a hook, or regularly suspended (optionally with a continuation
531** function), plus erroneous cases: non-suspended coroutine or dead
532** coroutine.
495533*/
496534static void resume (lua_State *L, void *ud) {
497535  int nCcalls = L->nCcalls;
r242885r242886
509547  else if (L->status != LUA_YIELD)
510548    resume_error(L, "cannot resume dead coroutine", firstArg);
511549  else {  /* resuming from previous yield */
512    L->status = LUA_OK;
550    L->status = LUA_OK;  /* mark that it is running (again) */
513551    ci->func = restorestack(L, ci->extra);
514552    if (isLua(ci))  /* yielded inside a hook? */
515553      luaV_execute(L);  /* just continue running Lua code */
516554    else {  /* 'common' yield */
517      if (ci->u.c.k != NULL) {  /* does it have a continuation? */
555      if (ci->u.c.k != NULL) {  /* does it have a continuation function? */
518556        int n;
519        ci->u.c.status = LUA_YIELD;  /* 'default' status */
520        ci->callstatus |= CIST_YIELDED;
521557        lua_unlock(L);
522        n = (*ci->u.c.k)(L); /* call continuation */
558        n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
523559        lua_lock(L);
524560        api_checknelems(L, n);
525561        firstArg = L->top - n;  /* yield results come from continuation */
526562      }
527563      luaD_poscall(L, firstArg);  /* finish 'luaD_precall' */
528564    }
529    unroll(L, NULL);
565    unroll(L, NULL);  /* run continuation */
530566  }
531567  lua_assert(nCcalls == L->nCcalls);
532568}
r242885r242886
534570
535571LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
536572  int status;
537  int oldnny = L->nny;  /* save 'nny' */
573  int oldnny = L->nny;  /* save "number of non-yieldable" calls */
538574  lua_lock(L);
539575  luai_userstateresume(L, nargs);
540576  L->nCcalls = (from) ? from->nCcalls + 1 : 1;
r242885r242886
543579  status = luaD_rawrunprotected(L, resume, L->top - nargs);
544580  if (status == -1)  /* error calling 'lua_resume'? */
545581    status = LUA_ERRRUN;
546  else {  /* yield or regular error */
547    while (status != LUA_OK && status != LUA_YIELD) {  /* error? */
548      if (recover(L, status))  /* recover point? */
549        status = luaD_rawrunprotected(L, unroll, NULL);  /* run continuation */
550      else {  /* unrecoverable error */
551        L->status = cast_byte(status);  /* mark thread as `dead' */
552        seterrorobj(L, status, L->top);
553        L->ci->top = L->top;
554        break;
555      }
582  else {  /* continue running after recoverable errors */
583    while (errorstatus(status) && recover(L, status)) {
584      /* unroll continuation */
585      status = luaD_rawrunprotected(L, unroll, &status);
556586    }
557    lua_assert(status == L->status);
587    if (errorstatus(status)) {  /* unrecoverable error? */
588      L->status = cast_byte(status);  /* mark thread as 'dead' */
589      seterrorobj(L, status, L->top);  /* push error message */
590      L->ci->top = L->top;
591    }
592    else lua_assert(status == L->status);  /* normal end or yield */
558593  }
559594  L->nny = oldnny;  /* restore 'nny' */
560595  L->nCcalls--;
r242885r242886
564599}
565600
566601
567LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k) {
602LUA_API int lua_isyieldable (lua_State *L) {
603  return (L->nny == 0);
604}
605
606
607LUA_API int lua_yieldk (lua_State *L, int nresults, lua_KContext ctx,
608                        lua_KFunction k) {
568609  CallInfo *ci = L->ci;
569610  luai_userstateyield(L, nresults);
570611  lua_lock(L);
r242885r242886
578619  L->status = LUA_YIELD;
579620  ci->extra = savestack(L, ci->func);  /* save current 'func' */
580621  if (isLua(ci)) {  /* inside a hook? */
581    api_check(L, k == NULL, "hooks cannot continue after yielding");
622    api_check(k == NULL, "hooks cannot continue after yielding");
582623  }
583624  else {
584625    if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */
r242885r242886
619660/*
620661** Execute a protected parser.
621662*/
622struct SParser {  /* data to `f_parser' */
663struct SParser {  /* data to 'f_parser' */
623664  ZIO *z;
624665  Mbuffer buff;  /* dynamic structure used by the scanner */
625666  Dyndata dyd;  /* dynamic structures used by the parser */
r242885r242886
631672static void checkmode (lua_State *L, const char *mode, const char *x) {
632673  if (mode && strchr(mode, x[0]) == NULL) {
633674    luaO_pushfstring(L,
634       "attempt to load a %s chunk (mode is " LUA_QS ")", x, mode);
675       "attempt to load a %s chunk (mode is '%s')", x, mode);
635676    luaD_throw(L, LUA_ERRSYNTAX);
636677  }
637678}
638679
639680
640681static void f_parser (lua_State *L, void *ud) {
641  int i;
642  Closure *cl;
682  LClosure *cl;
643683  struct SParser *p = cast(struct SParser *, ud);
644684  int c = zgetc(p->z);  /* read first character */
645685  if (c == LUA_SIGNATURE[0]) {
r242885r242886
650690    checkmode(L, p->mode, "text");
651691    cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
652692  }
653  lua_assert(cl->l.nupvalues == cl->l.p->sizeupvalues);
654  for (i = 0; i < cl->l.nupvalues; i++) {  /* initialize upvalues */
655    UpVal *up = luaF_newupval(L);
656    cl->l.upvals[i] = up;
657    luaC_objbarrier(L, cl, up);
658  }
693  lua_assert(cl->nupvalues == cl->p->sizeupvalues);
694  luaF_initupvals(L, cl);
659695}
660696
661697
trunk/3rdparty/lua/src/ldo.h
r242885r242886
11/*
2** $Id: ldo.h,v 2.20.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: ldo.h,v 2.21 2014/10/25 11:50:46 roberto Exp $
33** Stack and Call structure of Lua
44** See Copyright Notice in lua.h
55*/
r242885r242886
2323#define restorestack(L,n)   ((TValue *)((char *)L->stack + (n)))
2424
2525
26/* type of protected functions, to be ran by `runprotected' */
26/* type of protected functions, to be ran by 'runprotected' */
2727typedef void (*Pfunc) (lua_State *L, void *ud);
2828
2929LUAI_FUNC int luaD_protectedparser (lua_State *L, ZIO *z, const char *name,
trunk/3rdparty/lua/src/ldump.c
r242885r242886
11/*
2** $Id: ldump.c,v 2.17.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: ldump.c,v 2.34 2014/11/02 19:19:04 roberto Exp $
33** save precompiled Lua chunks
44** See Copyright Notice in lua.h
55*/
66
7#include <stddef.h>
8
97#define ldump_c
108#define LUA_CORE
119
10#include "lprefix.h"
11
12
13#include <stddef.h>
14
1215#include "lua.h"
1316
1417#include "lobject.h"
1518#include "lstate.h"
1619#include "lundump.h"
1720
21
1822typedef struct {
19 lua_State* L;
20 lua_Writer writer;
21 void* data;
22 int strip;
23 int status;
23  lua_State *L;
24  lua_Writer writer;
25  void *data;
26  int strip;
27  int status;
2428} DumpState;
2529
26#define DumpMem(b,n,size,D)   DumpBlock(b,(n)*(size),D)
27#define DumpVar(x,D)      DumpMem(&x,1,sizeof(x),D)
2830
29static void DumpBlock(const void* b, size_t size, DumpState* D)
30{
31 if (D->status==0)
32 {
33  lua_unlock(D->L);
34  D->status=(*D->writer)(D->L,b,size,D->data);
35  lua_lock(D->L);
36 }
31/*
32** All high-level dumps go through DumpVector; you can change it to
33** change the endianness of the result
34*/
35#define DumpVector(v,n,D)   DumpBlock(v,(n)*sizeof((v)[0]),D)
36
37#define DumpLiteral(s,D)   DumpBlock(s, sizeof(s) - sizeof(char), D)
38
39
40static void DumpBlock (const void *b, size_t size, DumpState *D) {
41  if (D->status == 0) {
42    lua_unlock(D->L);
43    D->status = (*D->writer)(D->L, b, size, D->data);
44    lua_lock(D->L);
45  }
3746}
3847
39static void DumpChar(int y, DumpState* D)
40{
41 char x=(char)y;
42 DumpVar(x,D);
48
49#define DumpVar(x,D)      DumpVector(&x,1,D)
50
51
52static void DumpByte (int y, DumpState *D) {
53  lu_byte x = (lu_byte)y;
54  DumpVar(x, D);
4355}
4456
45static void DumpInt(int x, DumpState* D)
46{
47 DumpVar(x,D);
57
58static void DumpInt (int x, DumpState *D) {
59  DumpVar(x, D);
4860}
4961
50static void DumpNumber(lua_Number x, DumpState* D)
51{
52 DumpVar(x,D);
62
63static void DumpNumber (lua_Number x, DumpState *D) {
64  DumpVar(x, D);
5365}
5466
55static void DumpVector(const void* b, int n, size_t size, DumpState* D)
56{
57 DumpInt(n,D);
58 DumpMem(b,n,size,D);
67
68static void DumpInteger (lua_Integer x, DumpState *D) {
69  DumpVar(x, D);
5970}
6071
61static void DumpString(const TString* s, DumpState* D)
62{
63 if (s==NULL)
64 {
65  size_t size=0;
66  DumpVar(size,D);
67 }
68 else
69 {
70  size_t size=s->tsv.len+1;      /* include trailing '\0' */
71  DumpVar(size,D);
72  DumpBlock(getstr(s),size*sizeof(char),D);
73 }
72
73static void DumpString (const TString *s, DumpState *D) {
74  if (s == NULL)
75    DumpByte(0, D);
76  else {
77    size_t size = s->len + 1;  /* include trailing '\0' */
78    if (size < 0xFF)
79      DumpByte(cast_int(size), D);
80    else {
81      DumpByte(0xFF, D);
82      DumpVar(size, D);
83    }
84    DumpVector(getstr(s), size - 1, D);  /* no need to save '\0' */
85  }
7486}
7587
76#define DumpCode(f,D)    DumpVector(f->code,f->sizecode,sizeof(Instruction),D)
7788
78static void DumpFunction(const Proto* f, DumpState* D);
89static void DumpCode (const Proto *f, DumpState *D) {
90  DumpInt(f->sizecode, D);
91  DumpVector(f->code, f->sizecode, D);
92}
7993
80static void DumpConstants(const Proto* f, DumpState* D)
81{
82 int i,n=f->sizek;
83 DumpInt(n,D);
84 for (i=0; i<n; i++)
85 {
86  const TValue* o=&f->k[i];
87  DumpChar(ttypenv(o),D);
88  switch (ttypenv(o))
89  {
90   case LUA_TNIL:
91   break;
92   case LUA_TBOOLEAN:
93   DumpChar(bvalue(o),D);
94   break;
95   case LUA_TNUMBER:
96   DumpNumber(nvalue(o),D);
97   break;
98   case LUA_TSTRING:
99   DumpString(rawtsvalue(o),D);
100   break;
101    default: lua_assert(0);
94
95static void DumpFunction(const Proto *f, TString *psource, DumpState *D);
96
97static void DumpConstants (const Proto *f, DumpState *D) {
98  int i;
99  int n = f->sizek;
100  DumpInt(n, D);
101  for (i = 0; i < n; i++) {
102    const TValue *o = &f->k[i];
103    DumpByte(ttype(o), D);
104    switch (ttype(o)) {
105    case LUA_TNIL:
106      break;
107    case LUA_TBOOLEAN:
108      DumpByte(bvalue(o), D);
109      break;
110    case LUA_TNUMFLT:
111      DumpNumber(fltvalue(o), D);
112      break;
113    case LUA_TNUMINT:
114      DumpInteger(ivalue(o), D);
115      break;
116    case LUA_TSHRSTR:
117    case LUA_TLNGSTR:
118      DumpString(tsvalue(o), D);
119      break;
120    default:
121      lua_assert(0);
122    }
102123  }
103 }
104 n=f->sizep;
105 DumpInt(n,D);
106 for (i=0; i<n; i++) DumpFunction(f->p[i],D);
107124}
108125
109static void DumpUpvalues(const Proto* f, DumpState* D)
110{
111 int i,n=f->sizeupvalues;
112 DumpInt(n,D);
113 for (i=0; i<n; i++)
114 {
115  DumpChar(f->upvalues[i].instack,D);
116  DumpChar(f->upvalues[i].idx,D);
117 }
126
127static void DumpProtos (const Proto *f, DumpState *D) {
128  int i;
129  int n = f->sizep;
130  DumpInt(n, D);
131  for (i = 0; i < n; i++)
132    DumpFunction(f->p[i], f->source, D);
118133}
119134
120static void DumpDebug(const Proto* f, DumpState* D)
121{
122 int i,n;
123 DumpString((D->strip) ? NULL : f->source,D);
124 n= (D->strip) ? 0 : f->sizelineinfo;
125 DumpVector(f->lineinfo,n,sizeof(int),D);
126 n= (D->strip) ? 0 : f->sizelocvars;
127 DumpInt(n,D);
128 for (i=0; i<n; i++)
129 {
130  DumpString(f->locvars[i].varname,D);
131  DumpInt(f->locvars[i].startpc,D);
132  DumpInt(f->locvars[i].endpc,D);
133 }
134 n= (D->strip) ? 0 : f->sizeupvalues;
135 DumpInt(n,D);
136 for (i=0; i<n; i++) DumpString(f->upvalues[i].name,D);
135
136static void DumpUpvalues (const Proto *f, DumpState *D) {
137  int i, n = f->sizeupvalues;
138  DumpInt(n, D);
139  for (i = 0; i < n; i++) {
140    DumpByte(f->upvalues[i].instack, D);
141    DumpByte(f->upvalues[i].idx, D);
142  }
137143}
138144
139static void DumpFunction(const Proto* f, DumpState* D)
140{
141 DumpInt(f->linedefined,D);
142 DumpInt(f->lastlinedefined,D);
143 DumpChar(f->numparams,D);
144 DumpChar(f->is_vararg,D);
145 DumpChar(f->maxstacksize,D);
146 DumpCode(f,D);
147 DumpConstants(f,D);
148 DumpUpvalues(f,D);
149 DumpDebug(f,D);
145
146static void DumpDebug (const Proto *f, DumpState *D) {
147  int i, n;
148  n = (D->strip) ? 0 : f->sizelineinfo;
149  DumpInt(n, D);
150  DumpVector(f->lineinfo, n, D);
151  n = (D->strip) ? 0 : f->sizelocvars;
152  DumpInt(n, D);
153  for (i = 0; i < n; i++) {
154    DumpString(f->locvars[i].varname, D);
155    DumpInt(f->locvars[i].startpc, D);
156    DumpInt(f->locvars[i].endpc, D);
157  }
158  n = (D->strip) ? 0 : f->sizeupvalues;
159  DumpInt(n, D);
160  for (i = 0; i < n; i++)
161    DumpString(f->upvalues[i].name, D);
150162}
151163
152static void DumpHeader(DumpState* D)
153{
154 lu_byte h[LUAC_HEADERSIZE];
155 luaU_header(h);
156 DumpBlock(h,LUAC_HEADERSIZE,D);
164
165static void DumpFunction (const Proto *f, TString *psource, DumpState *D) {
166  if (D->strip || f->source == psource)
167    DumpString(NULL, D);  /* no debug info or same source as its parent */
168  else
169    DumpString(f->source, D);
170  DumpInt(f->linedefined, D);
171  DumpInt(f->lastlinedefined, D);
172  DumpByte(f->numparams, D);
173  DumpByte(f->is_vararg, D);
174  DumpByte(f->maxstacksize, D);
175  DumpCode(f, D);
176  DumpConstants(f, D);
177  DumpUpvalues(f, D);
178  DumpProtos(f, D);
179  DumpDebug(f, D);
157180}
158181
182
183static void DumpHeader (DumpState *D) {
184  DumpLiteral(LUA_SIGNATURE, D);
185  DumpByte(LUAC_VERSION, D);
186  DumpByte(LUAC_FORMAT, D);
187  DumpLiteral(LUAC_DATA, D);
188  DumpByte(sizeof(int), D);
189  DumpByte(sizeof(size_t), D);
190  DumpByte(sizeof(Instruction), D);
191  DumpByte(sizeof(lua_Integer), D);
192  DumpByte(sizeof(lua_Number), D);
193  DumpInteger(LUAC_INT, D);
194  DumpNumber(LUAC_NUM, D);
195}
196
197
159198/*
160199** dump Lua function as precompiled chunk
161200*/
162int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip)
163{
164 DumpState D;
165 D.L=L;
166 D.writer=w;
167 D.data=data;
168 D.strip=strip;
169 D.status=0;
170 DumpHeader(&D);
171 DumpFunction(f,&D);
172 return D.status;
201int luaU_dump(lua_State *L, const Proto *f, lua_Writer w, void *data,
202              int strip) {
203  DumpState D;
204  D.L = L;
205  D.writer = w;
206  D.data = data;
207  D.strip = strip;
208  D.status = 0;
209  DumpHeader(&D);
210  DumpByte(f->sizeupvalues, &D);
211  DumpFunction(f, NULL, &D);
212  return D.status;
173213}
214
trunk/3rdparty/lua/src/lfunc.c
r242885r242886
11/*
2** $Id: lfunc.c,v 2.30.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lfunc.c,v 2.45 2014/11/02 19:19:04 roberto Exp $
33** Auxiliary functions to manipulate prototypes and closures
44** See Copyright Notice in lua.h
55*/
66
7
8#include <stddef.h>
9
107#define lfunc_c
118#define LUA_CORE
129
10#include "lprefix.h"
11
12
13#include <stddef.h>
14
1315#include "lua.h"
1416
1517#include "lfunc.h"
r242885r242886
2022
2123
2224
23Closure *luaF_newCclosure (lua_State *L, int n) {
24  Closure *c = &luaC_newobj(L, LUA_TCCL, sizeCclosure(n), NULL, 0)->cl;
25  c->c.nupvalues = cast_byte(n);
25CClosure *luaF_newCclosure (lua_State *L, int n) {
26  GCObject *o = luaC_newobj(L, LUA_TCCL, sizeCclosure(n));
27  CClosure *c = gco2ccl(o);
28  c->nupvalues = cast_byte(n);
2629  return c;
2730}
2831
2932
30Closure *luaF_newLclosure (lua_State *L, int n) {
31  Closure *c = &luaC_newobj(L, LUA_TLCL, sizeLclosure(n), NULL, 0)->cl;
32  c->l.p = NULL;
33  c->l.nupvalues = cast_byte(n);
34  while (n--) c->l.upvals[n] = NULL;
33LClosure *luaF_newLclosure (lua_State *L, int n) {
34  GCObject *o = luaC_newobj(L, LUA_TLCL, sizeLclosure(n));
35  LClosure *c = gco2lcl(o);
36  c->p = NULL;
37  c->nupvalues = cast_byte(n);
38  while (n--) c->upvals[n] = NULL;
3539  return c;
3640}
3741
38
39UpVal *luaF_newupval (lua_State *L) {
40  UpVal *uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), NULL, 0)->uv;
41  uv->v = &uv->u.value;
42  setnilvalue(uv->v);
43  return uv;
42/*
43** fill a closure with new closed upvalues
44*/
45void luaF_initupvals (lua_State *L, LClosure *cl) {
46  int i;
47  for (i = 0; i < cl->nupvalues; i++) {
48    UpVal *uv = luaM_new(L, UpVal);
49    uv->refcount = 1;
50    uv->v = &uv->u.value;  /* make it closed */
51    setnilvalue(uv->v);
52    cl->upvals[i] = uv;
53  }
4454}
4555
4656
4757UpVal *luaF_findupval (lua_State *L, StkId level) {
48  global_State *g = G(L);
49  GCObject **pp = &L->openupval;
58  UpVal **pp = &L->openupval;
5059  UpVal *p;
5160  UpVal *uv;
52  while (*pp != NULL && (p = gco2uv(*pp))->v >= level) {
53    GCObject *o = obj2gco(p);
54    lua_assert(p->v != &p->u.value);
55    lua_assert(!isold(o) || isold(obj2gco(L)));
56    if (p->v == level) {  /* found a corresponding upvalue? */
57      if (isdead(g, o))  /* is it dead? */
58        changewhite(o);  /* resurrect it */
59      return p;
60    }
61    pp = &p->next;
61  lua_assert(isintwups(L) || L->openupval == NULL);
62  while (*pp != NULL && (p = *pp)->v >= level) {
63    lua_assert(upisopen(p));
64    if (p->v == level)  /* found a corresponding upvalue? */
65      return p;  /* return it */
66    pp = &p->u.open.next;
6267  }
63  /* not found: create a new one */
64  uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), pp, 0)->uv;
68  /* not found: create a new upvalue */
69  uv = luaM_new(L, UpVal);
70  uv->refcount = 0;
71  uv->u.open.next = *pp;  /* link it to list of open upvalues */
72  uv->u.open.touched = 1;
73  *pp = uv;
6574  uv->v = level;  /* current value lives in the stack */
66  uv->u.l.prev = &g->uvhead;  /* double link it in `uvhead' list */
67  uv->u.l.next = g->uvhead.u.l.next;
68  uv->u.l.next->u.l.prev = uv;
69  g->uvhead.u.l.next = uv;
70  lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
75  if (!isintwups(L)) {  /* thread not in list of threads with upvalues? */
76    L->twups = G(L)->twups;  /* link it to the list */
77    G(L)->twups = L;
78  }
7179  return uv;
7280}
7381
7482
75static void unlinkupval (UpVal *uv) {
76  lua_assert(uv->u.l.next->u.l.prev == uv && uv->u.l.prev->u.l.next == uv);
77  uv->u.l.next->u.l.prev = uv->u.l.prev;  /* remove from `uvhead' list */
78  uv->u.l.prev->u.l.next = uv->u.l.next;
79}
80
81
82void luaF_freeupval (lua_State *L, UpVal *uv) {
83  if (uv->v != &uv->u.value)  /* is it open? */
84    unlinkupval(uv);  /* remove from open list */
85  luaM_free(L, uv);  /* free upvalue */
86}
87
88
8983void luaF_close (lua_State *L, StkId level) {
9084  UpVal *uv;
91  global_State *g = G(L);
92  while (L->openupval != NULL && (uv = gco2uv(L->openupval))->v >= level) {
93    GCObject *o = obj2gco(uv);
94    lua_assert(!isblack(o) && uv->v != &uv->u.value);
95    L->openupval = uv->next;  /* remove from `open' list */
96    if (isdead(g, o))
97      luaF_freeupval(L, uv);  /* free upvalue */
85  while (L->openupval != NULL && (uv = L->openupval)->v >= level) {
86    lua_assert(upisopen(uv));
87    L->openupval = uv->u.open.next;  /* remove from 'open' list */
88    if (uv->refcount == 0)  /* no references? */
89      luaM_free(L, uv);  /* free upvalue */
9890    else {
99      unlinkupval(uv);  /* remove upvalue from 'uvhead' list */
10091      setobj(L, &uv->u.value, uv->v);  /* move value to upvalue slot */
10192      uv->v = &uv->u.value;  /* now current value lives here */
102      gch(o)->next = g->allgc;  /* link upvalue into 'allgc' list */
103      g->allgc = o;
104      luaC_checkupvalcolor(g, uv);
93      luaC_upvalbarrier(L, uv);
10594    }
10695  }
10796}
10897
10998
11099Proto *luaF_newproto (lua_State *L) {
111  Proto *f = &luaC_newobj(L, LUA_TPROTO, sizeof(Proto), NULL, 0)->p;
100  GCObject *o = luaC_newobj(L, LUA_TPROTO, sizeof(Proto));
101  Proto *f = gco2p(o);
112102  f->k = NULL;
113103  f->sizek = 0;
114104  f->p = NULL;
r242885r242886
144134
145135
146136/*
147** Look for n-th local variable at line `line' in function `func'.
137** Look for n-th local variable at line 'line' in function 'func'.
148138** Returns NULL if not found.
149139*/
150140const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
trunk/3rdparty/lua/src/lfunc.h
r242885r242886
11/*
2** $Id: lfunc.h,v 2.8.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lfunc.h,v 2.14 2014/06/19 18:27:20 roberto Exp $
33** Auxiliary functions to manipulate prototypes and closures
44** See Copyright Notice in lua.h
55*/
r242885r242886
1818                         cast(int, sizeof(TValue *)*((n)-1)))
1919
2020
21/* test whether thread is in 'twups' list */
22#define isintwups(L)   (L->twups != L)
23
24
25/*
26** Upvalues for Lua closures
27*/
28struct UpVal {
29  TValue *v;  /* points to stack or to its own value */
30  lu_mem refcount;  /* reference counter */
31  union {
32    struct {  /* (when open) */
33      UpVal *next;  /* linked list */
34      int touched;  /* mark to avoid cycles with dead threads */
35    } open;
36    TValue value;  /* the value (when closed) */
37  } u;
38};
39
40#define upisopen(up)   ((up)->v != &(up)->u.value)
41
42
2143LUAI_FUNC Proto *luaF_newproto (lua_State *L);
22LUAI_FUNC Closure *luaF_newCclosure (lua_State *L, int nelems);
23LUAI_FUNC Closure *luaF_newLclosure (lua_State *L, int nelems);
24LUAI_FUNC UpVal *luaF_newupval (lua_State *L);
44LUAI_FUNC CClosure *luaF_newCclosure (lua_State *L, int nelems);
45LUAI_FUNC LClosure *luaF_newLclosure (lua_State *L, int nelems);
46LUAI_FUNC void luaF_initupvals (lua_State *L, LClosure *cl);
2547LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
2648LUAI_FUNC void luaF_close (lua_State *L, StkId level);
2749LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
28LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv);
2950LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
3051                                         int pc);
3152
trunk/3rdparty/lua/src/lgc.c
r242885r242886
11/*
2** $Id: lgc.c,v 2.140.1.2 2013/04/26 18:22:05 roberto Exp $
2** $Id: lgc.c,v 2.201 2014/12/20 13:58:15 roberto Exp $
33** Garbage Collector
44** See Copyright Notice in lua.h
55*/
66
7#include <string.h>
8
97#define lgc_c
108#define LUA_CORE
119
10#include "lprefix.h"
11
12
13#include <string.h>
14
1215#include "lua.h"
1316
1417#include "ldebug.h"
r242885r242886
2326#include "ltm.h"
2427
2528
29/*
30** internal state for collector while inside the atomic phase. The
31** collector should never be in this state while running regular code.
32*/
33#define GCSinsideatomic      (GCSpause + 1)
2634
2735/*
2836** cost of sweeping one element (the size of a small object divided
r242885r242886
3341/* maximum number of elements to sweep in each single step */
3442#define GCSWEEPMAX   (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
3543
36/* maximum number of finalizers to call in each GC step */
37#define GCFINALIZENUM   4
44/* cost of calling one finalizer */
45#define GCFINALIZECOST   GCSWEEPCOST
3846
3947
4048/*
r242885r242886
5260
5361
5462/*
55** 'makewhite' erases all color bits plus the old bit and then
56** sets only the current white bit
63** 'makewhite' erases all color bits then sets only the current white
64** bit
5765*/
58#define maskcolors   (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS))
66#define maskcolors   (~(bitmask(BLACKBIT) | WHITEBITS))
5967#define makewhite(g,x)   \
60 (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g)))
68 (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
6169
62#define white2gray(x)   resetbits(gch(x)->marked, WHITEBITS)
63#define black2gray(x)   resetbit(gch(x)->marked, BLACKBIT)
70#define white2gray(x)   resetbits(x->marked, WHITEBITS)
71#define black2gray(x)   resetbit(x->marked, BLACKBIT)
6472
6573
66#define isfinalized(x)      testbit(gch(x)->marked, FINALIZEDBIT)
74#define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x)))
6775
6876#define checkdeadkey(n)   lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
6977
r242885r242886
7583#define markvalue(g,o) { checkconsistency(o); \
7684  if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
7785
78#define markobject(g,t) { if ((t) && iswhite(obj2gco(t))) \
79      reallymarkobject(g, obj2gco(t)); }
86#define markobject(g,t) \
87  { if ((t) && iswhite(t)) reallymarkobject(g, obj2gco(t)); }
8088
8189static void reallymarkobject (global_State *g, GCObject *o);
8290
r242885r242886
95103
96104
97105/*
98** link table 'h' into list pointed by 'p'
106** link collectable object 'o' into list pointed by 'p'
99107*/
100#define linktable(h,p)   ((h)->gclist = *(p), *(p) = obj2gco(h))
108#define linkgclist(o,p)   ((o)->gclist = (p), (p) = obj2gco(o))
101109
102110
103111/*
r242885r242886
107115static void removeentry (Node *n) {
108116  lua_assert(ttisnil(gval(n)));
109117  if (valiswhite(gkey(n)))
110    setdeadvalue(gkey(n));  /* unused and unmarked key; remove it */
118    setdeadvalue(wgkey(n));  /* unused and unmarked key; remove it */
111119}
112120
113121
114122/*
115123** tells whether a key or value can be cleared from a weak
116124** table. Non-collectable objects are never removed from weak
117** tables. Strings behave as `values', so are never removed too. for
125** tables. Strings behave as 'values', so are never removed too. for
118126** other objects: if really collected, cannot keep them; for objects
119127** being finalized, keep them in keys, but not in values
120128*/
121129static int iscleared (global_State *g, const TValue *o) {
122130  if (!iscollectable(o)) return 0;
123131  else if (ttisstring(o)) {
124    markobject(g, rawtsvalue(o));  /* strings are `values', so are never weak */
132    markobject(g, tsvalue(o));  /* strings are 'values', so are never weak */
125133    return 0;
126134  }
127135  else return iswhite(gcvalue(o));
r242885r242886
130138
131139/*
132140** barrier that moves collector forward, that is, mark the white object
133** being pointed by a black object.
141** being pointed by a black object. (If in sweep phase, clear the black
142** object to white [sweep it] to avoid other barrier calls for this
143** same object.)
134144*/
135145void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
136146  global_State *g = G(L);
137147  lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
138  lua_assert(g->gcstate != GCSpause);
139  lua_assert(gch(o)->tt != LUA_TTABLE);
140  if (keepinvariantout(g))  /* must keep invariant? */
148  if (keepinvariant(g))  /* must keep invariant? */
141149    reallymarkobject(g, v);  /* restore invariant */
142150  else {  /* sweep phase */
143151    lua_assert(issweepphase(g));
r242885r242886
148156
149157/*
150158** barrier that moves collector backward, that is, mark the black object
151** pointing to a white object as gray again. (Current implementation
152** only works for tables; access to 'gclist' is not uniform across
153** different types.)
159** pointing to a white object as gray again.
154160*/
155void luaC_barrierback_ (lua_State *L, GCObject *o) {
161void luaC_barrierback_ (lua_State *L, Table *t) {
156162  global_State *g = G(L);
157  lua_assert(isblack(o) && !isdead(g, o) && gch(o)->tt == LUA_TTABLE);
158  black2gray(o);  /* make object gray (again) */
159  gco2t(o)->gclist = g->grayagain;
160  g->grayagain = o;
163  lua_assert(isblack(t) && !isdead(g, t));
164  black2gray(t);  /* make table gray (again) */
165  linkgclist(t, g->grayagain);
161166}
162167
163168
164169/*
165** barrier for prototypes. When creating first closure (cache is
166** NULL), use a forward barrier; this may be the only closure of the
167** prototype (if it is a "regular" function, with a single instance)
168** and the prototype may be big, so it is better to avoid traversing
169** it again. Otherwise, use a backward barrier, to avoid marking all
170** possible instances.
170** barrier for assignments to closed upvalues. Because upvalues are
171** shared among closures, it is impossible to know the color of all
172** closures pointing to it. So, we assume that the object being assigned
173** must be marked.
171174*/
172LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c) {
175void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
173176  global_State *g = G(L);
174  lua_assert(isblack(obj2gco(p)));
175  if (p->cache == NULL) {  /* first time? */
176    luaC_objbarrier(L, p, c);
177  }
178  else {  /* use a backward barrier */
179    black2gray(obj2gco(p));  /* make prototype gray (again) */
180    p->gclist = g->grayagain;
181    g->grayagain = obj2gco(p);
182  }
177  GCObject *o = gcvalue(uv->v);
178  lua_assert(!upisopen(uv));  /* ensured by macro luaC_upvalbarrier */
179  if (keepinvariant(g))
180    markobject(g, o);
183181}
184182
185183
186/*
187** check color (and invariants) for an upvalue that was closed,
188** i.e., moved into the 'allgc' list
189*/
190void luaC_checkupvalcolor (global_State *g, UpVal *uv) {
191  GCObject *o = obj2gco(uv);
192  lua_assert(!isblack(o));  /* open upvalues are never black */
193  if (isgray(o)) {
194    if (keepinvariant(g)) {
195      resetoldbit(o);  /* see MOVE OLD rule */
196      gray2black(o);  /* it is being visited now */
197      markvalue(g, uv->v);
198    }
199    else {
200      lua_assert(issweepphase(g));
201      makewhite(g, o);
202    }
203  }
184void luaC_fix (lua_State *L, GCObject *o) {
185  global_State *g = G(L);
186  lua_assert(g->allgc == o);  /* object must be 1st in 'allgc' list! */
187  white2gray(o);  /* they will be gray forever */
188  g->allgc = o->next;  /* remove object from 'allgc' list */
189  o->next = g->fixedgc;  /* link it to 'fixedgc' list */
190  g->fixedgc = o;
204191}
205192
206193
207194/*
208195** create a new collectable object (with given type and size) and link
209** it to '*list'. 'offset' tells how many bytes to allocate before the
210** object itself (used only by states).
196** it to 'allgc' list.
211197*/
212GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list,
213                       int offset) {
198GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
214199  global_State *g = G(L);
215  char *raw = cast(char *, luaM_newobject(L, novariant(tt), sz));
216  GCObject *o = obj2gco(raw + offset);
217  if (list == NULL)
218    list = &g->allgc;  /* standard list for collectable objects */
219  gch(o)->marked = luaC_white(g);
220  gch(o)->tt = tt;
221  gch(o)->next = *list;
222  *list = o;
200  GCObject *o = cast(GCObject *, luaM_newobject(L, novariant(tt), sz));
201  o->marked = luaC_white(g);
202  o->tt = tt;
203  o->next = g->allgc;
204  g->allgc = o;
223205  return o;
224206}
225207
r242885r242886
241223** upvalues are already linked in 'headuv' list.)
242224*/
243225static void reallymarkobject (global_State *g, GCObject *o) {
244  lu_mem size;
226 reentry:
245227  white2gray(o);
246  switch (gch(o)->tt) {
228  switch (o->tt) {
247229    case LUA_TSHRSTR:
248230    case LUA_TLNGSTR: {
249      size = sizestring(gco2ts(o));
250      break;  /* nothing else to mark; make it black */
231      gray2black(o);
232      g->GCmemtrav += sizestring(gco2ts(o));
233      break;
251234    }
252235    case LUA_TUSERDATA: {
253      Table *mt = gco2u(o)->metatable;
254      markobject(g, mt);
255      markobject(g, gco2u(o)->env);
256      size = sizeudata(gco2u(o));
236      TValue uvalue;
237      markobject(g, gco2u(o)->metatable);  /* mark its metatable */
238      gray2black(o);
239      g->GCmemtrav += sizeudata(gco2u(o));
240      getuservalue(g->mainthread, gco2u(o), &uvalue);
241      if (valiswhite(&uvalue)) {  /* markvalue(g, &uvalue); */
242        o = gcvalue(&uvalue);
243        goto reentry;
244      }
257245      break;
258246    }
259    case LUA_TUPVAL: {
260      UpVal *uv = gco2uv(o);
261      markvalue(g, uv->v);
262      if (uv->v != &uv->u.value)  /* open? */
263        return;  /* open upvalues remain gray */
264      size = sizeof(UpVal);
247    case LUA_TLCL: {
248      linkgclist(gco2lcl(o), g->gray);
265249      break;
266250    }
267    case LUA_TLCL: {
268      gco2lcl(o)->gclist = g->gray;
269      g->gray = o;
270      return;
271    }
272251    case LUA_TCCL: {
273      gco2ccl(o)->gclist = g->gray;
274      g->gray = o;
275      return;
252      linkgclist(gco2ccl(o), g->gray);
253      break;
276254    }
277255    case LUA_TTABLE: {
278      linktable(gco2t(o), &g->gray);
279      return;
256      linkgclist(gco2t(o), g->gray);
257      break;
280258    }
281259    case LUA_TTHREAD: {
282      gco2th(o)->gclist = g->gray;
283      g->gray = o;
284      return;
260      linkgclist(gco2th(o), g->gray);
261      break;
285262    }
286263    case LUA_TPROTO: {
287      gco2p(o)->gclist = g->gray;
288      g->gray = o;
289      return;
264      linkgclist(gco2p(o), g->gray);
265      break;
290266    }
291    default: lua_assert(0); return;
267    default: lua_assert(0); break;
292268  }
293  gray2black(o);
294  g->GCmemtrav += size;
295269}
296270
297271
r242885r242886
310284*/
311285static void markbeingfnz (global_State *g) {
312286  GCObject *o;
313  for (o = g->tobefnz; o != NULL; o = gch(o)->next) {
314    makewhite(g, o);
315    reallymarkobject(g, o);
316  }
287  for (o = g->tobefnz; o != NULL; o = o->next)
288    markobject(g, o);
317289}
318290
319291
320292/*
321** mark all values stored in marked open upvalues. (See comment in
322** 'lstate.h'.)
293** Mark all values stored in marked open upvalues from non-marked threads.
294** (Values from marked threads were already marked when traversing the
295** thread.) Remove from the list threads that no longer have upvalues and
296** not-marked threads.
323297*/
324298static void remarkupvals (global_State *g) {
325  UpVal *uv;
326  for (uv = g->uvhead.u.l.next; uv != &g->uvhead; uv = uv->u.l.next) {
327    if (isgray(obj2gco(uv)))
328      markvalue(g, uv->v);
299  lua_State *thread;
300  lua_State **p = &g->twups;
301  while ((thread = *p) != NULL) {
302    lua_assert(!isblack(thread));  /* threads are never black */
303    if (isgray(thread) && thread->openupval != NULL)
304      p = &thread->twups;  /* keep marked thread with upvalues in the list */
305    else {  /* thread is not marked or without upvalues */
306      UpVal *uv;
307      *p = thread->twups;  /* remove thread from the list */
308      thread->twups = thread;  /* mark that it is out of list */
309      for (uv = thread->openupval; uv != NULL; uv = uv->u.open.next) {
310        if (uv->u.open.touched) {
311          markvalue(g, uv->v);  /* remark upvalue's value */
312          uv->u.open.touched = 0;
313        }
314      }
315    }
329316  }
330317}
331318
332319
333320/*
334** mark root set and reset all gray lists, to start a new
335** incremental (or full) collection
321** mark root set and reset all gray lists, to start a new collection
336322*/
337323static void restartcollection (global_State *g) {
338324  g->gray = g->grayagain = NULL;
r242885r242886
352338** =======================================================
353339*/
354340
341/*
342** Traverse a table with weak values and link it to proper list. During
343** propagate phase, keep it in 'grayagain' list, to be revisited in the
344** atomic phase. In the atomic phase, if table has any white value,
345** put it in 'weak' list, to be cleared.
346*/
355347static void traverseweakvalue (global_State *g, Table *h) {
356348  Node *n, *limit = gnodelast(h);
357  /* if there is array part, assume it may have white values (do not
358     traverse it just to check) */
349  /* if there is array part, assume it may have white values (it is not
350     worth traversing it now just to check) */
359351  int hasclears = (h->sizearray > 0);
360  for (n = gnode(h, 0); n < limit; n++) {
352  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
361353    checkdeadkey(n);
362354    if (ttisnil(gval(n)))  /* entry is empty? */
363355      removeentry(n);  /* remove it */
r242885r242886
368360        hasclears = 1;  /* table will have to be cleared */
369361    }
370362  }
371  if (hasclears)
372    linktable(h, &g->weak);  /* has to be cleared later */
373  else  /* no white values */
374    linktable(h, &g->grayagain);  /* no need to clean */
363  if (g->gcstate == GCSpropagate)
364    linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */
365  else if (hasclears)
366    linkgclist(h, g->weak);  /* has to be cleared later */
375367}
376368
377369
370/*
371** Traverse an ephemeron table and link it to proper list. Returns true
372** iff any object was marked during this traversal (which implies that
373** convergence has to continue). During propagation phase, keep table
374** in 'grayagain' list, to be visited again in the atomic phase. In
375** the atomic phase, if table has any white->white entry, it has to
376** be revisited during ephemeron convergence (as that key may turn
377** black). Otherwise, if it has any white key, table has to be cleared
378** (in the atomic phase).
379*/
378380static int traverseephemeron (global_State *g, Table *h) {
379381  int marked = 0;  /* true if an object is marked in this traversal */
380382  int hasclears = 0;  /* true if table has white keys */
381  int prop = 0;  /* true if table has entry "white-key -> white-value" */
383  int hasww = 0;  /* true if table has entry "white-key -> white-value" */
382384  Node *n, *limit = gnodelast(h);
383  int i;
384  /* traverse array part (numeric keys are 'strong') */
385  unsigned int i;
386  /* traverse array part */
385387  for (i = 0; i < h->sizearray; i++) {
386388    if (valiswhite(&h->array[i])) {
387389      marked = 1;
r242885r242886
396398    else if (iscleared(g, gkey(n))) {  /* key is not marked (yet)? */
397399      hasclears = 1;  /* table must be cleared */
398400      if (valiswhite(gval(n)))  /* value not marked yet? */
399        prop = 1;  /* must propagate again */
401        hasww = 1;  /* white-white entry */
400402    }
401403    else if (valiswhite(gval(n))) {  /* value not marked yet? */
402404      marked = 1;
403405      reallymarkobject(g, gcvalue(gval(n)));  /* mark it now */
404406    }
405407  }
406  if (prop)
407    linktable(h, &g->ephemeron);  /* have to propagate again */
408  else if (hasclears)  /* does table have white keys? */
409    linktable(h, &g->allweak);  /* may have to clean white keys */
410  else  /* no white keys */
411    linktable(h, &g->grayagain);  /* no need to clean */
408  /* link table into proper list */
409  if (g->gcstate == GCSpropagate)
410    linkgclist(h, g->grayagain);  /* must retraverse it in atomic phase */
411  else if (hasww)  /* table has white->white entries? */
412    linkgclist(h, g->ephemeron);  /* have to propagate again */
413  else if (hasclears)  /* table has white keys? */
414    linkgclist(h, g->allweak);  /* may have to clean white keys */
412415  return marked;
413416}
414417
415418
416419static void traversestrongtable (global_State *g, Table *h) {
417420  Node *n, *limit = gnodelast(h);
418  int i;
421  unsigned int i;
419422  for (i = 0; i < h->sizearray; i++)  /* traverse array part */
420423    markvalue(g, &h->array[i]);
421424  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
r242885r242886
439442      ((weakkey = strchr(svalue(mode), 'k')),
440443       (weakvalue = strchr(svalue(mode), 'v')),
441444       (weakkey || weakvalue))) {  /* is really weak? */
442    black2gray(obj2gco(h));  /* keep table gray */
445    black2gray(h);  /* keep table gray */
443446    if (!weakkey)  /* strong keys? */
444447      traverseweakvalue(g, h);
445448    else if (!weakvalue)  /* strong values? */
446449      traverseephemeron(g, h);
447450    else  /* all weak */
448      linktable(h, &g->allweak);  /* nothing to traverse now */
451      linkgclist(h, g->allweak);  /* nothing to traverse now */
449452  }
450453  else  /* not weak */
451454    traversestrongtable(g, h);
r242885r242886
456459
457460static int traverseproto (global_State *g, Proto *f) {
458461  int i;
459  if (f->cache && iswhite(obj2gco(f->cache)))
462  if (f->cache && iswhite(f->cache))
460463    f->cache = NULL;  /* allow cache to be collected */
461464  markobject(g, f->source);
462465  for (i = 0; i < f->sizek; i++)  /* mark literals */
r242885r242886
483486  return sizeCclosure(cl->nupvalues);
484487}
485488
489/*
490** open upvalues point to values in a thread, so those values should
491** be marked when the thread is traversed except in the atomic phase
492** (because then the value cannot be changed by the thread and the
493** thread may not be traversed again)
494*/
486495static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
487496  int i;
488497  markobject(g, cl->p);  /* mark its prototype */
489  for (i = 0; i < cl->nupvalues; i++)  /* mark its upvalues */
490    markobject(g, cl->upvals[i]);
498  for (i = 0; i < cl->nupvalues; i++) {  /* mark its upvalues */
499    UpVal *uv = cl->upvals[i];
500    if (uv != NULL) {
501      if (upisopen(uv) && g->gcstate != GCSinsideatomic)
502        uv->u.open.touched = 1;  /* can be marked in 'remarkupvals' */
503      else
504        markvalue(g, uv->v);
505    }
506  }
491507  return sizeLclosure(cl->nupvalues);
492508}
493509
494510
495static lu_mem traversestack (global_State *g, lua_State *th) {
496  int n = 0;
511static lu_mem traversethread (global_State *g, lua_State *th) {
497512  StkId o = th->stack;
498513  if (o == NULL)
499514    return 1;  /* stack not completely built yet */
515  lua_assert(g->gcstate == GCSinsideatomic ||
516             th->openupval == NULL || isintwups(th));
500517  for (; o < th->top; o++)  /* mark live elements in the stack */
501518    markvalue(g, o);
502  if (g->gcstate == GCSatomic) {  /* final traversal? */
519  if (g->gcstate == GCSinsideatomic) {  /* final traversal? */
503520    StkId lim = th->stack + th->stacksize;  /* real end of stack */
504521    for (; o < lim; o++)  /* clear not-marked stack slice */
505522      setnilvalue(o);
523    /* 'remarkupvals' may have removed thread from 'twups' list */
524    if (!isintwups(th) && th->openupval != NULL) {
525      th->twups = g->twups;  /* link it back to the list */
526      g->twups = th;
527    }
506528  }
507  else {  /* count call infos to compute size */
508    CallInfo *ci;
509    for (ci = &th->base_ci; ci != th->ci; ci = ci->next)
510      n++;
511  }
512  return sizeof(lua_State) + sizeof(TValue) * th->stacksize +
513         sizeof(CallInfo) * n;
529  else if (g->gckind != KGC_EMERGENCY)
530    luaD_shrinkstack(th); /* do not change stack in emergency cycle */
531  return (sizeof(lua_State) + sizeof(TValue) * th->stacksize);
514532}
515533
516534
r242885r242886
523541  GCObject *o = g->gray;
524542  lua_assert(isgray(o));
525543  gray2black(o);
526  switch (gch(o)->tt) {
544  switch (o->tt) {
527545    case LUA_TTABLE: {
528546      Table *h = gco2t(o);
529547      g->gray = h->gclist;  /* remove from 'gray' list */
r242885r242886
545563    case LUA_TTHREAD: {
546564      lua_State *th = gco2th(o);
547565      g->gray = th->gclist;  /* remove from 'gray' list */
548      th->gclist = g->grayagain;
549      g->grayagain = o;  /* insert into 'grayagain' list */
566      linkgclist(th, g->grayagain);  /* insert into 'grayagain' list */
550567      black2gray(o);
551      size = traversestack(g, th);
568      size = traversethread(g, th);
552569      break;
553570    }
554571    case LUA_TPROTO: {
r242885r242886
568585}
569586
570587
571static void propagatelist (global_State *g, GCObject *l) {
572  lua_assert(g->gray == NULL);  /* no grays left */
573  g->gray = l;
574  propagateall(g);  /* traverse all elements from 'l' */
575}
576
577/*
578** retraverse all gray lists. Because tables may be reinserted in other
579** lists when traversed, traverse the original lists to avoid traversing
580** twice the same table (which is not wrong, but inefficient)
581*/
582static void retraversegrays (global_State *g) {
583  GCObject *weak = g->weak;  /* save original lists */
584  GCObject *grayagain = g->grayagain;
585  GCObject *ephemeron = g->ephemeron;
586  g->weak = g->grayagain = g->ephemeron = NULL;
587  propagateall(g);  /* traverse main gray list */
588  propagatelist(g, grayagain);
589  propagatelist(g, weak);
590  propagatelist(g, ephemeron);
591}
592
593
594588static void convergeephemerons (global_State *g) {
595589  int changed;
596590  do {
597591    GCObject *w;
598592    GCObject *next = g->ephemeron;  /* get ephemeron list */
599    g->ephemeron = NULL;  /* tables will return to this list when traversed */
593    g->ephemeron = NULL;  /* tables may return to this list when traversed */
600594    changed = 0;
601595    while ((w = next) != NULL) {
602596      next = gco2t(w)->gclist;
r242885r242886
644638  for (; l != f; l = gco2t(l)->gclist) {
645639    Table *h = gco2t(l);
646640    Node *n, *limit = gnodelast(h);
647    int i;
641    unsigned int i;
648642    for (i = 0; i < h->sizearray; i++) {
649643      TValue *o = &h->array[i];
650644      if (iscleared(g, o))  /* value was collected? */
r242885r242886
660654}
661655
662656
657void luaC_upvdeccount (lua_State *L, UpVal *uv) {
658  lua_assert(uv->refcount > 0);
659  uv->refcount--;
660  if (uv->refcount == 0 && !upisopen(uv))
661    luaM_free(L, uv);
662}
663
664
665static void freeLclosure (lua_State *L, LClosure *cl) {
666  int i;
667  for (i = 0; i < cl->nupvalues; i++) {
668    UpVal *uv = cl->upvals[i];
669    if (uv)
670      luaC_upvdeccount(L, uv);
671  }
672  luaM_freemem(L, cl, sizeLclosure(cl->nupvalues));
673}
674
675
663676static void freeobj (lua_State *L, GCObject *o) {
664  switch (gch(o)->tt) {
677  switch (o->tt) {
665678    case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
666679    case LUA_TLCL: {
667      luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues));
680      freeLclosure(L, gco2lcl(o));
668681      break;
669682    }
670683    case LUA_TCCL: {
671684      luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
672685      break;
673686    }
674    case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;
675687    case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
676688    case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
677689    case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
678690    case LUA_TSHRSTR:
679      G(L)->strt.nuse--;
691      luaS_remove(L, gco2ts(o));  /* remove it from hash table */
680692      /* go through */
681693    case LUA_TLNGSTR: {
682694      luaM_freemem(L, o, sizestring(gco2ts(o)));
r242885r242886
692704
693705
694706/*
695** sweep the (open) upvalues of a thread and resize its stack and
696** list of call-info structures.
697*/
698static void sweepthread (lua_State *L, lua_State *L1) {
699  if (L1->stack == NULL) return;  /* stack not completely built yet */
700  sweepwholelist(L, &L1->openupval);  /* sweep open upvalues */
701  luaE_freeCI(L1);  /* free extra CallInfo slots */
702  /* should not change the stack during an emergency gc cycle */
703  if (G(L)->gckind != KGC_EMERGENCY)
704    luaD_shrinkstack(L1);
705}
706
707
708/*
709707** sweep at most 'count' elements from a list of GCObjects erasing dead
710** objects, where a dead (not alive) object is one marked with the "old"
711** (non current) white and not fixed.
712** In non-generational mode, change all non-dead objects back to white,
713** preparing for next collection cycle.
714** In generational mode, keep black objects black, and also mark them as
715** old; stop when hitting an old object, as all objects after that
716** one will be old too.
717** When object is a thread, sweep its list of open upvalues too.
708** objects, where a dead object is one marked with the old (non current)
709** white; change all non-dead objects back to white, preparing for next
710** collection cycle. Return where to continue the traversal or NULL if
711** list is finished.
718712*/
719713static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
720714  global_State *g = G(L);
721715  int ow = otherwhite(g);
722  int toclear, toset;  /* bits to clear and to set in all live objects */
723  int tostop;  /* stop sweep when this is true */
724  if (isgenerational(g)) {  /* generational mode? */
725    toclear = ~0;  /* clear nothing */
726    toset = bitmask(OLDBIT);  /* set the old bit of all surviving objects */
727    tostop = bitmask(OLDBIT);  /* do not sweep old generation */
728  }
729  else {  /* normal mode */
730    toclear = maskcolors;  /* clear all color bits + old bit */
731    toset = luaC_white(g);  /* make object white */
732    tostop = 0;  /* do not stop */
733  }
716  int white = luaC_white(g);  /* current white */
734717  while (*p != NULL && count-- > 0) {
735718    GCObject *curr = *p;
736    int marked = gch(curr)->marked;
719    int marked = curr->marked;
737720    if (isdeadm(ow, marked)) {  /* is 'curr' dead? */
738      *p = gch(curr)->next;  /* remove 'curr' from list */
721      *p = curr->next;  /* remove 'curr' from list */
739722      freeobj(L, curr);  /* erase 'curr' */
740723    }
741    else {
742      if (testbits(marked, tostop))
743        return NULL;  /* stop sweeping this list */
744      if (gch(curr)->tt == LUA_TTHREAD)
745        sweepthread(L, gco2th(curr));  /* sweep thread's upvalues */
746      /* update marks */
747      gch(curr)->marked = cast_byte((marked & toclear) | toset);
748      p = &gch(curr)->next;  /* go to next element */
724    else {  /* change mark to 'white' */
725      curr->marked = cast_byte((marked & maskcolors) | white);
726      p = &curr->next;  /* go to next element */
749727    }
750728  }
751729  return (*p == NULL) ? NULL : p;
r242885r242886
756734** sweep a list until a live object (or end of list)
757735*/
758736static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) {
759  GCObject ** old = p;
737  GCObject **old = p;
760738  int i = 0;
761739  do {
762740    i++;
r242885r242886
775753** =======================================================
776754*/
777755
778static void checkSizes (lua_State *L) {
779  global_State *g = G(L);
780  if (g->gckind != KGC_EMERGENCY) {  /* do not change sizes in emergency */
781    int hs = g->strt.size / 2;  /* half the size of the string table */
782    if (g->strt.nuse < cast(lu_int32, hs))  /* using less than that half? */
783      luaS_resize(L, hs);  /* halve its size */
756/*
757** If possible, free concatenation buffer and shrink string table
758*/
759static void checkSizes (lua_State *L, global_State *g) {
760  if (g->gckind != KGC_EMERGENCY) {
761    l_mem olddebt = g->GCdebt;
784762    luaZ_freebuffer(L, &g->buff);  /* free concatenation buffer */
763    if (g->strt.nuse < g->strt.size / 4)  /* string table too big? */
764      luaS_resize(L, g->strt.size / 2);  /* shrink it a little */
765    g->GCestimate += g->GCdebt - olddebt;  /* update estimate */
785766  }
786767}
787768
788769
789770static GCObject *udata2finalize (global_State *g) {
790771  GCObject *o = g->tobefnz;  /* get first element */
791  lua_assert(isfinalized(o));
792  g->tobefnz = gch(o)->next;  /* remove it from 'tobefnz' list */
793  gch(o)->next = g->allgc;  /* return it to 'allgc' list */
772  lua_assert(tofinalize(o));
773  g->tobefnz = o->next;  /* remove it from 'tobefnz' list */
774  o->next = g->allgc;  /* return it to 'allgc' list */
794775  g->allgc = o;
795  resetbit(gch(o)->marked, SEPARATED);  /* mark that it is not in 'tobefnz' */
796  lua_assert(!isold(o));  /* see MOVE OLD rule */
797  if (!keepinvariantout(g))  /* not keeping invariant? */
776  resetbit(o->marked, FINALIZEDBIT);  /* object is "normal" again */
777  if (issweepphase(g))
798778    makewhite(g, o);  /* "sweep" object */
799779  return o;
800780}
r242885r242886
839819
840820
841821/*
822** call a few (up to 'g->gcfinnum') finalizers
823*/
824static int runafewfinalizers (lua_State *L) {
825  global_State *g = G(L);
826  unsigned int i;
827  lua_assert(!g->tobefnz || g->gcfinnum > 0);
828  for (i = 0; g->tobefnz && i < g->gcfinnum; i++)
829    GCTM(L, 1);  /* call one finalizer */
830  g->gcfinnum = (!g->tobefnz) ? 0  /* nothing more to finalize? */
831                    : g->gcfinnum * 2;  /* else call a few more next time */
832  return i;
833}
834
835
836/*
837** call all pending finalizers
838*/
839static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
840  global_State *g = G(L);
841  while (g->tobefnz)
842    GCTM(L, propagateerrors);
843}
844
845
846/*
847** find last 'next' field in list 'p' list (to add elements in its end)
848*/
849static GCObject **findlast (GCObject **p) {
850  while (*p != NULL)
851    p = &(*p)->next;
852  return p;
853}
854
855
856/*
842857** move all unreachable objects (or 'all' objects) that need
843858** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
844859*/
845static void separatetobefnz (lua_State *L, int all) {
846  global_State *g = G(L);
847  GCObject **p = &g->finobj;
860static void separatetobefnz (global_State *g, int all) {
848861  GCObject *curr;
849  GCObject **lastnext = &g->tobefnz;
850  /* find last 'next' field in 'tobefnz' list (to add elements in its end) */
851  while (*lastnext != NULL)
852    lastnext = &gch(*lastnext)->next;
862  GCObject **p = &g->finobj;
863  GCObject **lastnext = findlast(&g->tobefnz);
853864  while ((curr = *p) != NULL) {  /* traverse all finalizable objects */
854    lua_assert(!isfinalized(curr));
855    lua_assert(testbit(gch(curr)->marked, SEPARATED));
865    lua_assert(tofinalize(curr));
856866    if (!(iswhite(curr) || all))  /* not being collected? */
857      p = &gch(curr)->next;  /* don't bother with it */
867      p = &curr->next;  /* don't bother with it */
858868    else {
859      l_setbit(gch(curr)->marked, FINALIZEDBIT); /* won't be finalized again */
860      *p = gch(curr)->next;  /* remove 'curr' from 'finobj' list */
861      gch(curr)->next = *lastnext;  /* link at the end of 'tobefnz' list */
869      *p = curr->next;  /* remove 'curr' from 'finobj' list */
870      curr->next = *lastnext;  /* link at the end of 'tobefnz' list */
862871      *lastnext = curr;
863      lastnext = &gch(curr)->next;
872      lastnext = &curr->next;
864873    }
865874  }
866875}
r242885r242886
872881*/
873882void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
874883  global_State *g = G(L);
875  if (testbit(gch(o)->marked, SEPARATED) || /* obj. is already separated... */
876      isfinalized(o) ||                           /* ... or is finalized... */
877      gfasttm(g, mt, TM_GC) == NULL)                /* or has no finalizer? */
884  if (tofinalize(o) ||                 /* obj. is already marked... */
885      gfasttm(g, mt, TM_GC) == NULL)   /* or has no finalizer? */
878886    return;  /* nothing to be done */
879887  else {  /* move 'o' to 'finobj' list */
880888    GCObject **p;
881    GCheader *ho = gch(o);
882    if (g->sweepgc == &ho->next) {  /* avoid removing current sweep object */
883      lua_assert(issweepphase(g));
884      g->sweepgc = sweeptolive(L, g->sweepgc, NULL);
889    if (issweepphase(g)) {
890      makewhite(g, o);  /* "sweep" object 'o' */
891      if (g->sweepgc == &o->next)  /* should not remove 'sweepgc' object */
892        g->sweepgc = sweeptolive(L, g->sweepgc, NULL);  /* change 'sweepgc' */
885893    }
886894    /* search for pointer pointing to 'o' */
887    for (p = &g->allgc; *p != o; p = &gch(*p)->next) { /* empty */ }
888    *p = ho->next;  /* remove 'o' from root list */
889    ho->next = g->finobj;  /* link it in list 'finobj' */
895    for (p = &g->allgc; *p != o; p = &(*p)->next) { /* empty */ }
896    *p = o->next;  /* remove 'o' from 'allgc' list */
897    o->next = g->finobj;  /* link it in 'finobj' list */
890898    g->finobj = o;
891    l_setbit(ho->marked, SEPARATED);  /* mark it as such */
892    if (!keepinvariantout(g))  /* not keeping invariant? */
893      makewhite(g, o);  /* "sweep" object */
894    else
895      resetoldbit(o);  /* see MOVE OLD rule */
899    l_setbit(o->marked, FINALIZEDBIT);  /* mark it as such */
896900  }
897901}
898902
899903/* }====================================================== */
900904
901905
906
902907/*
903908** {======================================================
904909** GC control
r242885r242886
907912
908913
909914/*
910** set a reasonable "time" to wait before starting a new GC cycle;
911** cycle will start when memory use hits threshold
915** Set a reasonable "time" to wait before starting a new GC cycle; cycle
916** will start when memory use hits threshold. (Division by 'estimate'
917** should be OK: it cannot be zero (because Lua cannot even start with
918** less than PAUSEADJ bytes).
912919*/
913static void setpause (global_State *g, l_mem estimate) {
914  l_mem debt, threshold;
915  estimate = estimate / PAUSEADJ;  /* adjust 'estimate' */
920static void setpause (global_State *g) {
921  l_mem threshold, debt;
922  l_mem estimate = g->GCestimate / PAUSEADJ;  /* adjust 'estimate' */
923  lua_assert(estimate > 0);
916924  threshold = (g->gcpause < MAX_LMEM / estimate)  /* overflow? */
917925            ? estimate * g->gcpause  /* no overflow */
918926            : MAX_LMEM;  /* overflow; truncate to maximum */
919  debt = -cast(l_mem, threshold - gettotalbytes(g));
927  debt = gettotalbytes(g) - threshold;
920928  luaE_setdebt(g, debt);
921929}
922930
923931
924#define sweepphases  \
925   (bitmask(GCSsweepstring) | bitmask(GCSsweepudata) | bitmask(GCSsweep))
926
927
928932/*
929** enter first sweep phase (strings) and prepare pointers for other
930** sweep phases.  The calls to 'sweeptolive' make pointers point to an
931** object inside the list (instead of to the header), so that the real
932** sweep do not need to skip objects created between "now" and the start
933** of the real sweep.
933** Enter first sweep phase.
934** The call to 'sweeptolive' makes pointer point to an object inside
935** the list (instead of to the header), so that the real sweep do not
936** need to skip objects created between "now" and the start of the real
937** sweep.
934938** Returns how many objects it swept.
935939*/
936940static int entersweep (lua_State *L) {
937941  global_State *g = G(L);
938942  int n = 0;
939  g->gcstate = GCSsweepstring;
940  lua_assert(g->sweepgc == NULL && g->sweepfin == NULL);
941  /* prepare to sweep strings, finalizable objects, and regular objects */
942  g->sweepstrgc = 0;
943  g->sweepfin = sweeptolive(L, &g->finobj, &n);
943  g->gcstate = GCSswpallgc;
944  lua_assert(g->sweepgc == NULL);
944945  g->sweepgc = sweeptolive(L, &g->allgc, &n);
945946  return n;
946947}
947948
948949
949/*
950** change GC mode
951*/
952void luaC_changemode (lua_State *L, int mode) {
953  global_State *g = G(L);
954  if (mode == g->gckind) return;  /* nothing to change */
955  if (mode == KGC_GEN) {  /* change to generational mode */
956    /* make sure gray lists are consistent */
957    luaC_runtilstate(L, bitmask(GCSpropagate));
958    g->GCestimate = gettotalbytes(g);
959    g->gckind = KGC_GEN;
960  }
961  else {  /* change to incremental mode */
962    /* sweep all objects to turn them back to white
963       (as white has not changed, nothing extra will be collected) */
964    g->gckind = KGC_NORMAL;
965    entersweep(L);
966    luaC_runtilstate(L, ~sweepphases);
967  }
968}
969
970
971/*
972** call all pending finalizers
973*/
974static void callallpendingfinalizers (lua_State *L, int propagateerrors) {
975  global_State *g = G(L);
976  while (g->tobefnz) {
977    resetoldbit(g->tobefnz);
978    GCTM(L, propagateerrors);
979  }
980}
981
982
983950void luaC_freeallobjects (lua_State *L) {
984951  global_State *g = G(L);
985  int i;
986  separatetobefnz(L, 1);  /* separate all objects with finalizers */
952  separatetobefnz(g, 1);  /* separate all objects with finalizers */
987953  lua_assert(g->finobj == NULL);
988954  callallpendingfinalizers(L, 0);
955  lua_assert(g->tobefnz == NULL);
989956  g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
990957  g->gckind = KGC_NORMAL;
991  sweepwholelist(L, &g->finobj);  /* finalizers can create objs. in 'finobj' */
958  sweepwholelist(L, &g->finobj);
992959  sweepwholelist(L, &g->allgc);
993  for (i = 0; i < g->strt.size; i++)  /* free all string lists */
994    sweepwholelist(L, &g->strt.hash[i]);
960  sweepwholelist(L, &g->fixedgc);  /* collect fixed objects */
995961  lua_assert(g->strt.nuse == 0);
996962}
997963
998964
999965static l_mem atomic (lua_State *L) {
1000966  global_State *g = G(L);
1001  l_mem work = -cast(l_mem, g->GCmemtrav);  /* start counting work */
967  l_mem work;
1002968  GCObject *origweak, *origall;
1003  lua_assert(!iswhite(obj2gco(g->mainthread)));
969  GCObject *grayagain = g->grayagain;  /* save original list */
970  lua_assert(g->ephemeron == NULL && g->weak == NULL);
971  lua_assert(!iswhite(g->mainthread));
972  g->gcstate = GCSinsideatomic;
973  g->GCmemtrav = 0;  /* start counting work */
1004974  markobject(g, L);  /* mark running thread */
1005975  /* registry and global metatables may be changed by API */
1006976  markvalue(g, &g->l_registry);
1007  markmt(g);  /* mark basic metatables */
977  markmt(g);  /* mark global metatables */
1008978  /* remark occasional upvalues of (maybe) dead threads */
1009979  remarkupvals(g);
1010980  propagateall(g);  /* propagate changes */
1011  work += g->GCmemtrav;  /* stop counting (do not (re)count grays) */
1012  /* traverse objects caught by write barrier and by 'remarkupvals' */
1013  retraversegrays(g);
1014  work -= g->GCmemtrav;  /* restart counting */
981  work = g->GCmemtrav;  /* stop counting (do not recount 'grayagain') */
982  g->gray = grayagain;
983  propagateall(g);  /* traverse 'grayagain' list */
984  g->GCmemtrav = 0;  /* restart counting */
1015985  convergeephemerons(g);
1016986  /* at this point, all strongly accessible objects are marked. */
1017  /* clear values from weak tables, before checking finalizers */
987  /* Clear values from weak tables, before checking finalizers */
1018988  clearvalues(g, g->weak, NULL);
1019989  clearvalues(g, g->allweak, NULL);
1020990  origweak = g->weak; origall = g->allweak;
1021991  work += g->GCmemtrav;  /* stop counting (objects being finalized) */
1022  separatetobefnz(L, 0);  /* separate objects to be finalized */
992  separatetobefnz(g, 0);  /* separate objects to be finalized */
993  g->gcfinnum = 1;  /* there may be objects to be finalized */
1023994  markbeingfnz(g);  /* mark objects that will be finalized */
1024  propagateall(g);  /* remark, to propagate `preserveness' */
1025  work -= g->GCmemtrav;  /* restart counting */
995  propagateall(g);  /* remark, to propagate 'resurrection' */
996  g->GCmemtrav = 0;  /* restart counting */
1026997  convergeephemerons(g);
1027998  /* at this point, all resurrected objects are marked. */
1028999  /* remove dead objects from weak tables */
10291000  clearkeys(g, g->ephemeron, NULL);  /* clear keys from all ephemeron tables */
1030  clearkeys(g, g->allweak, NULL);  /* clear keys from all allweak tables */
1001  clearkeys(g, g->allweak, NULL);  /* clear keys from all 'allweak' tables */
10311002  /* clear values from resurrected weak tables */
10321003  clearvalues(g, g->weak, origweak);
10331004  clearvalues(g, g->allweak, origall);
r242885r242886
10371008}
10381009
10391010
1011static lu_mem sweepstep (lua_State *L, global_State *g,
1012                         int nextstate, GCObject **nextlist) {
1013  if (g->sweepgc) {
1014    l_mem olddebt = g->GCdebt;
1015    g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1016    g->GCestimate += g->GCdebt - olddebt;  /* update estimate */
1017    if (g->sweepgc)  /* is there still something to sweep? */
1018      return (GCSWEEPMAX * GCSWEEPCOST);
1019  }
1020  /* else enter next state */
1021  g->gcstate = nextstate;
1022  g->sweepgc = nextlist;
1023  return 0;
1024}
1025
1026
10401027static lu_mem singlestep (lua_State *L) {
10411028  global_State *g = G(L);
10421029  switch (g->gcstate) {
10431030    case GCSpause: {
1044      /* start to count memory traversed */
10451031      g->GCmemtrav = g->strt.size * sizeof(GCObject*);
1046      lua_assert(!isgenerational(g));
10471032      restartcollection(g);
10481033      g->gcstate = GCSpropagate;
10491034      return g->GCmemtrav;
10501035    }
10511036    case GCSpropagate: {
1052      if (g->gray) {
1053        lu_mem oldtrav = g->GCmemtrav;
1054        propagatemark(g);
1055        return g->GCmemtrav - oldtrav;  /* memory traversed in this step */
1056      }
1057      else {  /* no more `gray' objects */
1058        lu_mem work;
1059        int sw;
1060        g->gcstate = GCSatomic;  /* finish mark phase */
1061        g->GCestimate = g->GCmemtrav;  /* save what was counted */;
1062        work = atomic(L);  /* add what was traversed by 'atomic' */
1063        g->GCestimate += work;  /* estimate of total memory traversed */
1064        sw = entersweep(L);
1065        return work + sw * GCSWEEPCOST;
1066      }
1037      g->GCmemtrav = 0;
1038      lua_assert(g->gray);
1039      propagatemark(g);
1040       if (g->gray == NULL)  /* no more gray objects? */
1041        g->gcstate = GCSatomic;  /* finish propagate phase */
1042      return g->GCmemtrav;  /* memory traversed in this step */
10671043    }
1068    case GCSsweepstring: {
1069      int i;
1070      for (i = 0; i < GCSWEEPMAX && g->sweepstrgc + i < g->strt.size; i++)
1071        sweepwholelist(L, &g->strt.hash[g->sweepstrgc + i]);
1072      g->sweepstrgc += i;
1073      if (g->sweepstrgc >= g->strt.size)  /* no more strings to sweep? */
1074        g->gcstate = GCSsweepudata;
1075      return i * GCSWEEPCOST;
1044    case GCSatomic: {
1045      lu_mem work;
1046      int sw;
1047      propagateall(g);  /* make sure gray list is empty */
1048      work = atomic(L);  /* work is what was traversed by 'atomic' */
1049      sw = entersweep(L);
1050      g->GCestimate = gettotalbytes(g);  /* first estimate */;
1051      return work + sw * GCSWEEPCOST;
10761052    }
1077    case GCSsweepudata: {
1078      if (g->sweepfin) {
1079        g->sweepfin = sweeplist(L, g->sweepfin, GCSWEEPMAX);
1080        return GCSWEEPMAX*GCSWEEPCOST;
1081      }
1082      else {
1083        g->gcstate = GCSsweep;
1084        return 0;
1085      }
1053    case GCSswpallgc: {  /* sweep "regular" objects */
1054      return sweepstep(L, g, GCSswpfinobj, &g->finobj);
10861055    }
1087    case GCSsweep: {
1088      if (g->sweepgc) {
1089        g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1090        return GCSWEEPMAX*GCSWEEPCOST;
1056    case GCSswpfinobj: {  /* sweep objects with finalizers */
1057      return sweepstep(L, g, GCSswptobefnz, &g->tobefnz);
1058    }
1059    case GCSswptobefnz: {  /* sweep objects to be finalized */
1060      return sweepstep(L, g, GCSswpend, NULL);
1061    }
1062    case GCSswpend: {  /* finish sweeps */
1063      makewhite(g, g->mainthread);  /* sweep main thread */
1064      checkSizes(L, g);
1065      g->gcstate = GCScallfin;
1066      return 0;
1067    }
1068    case GCScallfin: {  /* call remaining finalizers */
1069      if (g->tobefnz && g->gckind != KGC_EMERGENCY) {
1070        int n = runafewfinalizers(L);
1071        return (n * GCFINALIZECOST);
10911072      }
1092      else {
1093        /* sweep main thread */
1094        GCObject *mt = obj2gco(g->mainthread);
1095        sweeplist(L, &mt, 1);
1096        checkSizes(L);
1073      else {  /* emergency mode or no more finalizers */
10971074        g->gcstate = GCSpause;  /* finish collection */
1098        return GCSWEEPCOST;
1075        return 0;
10991076      }
11001077    }
11011078    default: lua_assert(0); return 0;
r242885r242886
11141091}
11151092
11161093
1117static void generationalcollection (lua_State *L) {
1118  global_State *g = G(L);
1119  lua_assert(g->gcstate == GCSpropagate);
1120  if (g->GCestimate == 0) {  /* signal for another major collection? */
1121    luaC_fullgc(L, 0);  /* perform a full regular collection */
1122    g->GCestimate = gettotalbytes(g);  /* update control */
1123  }
1124  else {
1125    lu_mem estimate = g->GCestimate;
1126    luaC_runtilstate(L, bitmask(GCSpause));  /* run complete (minor) cycle */
1127    g->gcstate = GCSpropagate;  /* skip restart */
1128    if (gettotalbytes(g) > (estimate / 100) * g->gcmajorinc)
1129      g->GCestimate = 0;  /* signal for a major collection */
1130    else
1131      g->GCestimate = estimate;  /* keep estimate from last major coll. */
1132
1133  }
1134  setpause(g, gettotalbytes(g));
1135  lua_assert(g->gcstate == GCSpropagate);
1136}
1137
1138
1139static void incstep (lua_State *L) {
1140  global_State *g = G(L);
1094/*
1095** get GC debt and convert it from Kb to 'work units' (avoid zero debt
1096** and overflows)
1097*/
1098static l_mem getdebt (global_State *g) {
11411099  l_mem debt = g->GCdebt;
11421100  int stepmul = g->gcstepmul;
1143  if (stepmul < 40) stepmul = 40;  /* avoid ridiculous low values (and 0) */
1144  /* convert debt from Kb to 'work units' (avoid zero debt and overflows) */
11451101  debt = (debt / STEPMULADJ) + 1;
11461102  debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
1147  do {  /* always perform at least one single step */
1148    lu_mem work = singlestep(L);  /* do some work */
1103  return debt;
1104}
1105
1106/*
1107** performs a basic GC step when collector is running
1108*/
1109void luaC_step (lua_State *L) {
1110  global_State *g = G(L);
1111  l_mem debt = getdebt(g);  /* GC deficit (be paid now) */
1112  if (!g->gcrunning) {  /* not running? */
1113    luaE_setdebt(g, -GCSTEPSIZE * 10);  /* avoid being called too often */
1114    return;
1115  }
1116  do {  /* repeat until pause or enough "credit" (negative debt) */
1117    lu_mem work = singlestep(L);  /* perform one single step */
11491118    debt -= work;
11501119  } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
11511120  if (g->gcstate == GCSpause)
1152    setpause(g, g->GCestimate);  /* pause until next cycle */
1121    setpause(g);  /* pause until next cycle */
11531122  else {
1154    debt = (debt / stepmul) * STEPMULADJ;  /* convert 'work units' to Kb */
1123    debt = (debt / g->gcstepmul) * STEPMULADJ;  /* convert 'work units' to Kb */
11551124    luaE_setdebt(g, debt);
1125    runafewfinalizers(L);
11561126  }
11571127}
11581128
11591129
11601130/*
1161** performs a basic GC step
1131** Performs a full GC cycle; if 'isemergency', set a flag to avoid
1132** some operations which could change the interpreter state in some
1133** unexpected ways (running finalizers and shrinking some structures).
1134** Before running the collection, check 'keepinvariant'; if it is true,
1135** there may be some objects marked as black, so the collector has
1136** to sweep all objects to turn them back to white (as white has not
1137** changed, nothing will be collected).
11621138*/
1163void luaC_forcestep (lua_State *L) {
1164  global_State *g = G(L);
1165  int i;
1166  if (isgenerational(g)) generationalcollection(L);
1167  else incstep(L);
1168  /* run a few finalizers (or all of them at the end of a collect cycle) */
1169  for (i = 0; g->tobefnz && (i < GCFINALIZENUM || g->gcstate == GCSpause); i++)
1170    GCTM(L, 1);  /* call one finalizer */
1171}
1172
1173
1174/*
1175** performs a basic GC step only if collector is running
1176*/
1177void luaC_step (lua_State *L) {
1178  global_State *g = G(L);
1179  if (g->gcrunning) luaC_forcestep(L);
1180  else luaE_setdebt(g, -GCSTEPSIZE);  /* avoid being called too often */
1181}
1182
1183
1184
1185/*
1186** performs a full GC cycle; if "isemergency", does not call
1187** finalizers (which could change stack positions)
1188*/
11891139void luaC_fullgc (lua_State *L, int isemergency) {
11901140  global_State *g = G(L);
1191  int origkind = g->gckind;
1192  lua_assert(origkind != KGC_EMERGENCY);
1193  if (isemergency)  /* do not run finalizers during emergency GC */
1194    g->gckind = KGC_EMERGENCY;
1195  else {
1196    g->gckind = KGC_NORMAL;
1197    callallpendingfinalizers(L, 1);
1141  lua_assert(g->gckind == KGC_NORMAL);
1142  if (isemergency) g->gckind = KGC_EMERGENCY;  /* set flag */
1143  if (keepinvariant(g)) {  /* black objects? */
1144    entersweep(L); /* sweep everything to turn them back to white */
11981145  }
1199  if (keepinvariant(g)) {  /* may there be some black objects? */
1200    /* must sweep all objects to turn them back to white
1201       (as white has not changed, nothing will be collected) */
1202    entersweep(L);
1203  }
12041146  /* finish any pending sweep phase to start a new cycle */
12051147  luaC_runtilstate(L, bitmask(GCSpause));
12061148  luaC_runtilstate(L, ~bitmask(GCSpause));  /* start new collection */
1207  luaC_runtilstate(L, bitmask(GCSpause));  /* run entire collection */
1208  if (origkind == KGC_GEN) {  /* generational mode? */
1209    /* generational mode must be kept in propagate phase */
1210    luaC_runtilstate(L, bitmask(GCSpropagate));
1211  }
1212  g->gckind = origkind;
1213  setpause(g, gettotalbytes(g));
1214  if (!isemergency)   /* do not run finalizers during emergency GC */
1215    callallpendingfinalizers(L, 1);
1149  luaC_runtilstate(L, bitmask(GCScallfin));  /* run up to finalizers */
1150  /* estimate must be correct after a full GC cycle */
1151  lua_assert(g->GCestimate == gettotalbytes(g));
1152  luaC_runtilstate(L, bitmask(GCSpause));  /* finish collection */
1153  g->gckind = KGC_NORMAL;
1154  setpause(g);
12161155}
12171156
12181157/* }====================================================== */
trunk/3rdparty/lua/src/lgc.h
r242885r242886
11/*
2** $Id: lgc.h,v 2.58.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lgc.h,v 2.86 2014/10/25 11:50:46 roberto Exp $
33** Garbage Collector
44** See Copyright Notice in lua.h
55*/
r242885r242886
3838*/
3939#define GCSpropagate   0
4040#define GCSatomic   1
41#define GCSsweepstring   2
42#define GCSsweepudata   3
43#define GCSsweep   4
44#define GCSpause   5
41#define GCSswpallgc   2
42#define GCSswpfinobj   3
43#define GCSswptobefnz   4
44#define GCSswpend   5
45#define GCScallfin   6
46#define GCSpause   7
4547
4648
4749#define issweepphase(g)  \
48   (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep)
50   (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend)
4951
50#define isgenerational(g)   ((g)->gckind == KGC_GEN)
5152
5253/*
53** macros to tell when main invariant (white objects cannot point to black
54** ones) must be kept. During a non-generational collection, the sweep
54** macro to tell when main invariant (white objects cannot point to black
55** ones) must be kept. During a collection, the sweep
5556** phase may break the invariant, as objects turned white may point to
5657** still-black objects. The invariant is restored when sweep ends and
57** all objects are white again. During a generational collection, the
58** invariant must be kept all times.
58** all objects are white again.
5959*/
6060
61#define keepinvariant(g)   (isgenerational(g) || g->gcstate <= GCSatomic)
61#define keepinvariant(g)   ((g)->gcstate <= GCSatomic)
6262
6363
6464/*
65** Outside the collector, the state in generational mode is kept in
66** 'propagate', so 'keepinvariant' is always true.
67*/
68#define keepinvariantout(g)  \
69  check_exp(g->gcstate == GCSpropagate || !isgenerational(g),  \
70            g->gcstate <= GCSatomic)
71
72
73/*
7465** some useful bit tricks
7566*/
7667#define resetbits(x,m)      ((x) &= cast(lu_byte, ~(m)))
r242885r242886
8374#define testbit(x,b)      testbits(x, bitmask(b))
8475
8576
86/* Layout for bit use in `marked' field: */
77/* Layout for bit use in 'marked' field: */
8778#define WHITE0BIT   0  /* object is white (type 0) */
8879#define WHITE1BIT   1  /* object is white (type 1) */
8980#define BLACKBIT   2  /* object is black */
90#define FINALIZEDBIT   3  /* object has been separated for finalization */
91#define SEPARATED   4  /* object is in 'finobj' list or in 'tobefnz' */
92#define FIXEDBIT   5  /* object is fixed (should not be collected) */
93#define OLDBIT      6  /* object is old (only in generational mode) */
81#define FINALIZEDBIT   3  /* object has been marked for finalization */
9482/* bit 7 is currently used by tests (luaL_checkmemory) */
9583
9684#define WHITEBITS   bit2mask(WHITE0BIT, WHITE1BIT)
9785
9886
99#define iswhite(x)      testbits((x)->gch.marked, WHITEBITS)
100#define isblack(x)      testbit((x)->gch.marked, BLACKBIT)
87#define iswhite(x)      testbits((x)->marked, WHITEBITS)
88#define isblack(x)      testbit((x)->marked, BLACKBIT)
10189#define isgray(x)  /* neither white nor black */  \
102   (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT)))
90   (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT)))
10391
104#define isold(x)   testbit((x)->gch.marked, OLDBIT)
92#define tofinalize(x)   testbit((x)->marked, FINALIZEDBIT)
10593
106/* MOVE OLD rule: whenever an object is moved to the beginning of
107   a GC list, its old bit must be cleared */
108#define resetoldbit(o)   resetbit((o)->gch.marked, OLDBIT)
109
110#define otherwhite(g)   (g->currentwhite ^ WHITEBITS)
94#define otherwhite(g)   ((g)->currentwhite ^ WHITEBITS)
11195#define isdeadm(ow,m)   (!(((m) ^ WHITEBITS) & (ow)))
112#define isdead(g,v)   isdeadm(otherwhite(g), (v)->gch.marked)
96#define isdead(g,v)   isdeadm(otherwhite(g), (v)->marked)
11397
114#define changewhite(x)   ((x)->gch.marked ^= WHITEBITS)
115#define gray2black(x)   l_setbit((x)->gch.marked, BLACKBIT)
98#define changewhite(x)   ((x)->marked ^= WHITEBITS)
99#define gray2black(x)   l_setbit((x)->marked, BLACKBIT)
116100
117#define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x)))
118
119101#define luaC_white(g)   cast(lu_byte, (g)->currentwhite & WHITEBITS)
120102
121103
r242885r242886
124106#define luaC_checkGC(L)      luaC_condGC(L, luaC_step(L);)
125107
126108
127#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p)))  \
109#define luaC_barrier(L,p,v) {  \
110   if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v)))  \
128111   luaC_barrier_(L,obj2gco(p),gcvalue(v)); }
129112
130#define luaC_barrierback(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p)))  \
113#define luaC_barrierback(L,p,v) {  \
114   if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v)))  \
131115   luaC_barrierback_(L,p); }
132116
133#define luaC_objbarrier(L,p,o)  \
134   { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
117#define luaC_objbarrier(L,p,o) {  \
118   if (isblack(p) && iswhite(o)) \
135119      luaC_barrier_(L,obj2gco(p),obj2gco(o)); }
136120
137#define luaC_objbarrierback(L,p,o)  \
138   { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) luaC_barrierback_(L,p); }
121#define luaC_upvalbarrier(L,uv) \
122  { if (iscollectable((uv)->v) && !upisopen(uv)) \
123         luaC_upvalbarrier_(L,uv); }
139124
140#define luaC_barrierproto(L,p,c) \
141   { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); }
142
125LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o);
143126LUAI_FUNC void luaC_freeallobjects (lua_State *L);
144127LUAI_FUNC void luaC_step (lua_State *L);
145LUAI_FUNC void luaC_forcestep (lua_State *L);
146128LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);
147129LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
148LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,
149                                 GCObject **list, int offset);
130LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz);
150131LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
151LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);
152LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c);
132LUAI_FUNC void luaC_barrierback_ (lua_State *L, Table *o);
133LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv);
153134LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
154LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv);
155LUAI_FUNC void luaC_changemode (lua_State *L, int mode);
135LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv);
156136
137
157138#endif
trunk/3rdparty/lua/src/linit.c
r242885r242886
11/*
2** $Id: linit.c,v 1.32.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: linit.c,v 1.38 2015/01/05 13:48:33 roberto Exp $
33** Initialization of libraries for lua.c and other clients
44** See Copyright Notice in lua.h
55*/
66
77
8#define linit_c
9#define LUA_LIB
10
811/*
912** If you embed Lua in your program and need to open the standard
1013** libraries, call luaL_openlibs in your program. If you need a
1114** different set of libraries, copy this file to your project and edit
1215** it to suit your needs.
16**
17** You can also *preload* libraries, so that a later 'require' can
18** open the library, which is already linked to the application.
19** For that, do the following code:
20**
21**  luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
22**  lua_pushcfunction(L, luaopen_modname);
23**  lua_setfield(L, -2, modname);
24**  lua_pop(L, 1);  // remove _PRELOAD table
1325*/
1426
27#include "lprefix.h"
1528
16#define linit_c
17#define LUA_LIB
1829
30#include <stddef.h>
31
1932#include "lua.h"
2033
2134#include "lualib.h"
r242885r242886
3447  {LUA_IOLIBNAME, luaopen_io},
3548  {LUA_OSLIBNAME, luaopen_os},
3649  {LUA_STRLIBNAME, luaopen_string},
37  {LUA_BITLIBNAME, luaopen_bit32},
3850  {LUA_MATHLIBNAME, luaopen_math},
51  {LUA_UTF8LIBNAME, luaopen_utf8},
3952  {LUA_DBLIBNAME, luaopen_debug},
53#if defined(LUA_COMPAT_BITLIB)
54  {LUA_BITLIBNAME, luaopen_bit32},
55#endif
4056  {NULL, NULL}
4157};
4258
4359
44/*
45** these libs are preloaded and must be required before used
46*/
47static const luaL_Reg preloadedlibs[] = {
48  {NULL, NULL}
49};
50
51
5260LUALIB_API void luaL_openlibs (lua_State *L) {
5361  const luaL_Reg *lib;
54  /* call open functions from 'loadedlibs' and set results to global table */
62  /* "require" functions from 'loadedlibs' and set results to global table */
5563  for (lib = loadedlibs; lib->func; lib++) {
5664    luaL_requiref(L, lib->name, lib->func, 1);
5765    lua_pop(L, 1);  /* remove lib */
5866  }
59  /* add open functions from 'preloadedlibs' into 'package.preload' table */
60  luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
61  for (lib = preloadedlibs; lib->func; lib++) {
62    lua_pushcfunction(L, lib->func);
63    lua_setfield(L, -2, lib->name);
64  }
65  lua_pop(L, 1);  /* remove _PRELOAD table */
6667}
6768
trunk/3rdparty/lua/src/liolib.c
r242885r242886
11/*
2** $Id: liolib.c,v 2.112.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: liolib.c,v 2.142 2015/01/02 12:50:28 roberto Exp $
33** Standard I/O (and system) library
44** See Copyright Notice in lua.h
55*/
66
7#define liolib_c
8#define LUA_LIB
79
8/*
9** This definition must come before the inclusion of 'stdio.h'; it
10** should not affect non-POSIX systems
11*/
12#if !defined(_FILE_OFFSET_BITS)
13#define   _LARGEFILE_SOURCE   1
14#define _FILE_OFFSET_BITS   64
15#endif
10#include "lprefix.h"
1611
1712
13#include <ctype.h>
1814#include <errno.h>
15#include <locale.h>
1916#include <stdio.h>
2017#include <stdlib.h>
2118#include <string.h>
2219
23#define liolib_c
24#define LUA_LIB
25
2620#include "lua.h"
2721
2822#include "lauxlib.h"
2923#include "lualib.h"
3024
3125
32#if !defined(lua_checkmode)
26#if !defined(l_checkmode)
3327
3428/*
3529** Check whether 'mode' matches '[rwa]%+?b?'.
3630** Change this macro to accept other modes for 'fopen' besides
3731** the standard ones.
3832*/
39#define lua_checkmode(mode) \
33#define l_checkmode(mode) \
4034   (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&   \
4135   (*mode != '+' || ++mode) &&  /* skip if char is '+' */   \
4236   (*mode != 'b' || ++mode) &&  /* skip if char is 'b' */   \
r242885r242886
4640
4741/*
4842** {======================================================
49** lua_popen spawns a new process connected to the current
43** l_popen spawns a new process connected to the current
5044** one through the file streams.
5145** =======================================================
5246*/
5347
54#if !defined(lua_popen)   /* { */
48#if !defined(l_popen)      /* { */
5549
56#if defined(LUA_USE_POPEN)   /* { */
50#if defined(LUA_USE_POSIX)   /* { */
5751
58#define lua_popen(L,c,m)   ((void)L, fflush(NULL), popen(c,m))
59#define lua_pclose(L,file)   ((void)L, pclose(file))
52#define l_popen(L,c,m)      (fflush(NULL), popen(c,m))
53#define l_pclose(L,file)   (pclose(file))
6054
61#elif defined(LUA_WIN)      /* }{ */
55#elif defined(LUA_USE_WINDOWS)   /* }{ */
6256
63#define lua_popen(L,c,m)      ((void)L, _popen(c,m))
64#define lua_pclose(L,file)      ((void)L, _pclose(file))
57#define l_popen(L,c,m)      (_popen(c,m))
58#define l_pclose(L,file)   (_pclose(file))
6559
66
6760#else            /* }{ */
6861
69#define lua_popen(L,c,m)      ((void)((void)c, m),  \
70      luaL_error(L, LUA_QL("popen") " not supported"), (FILE*)0)
71#define lua_pclose(L,file)      ((void)((void)L, file), -1)
62/* ISO C definitions */
63#define l_popen(L,c,m)  \
64     ((void)((void)c, m), \
65     luaL_error(L, "'popen' not supported"), \
66     (FILE*)0)
67#define l_pclose(L,file)      ((void)L, (void)file, -1)
7268
69#endif            /* } */
7370
7471#endif            /* } */
7572
76#endif         /* } */
77
7873/* }====================================================== */
7974
8075
76#if !defined(l_getc)      /* { */
77
78#if defined(LUA_USE_POSIX)
79#define l_getc(f)      getc_unlocked(f)
80#define l_lockfile(f)      flockfile(f)
81#define l_unlockfile(f)      funlockfile(f)
82#else
83#define l_getc(f)      getc(f)
84#define l_lockfile(f)      ((void)0)
85#define l_unlockfile(f)      ((void)0)
86#endif
87
88#endif            /* } */
89
90
8191/*
8292** {======================================================
83** lua_fseek: configuration for longer offsets
93** l_fseek: configuration for longer offsets
8494** =======================================================
8595*/
8696
87#if !defined(lua_fseek)   && !defined(LUA_ANSI)   /* { */
97#if !defined(l_fseek)      /* { */
8898
8999#if defined(LUA_USE_POSIX)   /* { */
90100
101#include <sys/types.h>
102
91103#define l_fseek(f,o,w)      fseeko(f,o,w)
92104#define l_ftell(f)      ftello(f)
93105#define l_seeknum      off_t
94106
95#elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
107#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
96108   && defined(_MSC_VER) && (_MSC_VER >= 1400)   /* }{ */
109
97110/* Windows (but not DDK) and Visual C++ 2005 or higher */
98
99111#define l_fseek(f,o,w)      _fseeki64(f,o,w)
100112#define l_ftell(f)      _ftelli64(f)
101113#define l_seeknum      __int64
102114
103#endif   /* } */
115#else            /* }{ */
104116
105#endif         /* } */
106
107
108#if !defined(l_fseek)      /* default definitions */
117/* ISO C definitions */
109118#define l_fseek(f,o,w)      fseek(f,o,w)
110119#define l_ftell(f)      ftell(f)
111120#define l_seeknum      long
112#endif
113121
122#endif            /* } */
123
124#endif            /* } */
125
114126/* }====================================================== */
115127
116128
117129#define IO_PREFIX   "_IO_"
130#define IOPREF_LEN   (sizeof(IO_PREFIX)/sizeof(char) - 1)
118131#define IO_INPUT   (IO_PREFIX "input")
119132#define IO_OUTPUT   (IO_PREFIX "output")
120133
r242885r242886
161174
162175
163176/*
164** When creating file handles, always creates a `closed' file handle
177** When creating file handles, always creates a 'closed' file handle
165178** before opening the actual file; so, if there is a memory error, the
166179** file is not left opened.
167180*/
r242885r242886
173186}
174187
175188
189/*
190** Calls the 'close' function from a file handle. The 'volatile' avoids
191** a bug in some versions of the Clang compiler (e.g., clang 3.0 for
192** 32 bits).
193*/
176194static int aux_close (lua_State *L) {
177195  LStream *p = tolstream(L);
178  lua_CFunction cf = p->closef;
196  volatile lua_CFunction cf = p->closef;
179197  p->closef = NULL;  /* mark stream as closed */
180198  return (*cf)(L);  /* close it */
181199}
r242885r242886
219237  LStream *p = newfile(L);
220238  p->f = fopen(fname, mode);
221239  if (p->f == NULL)
222    luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
240    luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
223241}
224242
225243
r242885r242886
228246  const char *mode = luaL_optstring(L, 2, "r");
229247  LStream *p = newfile(L);
230248  const char *md = mode;  /* to traverse/check mode */
231  luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode");
249  luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
232250  p->f = fopen(filename, mode);
233251  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
234252}
r242885r242886
239257*/
240258static int io_pclose (lua_State *L) {
241259  LStream *p = tolstream(L);
242  return luaL_execresult(L, lua_pclose(L, p->f));
260  return luaL_execresult(L, l_pclose(L, p->f));
243261}
244262
245263
r242885r242886
247265  const char *filename = luaL_checkstring(L, 1);
248266  const char *mode = luaL_optstring(L, 2, "r");
249267  LStream *p = newprefile(L);
250  p->f = lua_popen(L, filename, mode);
268  p->f = l_popen(L, filename, mode);
251269  p->closef = &io_pclose;
252270  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
253271}
r242885r242886
265283  lua_getfield(L, LUA_REGISTRYINDEX, findex);
266284  p = (LStream *)lua_touserdata(L, -1);
267285  if (isclosed(p))
268    luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
286    luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
269287  return p->f;
270288}
271289
r242885r242886
301319
302320
303321static void aux_lines (lua_State *L, int toclose) {
304  int i;
305322  int n = lua_gettop(L) - 1;  /* number of arguments to read */
306  /* ensure that arguments will fit here and into 'io_readline' stack */
307  luaL_argcheck(L, n <= LUA_MINSTACK - 3, LUA_MINSTACK - 3, "too many options");
308  lua_pushvalue(L, 1);  /* file handle */
309323  lua_pushinteger(L, n);  /* number of arguments to read */
310324  lua_pushboolean(L, toclose);  /* close/not close file when finished */
311  for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1);  /* copy arguments */
325  lua_rotate(L, 2, 2);  /* move 'n' and 'toclose' to their positions */
312326  lua_pushcclosure(L, io_readline, 3 + n);
313327}
314328
r242885r242886
347361*/
348362
349363
350static int read_number (lua_State *L, FILE *f) {
351  lua_Number d;
352  if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
353    lua_pushnumber(L, d);
364/* maximum length of a numeral */
365#define MAXRN      200
366
367/* auxiliary structure used by 'read_number' */
368typedef struct {
369  FILE *f;  /* file being read */
370  int c;  /* current character (look ahead) */
371  int n;  /* number of elements in buffer 'buff' */
372  char buff[MAXRN + 1];  /* +1 for ending '\0' */
373} RN;
374
375
376/*
377** Add current char to buffer (if not out of space) and read next one
378*/
379static int nextc (RN *rn) {
380  if (rn->n >= MAXRN) {  /* buffer overflow? */
381    rn->buff[0] = '\0';  /* invalidate result */
382    return 0;  /* fail */
383  }
384  else {
385    rn->buff[rn->n++] = rn->c;  /* save current char */
386    rn->c = l_getc(rn->f);  /* read next one */
354387    return 1;
355388  }
356  else {
389}
390
391
392/*
393** Accept current char if it is in 'set' (of size 1 or 2)
394*/
395static int test2 (RN *rn, const char *set) {
396  if (rn->c == set[0] || (rn->c == set[1] && rn->c != '\0'))
397    return nextc(rn);
398  else return 0;
399}
400
401
402/*
403** Read a sequence of (hex)digits
404*/
405static int readdigits (RN *rn, int hex) {
406  int count = 0;
407  while ((hex ? isxdigit(rn->c) : isdigit(rn->c)) && nextc(rn))
408    count++;
409  return count;
410}
411
412
413/* access to locale "radix character" (decimal point) */
414#if !defined(l_getlocaledecpoint)
415#define l_getlocaledecpoint()     (localeconv()->decimal_point[0])
416#endif
417
418
419/*
420** Read a number: first reads a valid prefix of a numeral into a buffer.
421** Then it calls 'lua_stringtonumber' to check whether the format is
422** correct and to convert it to a Lua number
423*/
424static int read_number (lua_State *L, FILE *f) {
425  RN rn;
426  int count = 0;
427  int hex = 0;
428  char decp[2] = ".";
429  rn.f = f; rn.n = 0;
430  decp[0] = l_getlocaledecpoint();  /* get decimal point from locale */
431  l_lockfile(rn.f);
432  do { rn.c = l_getc(rn.f); } while (isspace(rn.c));  /* skip spaces */
433  test2(&rn, "-+");  /* optional signal */
434  if (test2(&rn, "0")) {
435    if (test2(&rn, "xX")) hex = 1;  /* numeral is hexadecimal */
436    else count = 1;  /* count initial '0' as a valid digit */
437  }
438  count += readdigits(&rn, hex);  /* integral part */
439  if (test2(&rn, decp))  /* decimal point? */
440    count += readdigits(&rn, hex);  /* fractional part */
441  if (count > 0 && test2(&rn, (hex ? "pP" : "eE"))) {  /* exponent mark? */
442    test2(&rn, "-+");  /* exponent signal */
443    readdigits(&rn, 0);  /* exponent digits */
444  }
445  ungetc(rn.c, rn.f);  /* unread look-ahead char */
446  l_unlockfile(rn.f);
447  rn.buff[rn.n] = '\0';  /* finish string */
448  if (lua_stringtonumber(L, rn.buff))  /* is this a valid number? */
449    return 1;  /* ok */
450  else {  /* invalid format */
357451   lua_pushnil(L);  /* "result" to be removed */
358452   return 0;  /* read fails */
359453  }
r242885r242886
362456
363457static int test_eof (lua_State *L, FILE *f) {
364458  int c = getc(f);
365  ungetc(c, f);
459  ungetc(c, f);  /* no-op when c == EOF */
366460  lua_pushlstring(L, NULL, 0);
367461  return (c != EOF);
368462}
r242885r242886
370464
371465static int read_line (lua_State *L, FILE *f, int chop) {
372466  luaL_Buffer b;
467  int c = '\0';
373468  luaL_buffinit(L, &b);
374  for (;;) {
375    size_t l;
376    char *p = luaL_prepbuffer(&b);
377    if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) {  /* eof? */
378      luaL_pushresult(&b);  /* close buffer */
379      return (lua_rawlen(L, -1) > 0);  /* check whether read something */
380    }
381    l = strlen(p);
382    if (l == 0 || p[l-1] != '\n')
383      luaL_addsize(&b, l);
384    else {
385      luaL_addsize(&b, l - chop);  /* chop 'eol' if needed */
386      luaL_pushresult(&b);  /* close buffer */
387      return 1;  /* read at least an `eol' */
388    }
469  while (c != EOF && c != '\n') {  /* repeat until end of line */
470    char *buff = luaL_prepbuffer(&b);  /* pre-allocate buffer */
471    int i = 0;
472    l_lockfile(f);  /* no memory errors can happen inside the lock */
473    while (i < LUAL_BUFFERSIZE && (c = l_getc(f)) != EOF && c != '\n')
474      buff[i++] = c;
475    l_unlockfile(f);
476    luaL_addsize(&b, i);
389477  }
478  if (!chop && c == '\n')  /* want a newline and have one? */
479    luaL_addchar(&b, c);  /* add ending newline to result */
480  luaL_pushresult(&b);  /* close buffer */
481  /* return ok if read something (either a newline or something else) */
482  return (c == '\n' || lua_rawlen(L, -1) > 0);
390483}
391484
392485
393#define MAX_SIZE_T   (~(size_t)0)
394
395486static void read_all (lua_State *L, FILE *f) {
396  size_t rlen = LUAL_BUFFERSIZE;  /* how much to read in each cycle */
487  size_t nr;
397488  luaL_Buffer b;
398489  luaL_buffinit(L, &b);
399  for (;;) {
400    char *p = luaL_prepbuffsize(&b, rlen);
401    size_t nr = fread(p, sizeof(char), rlen, f);
490  do {  /* read file in chunks of LUAL_BUFFERSIZE bytes */
491    char *p = luaL_prepbuffsize(&b, LUAL_BUFFERSIZE);
492    nr = fread(p, sizeof(char), LUAL_BUFFERSIZE, f);
402493    luaL_addsize(&b, nr);
403    if (nr < rlen) break;  /* eof? */
404    else if (rlen <= (MAX_SIZE_T / 4))  /* avoid buffers too large */
405      rlen *= 2;  /* double buffer size at each iteration */
406  }
494  } while (nr == LUAL_BUFFERSIZE);
407495  luaL_pushresult(&b);  /* close buffer */
408496}
409497
r242885r242886
435523    success = 1;
436524    for (n = first; nargs-- && success; n++) {
437525      if (lua_type(L, n) == LUA_TNUMBER) {
438        size_t l = (size_t)lua_tointeger(L, n);
526        size_t l = (size_t)luaL_checkinteger(L, n);
439527        success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
440528      }
441529      else {
442        const char *p = lua_tostring(L, n);
443        luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
444        switch (p[1]) {
530        const char *p = luaL_checkstring(L, n);
531        if (*p == '*') p++;  /* skip optional '*' (for compatibility) */
532        switch (*p) {
445533          case 'n':  /* number */
446534            success = read_number(L, f);
447535            break;
r242885r242886
488576  if (isclosed(p))  /* file is already closed? */
489577    return luaL_error(L, "file is already closed");
490578  lua_settop(L , 1);
579  luaL_checkstack(L, n, "too many arguments");
491580  for (i = 1; i <= n; i++)  /* push arguments to 'g_read' */
492581    lua_pushvalue(L, lua_upvalueindex(3 + i));
493582  n = g_read(L, p->f, 2);  /* 'n' is number of results */
494583  lua_assert(n > 0);  /* should return at least a nil */
495  if (!lua_isnil(L, -n))  /* read at least one value? */
584  if (lua_toboolean(L, -n))  /* read at least one value? */
496585    return n;  /* return them */
497586  else {  /* first result is nil: EOF or error */
498587    if (n > 1) {  /* is there error information? */
r242885r242886
517606  for (; nargs--; arg++) {
518607    if (lua_type(L, arg) == LUA_TNUMBER) {
519608      /* optimization: could be done exactly as for strings */
520      status = status &&
521          fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
609      int len = lua_isinteger(L, arg)
610                ? fprintf(f, LUA_INTEGER_FMT, lua_tointeger(L, arg))
611                : fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg));
612      status = status && (len > 0);
522613    }
523614    else {
524615      size_t l;
r242885r242886
548639  static const char *const modenames[] = {"set", "cur", "end", NULL};
549640  FILE *f = tofile(L);
550641  int op = luaL_checkoption(L, 2, "cur", modenames);
551  lua_Number p3 = luaL_optnumber(L, 3, 0);
642  lua_Integer p3 = luaL_optinteger(L, 3, 0);
552643  l_seeknum offset = (l_seeknum)p3;
553  luaL_argcheck(L, (lua_Number)offset == p3, 3,
644  luaL_argcheck(L, (lua_Integer)offset == p3, 3,
554645                  "not an integer in proper range");
555646  op = l_fseek(f, offset, mode[op]);
556647  if (op)
557648    return luaL_fileresult(L, 0, NULL);  /* error */
558649  else {
559    lua_pushnumber(L, (lua_Number)(1.0 * l_ftell(f)));
650    lua_pushinteger(L, (lua_Integer)l_ftell(f));
560651    return 1;
561652  }
562653}
r242885r242886
568659  FILE *f = tofile(L);
569660  int op = luaL_checkoption(L, 2, NULL, modenames);
570661  lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
571  int res = setvbuf(f, NULL, mode[op], sz);
662  int res = setvbuf(f, NULL, mode[op], (size_t)sz);
572663  return luaL_fileresult(L, res == 0, NULL);
573664}
574665
trunk/3rdparty/lua/src/llex.c
r242885r242886
11/*
2** $Id: llex.c,v 2.63.1.2 2013/08/30 15:49:41 roberto Exp $
2** $Id: llex.c,v 2.89 2014/11/14 16:06:09 roberto Exp $
33** Lexical Analyzer
44** See Copyright Notice in lua.h
55*/
66
7#define llex_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <locale.h>
914#include <string.h>
1015
11#define llex_c
12#define LUA_CORE
13
1416#include "lua.h"
1517
1618#include "lctype.h"
1719#include "ldo.h"
20#include "lgc.h"
1821#include "llex.h"
1922#include "lobject.h"
2023#include "lparser.h"
r242885r242886
3841    "end", "false", "for", "function", "goto", "if",
3942    "in", "local", "nil", "not", "or", "repeat",
4043    "return", "then", "true", "until", "while",
41    "..", "...", "==", ">=", "<=", "~=", "::", "<eof>",
42    "<number>", "<name>", "<string>"
44    "//", "..", "...", "==", ">=", "<=", "~=",
45    "<<", ">>", "::", "<eof>",
46    "<number>", "<integer>", "<name>", "<string>"
4347};
4448
4549
r242885r242886
5357  Mbuffer *b = ls->buff;
5458  if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
5559    size_t newsize;
56    if (luaZ_sizebuffer(b) >= MAX_SIZET/2)
60    if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
5761      lexerror(ls, "lexical element too long", 0);
5862    newsize = luaZ_sizebuffer(b) * 2;
5963    luaZ_resizebuffer(ls->L, b, newsize);
r242885r242886
6468
6569void luaX_init (lua_State *L) {
6670  int i;
71  TString *e = luaS_new(L, LUA_ENV);  /* create env name */
72  luaC_fix(L, obj2gco(e));  /* never collect this name */
6773  for (i=0; i<NUM_RESERVED; i++) {
6874    TString *ts = luaS_new(L, luaX_tokens[i]);
69    luaS_fix(ts);  /* reserved words are never collected */
70    ts->tsv.extra = cast_byte(i+1);  /* reserved word */
75    luaC_fix(L, obj2gco(ts));  /* reserved words are never collected */
76    ts->extra = cast_byte(i+1);  /* reserved word */
7177  }
7278}
7379
7480
7581const char *luaX_token2str (LexState *ls, int token) {
7682  if (token < FIRST_RESERVED) {  /* single-byte symbols? */
77    lua_assert(token == cast(unsigned char, token));
78    return (lisprint(token)) ? luaO_pushfstring(ls->L, LUA_QL("%c"), token) :
79                              luaO_pushfstring(ls->L, "char(%d)", token);
83    lua_assert(token == cast_uchar(token));
84    return luaO_pushfstring(ls->L, "'%c'", token);
8085  }
8186  else {
8287    const char *s = luaX_tokens[token - FIRST_RESERVED];
8388    if (token < TK_EOS)  /* fixed format (symbols and reserved words)? */
84      return luaO_pushfstring(ls->L, LUA_QS, s);
89      return luaO_pushfstring(ls->L, "'%s'", s);
8590    else  /* names, strings, and numerals */
8691      return s;
8792  }
r242885r242886
9095
9196static const char *txtToken (LexState *ls, int token) {
9297  switch (token) {
93    case TK_NAME:
94    case TK_STRING:
95    case TK_NUMBER:
98    case TK_NAME: case TK_STRING:
99    case TK_FLT: case TK_INT:
96100      save(ls, '\0');
97      return luaO_pushfstring(ls->L, LUA_QS, luaZ_buffer(ls->buff));
101      return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff));
98102    default:
99103      return luaX_token2str(ls, token);
100104  }
r242885r242886
117121
118122
119123/*
120** creates a new string and anchors it in function's table so that
121** it will not be collected until the end of the function's compilation
122** (by that time it should be anchored in function's prototype)
124** creates a new string and anchors it in scanner's table so that
125** it will not be collected until the end of the compilation
126** (by that time it should be anchored somewhere)
123127*/
124128TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
125129  lua_State *L = ls->L;
126  TValue *o;  /* entry for `str' */
130  TValue *o;  /* entry for 'str' */
127131  TString *ts = luaS_newlstr(L, str, l);  /* create new string */
128132  setsvalue2s(L, L->top++, ts);  /* temporarily anchor it in stack */
129  o = luaH_set(L, ls->fs->h, L->top - 1);
130  if (ttisnil(o)) {  /* not in use yet? (see 'addK') */
133  o = luaH_set(L, ls->h, L->top - 1);
134  if (ttisnil(o)) {  /* not in use yet? */
131135    /* boolean value does not need GC barrier;
132136       table has no metatable, so it does not need to invalidate cache */
133137    setbvalue(o, 1);  /* t[string] = true */
134138    luaC_checkGC(L);
135139  }
136140  else {  /* string already present */
137    ts = rawtsvalue(keyfromval(o));  /* re-use value previously stored */
141    ts = tsvalue(keyfromval(o));  /* re-use value previously stored */
138142  }
139143  L->top--;  /* remove string from stack */
140144  return ts;
r242885r242886
148152static void inclinenumber (LexState *ls) {
149153  int old = ls->current;
150154  lua_assert(currIsNewline(ls));
151  next(ls);  /* skip `\n' or `\r' */
155  next(ls);  /* skip '\n' or '\r' */
152156  if (currIsNewline(ls) && ls->current != old)
153    next(ls);  /* skip `\n\r' or `\r\n' */
157    next(ls);  /* skip '\n\r' or '\r\n' */
154158  if (++ls->linenumber >= MAX_INT)
155    luaX_syntaxerror(ls, "chunk has too many lines");
159    lexerror(ls, "chunk has too many lines", 0);
156160}
157161
158162
159163void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
160164                    int firstchar) {
165  ls->t.token = 0;
161166  ls->decpoint = '.';
162167  ls->L = L;
163168  ls->current = firstchar;
r242885r242886
167172  ls->linenumber = 1;
168173  ls->lastline = 1;
169174  ls->source = source;
170  ls->envn = luaS_new(L, LUA_ENV);  /* create env name */
171  luaS_fix(ls->envn);  /* never collect this name */
175  ls->envn = luaS_new(L, LUA_ENV);  /* get env name */
172176  luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER);  /* initialize buffer */
173177}
174178
r242885r242886
181185*/
182186
183187
188static int check_next1 (LexState *ls, int c) {
189  if (ls->current == c) {
190    next(ls);
191    return 1;
192  }
193  else return 0;
194}
184195
185static int check_next (LexState *ls, const char *set) {
186  if (ls->current == '\0' || !strchr(set, ls->current))
187    return 0;
188  save_and_next(ls);
189  return 1;
196
197/*
198** Check whether current char is in set 'set' (with two chars) and
199** saves it
200*/
201static int check_next2 (LexState *ls, const char *set) {
202  lua_assert(set[2] == '\0');
203  if (ls->current == set[0] || ls->current == set[1]) {
204    save_and_next(ls);
205    return 1;
206  }
207  else return 0;
190208}
191209
192210
r242885r242886
194212** change all characters 'from' in buffer to 'to'
195213*/
196214static void buffreplace (LexState *ls, char from, char to) {
197  size_t n = luaZ_bufflen(ls->buff);
198  char *p = luaZ_buffer(ls->buff);
199  while (n--)
200    if (p[n] == from) p[n] = to;
215  if (from != to) {
216    size_t n = luaZ_bufflen(ls->buff);
217    char *p = luaZ_buffer(ls->buff);
218    while (n--)
219      if (p[n] == from) p[n] = to;
220  }
201221}
202222
203223
204#if !defined(getlocaledecpoint)
205#define getlocaledecpoint()   (localeconv()->decimal_point[0])
224#if !defined(l_getlocaledecpoint)
225#define l_getlocaledecpoint()   (localeconv()->decimal_point[0])
206226#endif
207227
208228
209#define buff2d(b,e)   luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e)
229#define buff2num(b,o)   (luaO_str2num(luaZ_buffer(b), o) != 0)
210230
211231/*
212232** in case of format error, try to change decimal point separator to
213233** the one defined in the current locale and check again
214234*/
215static void trydecpoint (LexState *ls, SemInfo *seminfo) {
235static void trydecpoint (LexState *ls, TValue *o) {
216236  char old = ls->decpoint;
217  ls->decpoint = getlocaledecpoint();
237  ls->decpoint = l_getlocaledecpoint();
218238  buffreplace(ls, old, ls->decpoint);  /* try new decimal separator */
219  if (!buff2d(ls->buff, &seminfo->r)) {
239  if (!buff2num(ls->buff, o)) {
220240    /* format error with correct decimal point: no more options */
221241    buffreplace(ls, ls->decpoint, '.');  /* undo change (for error message) */
222    lexerror(ls, "malformed number", TK_NUMBER);
242    lexerror(ls, "malformed number", TK_FLT);
223243  }
224244}
225245
226246
227247/* LUA_NUMBER */
228248/*
229** this function is quite liberal in what it accepts, as 'luaO_str2d'
249** this function is quite liberal in what it accepts, as 'luaO_str2num'
230250** will reject ill-formed numerals.
231251*/
232static void read_numeral (LexState *ls, SemInfo *seminfo) {
252static int read_numeral (LexState *ls, SemInfo *seminfo) {
253  TValue obj;
233254  const char *expo = "Ee";
234255  int first = ls->current;
235256  lua_assert(lisdigit(ls->current));
236257  save_and_next(ls);
237  if (first == '0' && check_next(ls, "Xx"))  /* hexadecimal? */
258  if (first == '0' && check_next2(ls, "xX"))  /* hexadecimal? */
238259    expo = "Pp";
239260  for (;;) {
240    if (check_next(ls, expo))  /* exponent part? */
241      check_next(ls, "+-");  /* optional exponent sign */
242    if (lisxdigit(ls->current) || ls->current == '.')
261    if (check_next2(ls, expo))  /* exponent part? */
262      check_next2(ls, "-+");  /* optional exponent sign */
263    if (lisxdigit(ls->current))
243264      save_and_next(ls);
244    else  break;
265    else if (ls->current == '.')
266      save_and_next(ls);
267    else break;
245268  }
246269  save(ls, '\0');
247270  buffreplace(ls, '.', ls->decpoint);  /* follow locale for decimal point */
248  if (!buff2d(ls->buff, &seminfo->r))  /* format error? */
249    trydecpoint(ls, seminfo); /* try to update decimal point separator */
271  if (!buff2num(ls->buff, &obj))  /* format error? */
272    trydecpoint(ls, &obj); /* try to update decimal point separator */
273  if (ttisinteger(&obj)) {
274    seminfo->i = ivalue(&obj);
275    return TK_INT;
276  }
277  else {
278    lua_assert(ttisfloat(&obj));
279    seminfo->r = fltvalue(&obj);
280    return TK_FLT;
281  }
250282}
251283
252284
r242885r242886
268300
269301
270302static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
271  save_and_next(ls);  /* skip 2nd `[' */
303  int line = ls->linenumber;  /* initial line (for error message) */
304  save_and_next(ls);  /* skip 2nd '[' */
272305  if (currIsNewline(ls))  /* string starts with a newline? */
273306    inclinenumber(ls);  /* skip it */
274307  for (;;) {
275308    switch (ls->current) {
276      case EOZ:
277        lexerror(ls, (seminfo) ? "unfinished long string" :
278                                 "unfinished long comment", TK_EOS);
309      case EOZ: {  /* error */
310        const char *what = (seminfo ? "string" : "comment");
311        const char *msg = luaO_pushfstring(ls->L,
312                     "unfinished long %s (starting at line %d)", what, line);
313        lexerror(ls, msg, TK_EOS);
279314        break;  /* to avoid warnings */
315      }
280316      case ']': {
281317        if (skip_sep(ls) == sep) {
282          save_and_next(ls);  /* skip 2nd `]' */
318          save_and_next(ls);  /* skip 2nd ']' */
283319          goto endloop;
284320        }
285321        break;
r242885r242886
302338}
303339
304340
305static void escerror (LexState *ls, int *c, int n, const char *msg) {
306  int i;
307  luaZ_resetbuffer(ls->buff);  /* prepare error message */
308  save(ls, '\\');
309  for (i = 0; i < n && c[i] != EOZ; i++)
310    save(ls, c[i]);
311  lexerror(ls, msg, TK_STRING);
341static void esccheck (LexState *ls, int c, const char *msg) {
342  if (!c) {
343    if (ls->current != EOZ)
344      save_and_next(ls);  /* add current to buffer for error message */
345    lexerror(ls, msg, TK_STRING);
346  }
312347}
313348
314349
350static int gethexa (LexState *ls) {
351  save_and_next(ls);
352  esccheck (ls, lisxdigit(ls->current), "hexadecimal digit expected");
353  return luaO_hexavalue(ls->current);
354}
355
356
315357static int readhexaesc (LexState *ls) {
316  int c[3], i;  /* keep input for error message */
317  int r = 0;  /* result accumulator */
318  c[0] = 'x';  /* for error message */
319  for (i = 1; i < 3; i++) {  /* read two hexadecimal digits */
320    c[i] = next(ls);
321    if (!lisxdigit(c[i]))
322      escerror(ls, c, i + 1, "hexadecimal digit expected");
323    r = (r << 4) + luaO_hexavalue(c[i]);
358  int r = gethexa(ls);
359  r = (r << 4) + gethexa(ls);
360  luaZ_buffremove(ls->buff, 2);  /* remove saved chars from buffer */
361  return r;
362}
363
364
365static unsigned long readutf8esc (LexState *ls) {
366  unsigned long r;
367  int i = 4;  /* chars to be removed: '\', 'u', '{', and first digit */
368  save_and_next(ls);  /* skip 'u' */
369  esccheck(ls, ls->current == '{', "missing '{'");
370  r = gethexa(ls);  /* must have at least one digit */
371  while ((save_and_next(ls), lisxdigit(ls->current))) {
372    i++;
373    r = (r << 4) + luaO_hexavalue(ls->current);
374    esccheck(ls, r <= 0x10FFFF, "UTF-8 value too large");
324375  }
376  esccheck(ls, ls->current == '}', "missing '}'");
377  next(ls);  /* skip '}' */
378  luaZ_buffremove(ls->buff, i);  /* remove saved chars from buffer */
325379  return r;
326380}
327381
328382
383static void utf8esc (LexState *ls) {
384  char buff[UTF8BUFFSZ];
385  int n = luaO_utf8esc(buff, readutf8esc(ls));
386  for (; n > 0; n--)  /* add 'buff' to string */
387    save(ls, buff[UTF8BUFFSZ - n]);
388}
389
390
329391static int readdecesc (LexState *ls) {
330  int c[3], i;
392  int i;
331393  int r = 0;  /* result accumulator */
332394  for (i = 0; i < 3 && lisdigit(ls->current); i++) {  /* read up to 3 digits */
333    c[i] = ls->current;
334    r = 10*r + c[i] - '0';
335    next(ls);
395    r = 10*r + ls->current - '0';
396    save_and_next(ls);
336397  }
337  if (r > UCHAR_MAX)
338    escerror(ls, c, i, "decimal escape too large");
398  esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
399  luaZ_buffremove(ls->buff, i);  /* remove read digits from buffer */
339400  return r;
340401}
341402
r242885r242886
353414        break;  /* to avoid warnings */
354415      case '\\': {  /* escape sequences */
355416        int c;  /* final character to be saved */
356        next(ls);  /* do not save the `\' */
417        save_and_next(ls);  /* keep '\\' for error messages */
357418        switch (ls->current) {
358419          case 'a': c = '\a'; goto read_save;
359420          case 'b': c = '\b'; goto read_save;
r242885r242886
363424          case 't': c = '\t'; goto read_save;
364425          case 'v': c = '\v'; goto read_save;
365426          case 'x': c = readhexaesc(ls); goto read_save;
427          case 'u': utf8esc(ls);  goto no_save;
366428          case '\n': case '\r':
367429            inclinenumber(ls); c = '\n'; goto only_save;
368430          case '\\': case '\"': case '\'':
369431            c = ls->current; goto read_save;
370432          case EOZ: goto no_save;  /* will raise an error next loop */
371433          case 'z': {  /* zap following span of spaces */
434            luaZ_buffremove(ls->buff, 1);  /* remove '\\' */
372435            next(ls);  /* skip the 'z' */
373436            while (lisspace(ls->current)) {
374437              if (currIsNewline(ls)) inclinenumber(ls);
r242885r242886
377440            goto no_save;
378441          }
379442          default: {
380            if (!lisdigit(ls->current))
381              escerror(ls, &ls->current, 1, "invalid escape sequence");
382            /* digital escape \ddd */
383            c = readdecesc(ls);
443            esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
444            c = readdecesc(ls);  /* digital escape '\ddd' */
384445            goto only_save;
385446          }
386447        }
387       read_save: next(ls);  /* read next character */
388       only_save: save(ls, c);  /* save 'c' */
448       read_save:
449         next(ls);
450         /* go through */
451       only_save:
452         luaZ_buffremove(ls->buff, 1);  /* remove '\\' */
453         save(ls, c);
454         /* go through */
389455       no_save: break;
390456      }
391457      default:
r242885r242886
417483        next(ls);
418484        if (ls->current == '[') {  /* long comment? */
419485          int sep = skip_sep(ls);
420          luaZ_resetbuffer(ls->buff);  /* `skip_sep' may dirty the buffer */
486          luaZ_resetbuffer(ls->buff);  /* 'skip_sep' may dirty the buffer */
421487          if (sep >= 0) {
422488            read_long_string(ls, NULL, sep);  /* skip long comment */
423489            luaZ_resetbuffer(ls->buff);  /* previous call may dirty the buff. */
r242885r242886
440506      }
441507      case '=': {
442508        next(ls);
443        if (ls->current != '=') return '=';
444        else { next(ls); return TK_EQ; }
509        if (check_next1(ls, '=')) return TK_EQ;
510        else return '=';
445511      }
446512      case '<': {
447513        next(ls);
448        if (ls->current != '=') return '<';
449        else { next(ls); return TK_LE; }
514        if (check_next1(ls, '=')) return TK_LE;
515        else if (check_next1(ls, '<')) return TK_SHL;
516        else return '<';
450517      }
451518      case '>': {
452519        next(ls);
453        if (ls->current != '=') return '>';
454        else { next(ls); return TK_GE; }
520        if (check_next1(ls, '=')) return TK_GE;
521        else if (check_next1(ls, '>')) return TK_SHR;
522        else return '>';
455523      }
524      case '/': {
525        next(ls);
526        if (check_next1(ls, '/')) return TK_IDIV;
527        else return '/';
528      }
456529      case '~': {
457530        next(ls);
458        if (ls->current != '=') return '~';
459        else { next(ls); return TK_NE; }
531        if (check_next1(ls, '=')) return TK_NE;
532        else return '~';
460533      }
461534      case ':': {
462535        next(ls);
463        if (ls->current != ':') return ':';
464        else { next(ls); return TK_DBCOLON; }
536        if (check_next1(ls, ':')) return TK_DBCOLON;
537        else return ':';
465538      }
466539      case '"': case '\'': {  /* short literal strings */
467540        read_string(ls, ls->current, seminfo);
r242885r242886
469542      }
470543      case '.': {  /* '.', '..', '...', or number */
471544        save_and_next(ls);
472        if (check_next(ls, ".")) {
473          if (check_next(ls, "."))
545        if (check_next1(ls, '.')) {
546          if (check_next1(ls, '.'))
474547            return TK_DOTS;   /* '...' */
475548          else return TK_CONCAT;   /* '..' */
476549        }
477550        else if (!lisdigit(ls->current)) return '.';
478        /* else go through */
551        else return read_numeral(ls, seminfo);
479552      }
480553      case '0': case '1': case '2': case '3': case '4':
481554      case '5': case '6': case '7': case '8': case '9': {
482        read_numeral(ls, seminfo);
483        return TK_NUMBER;
555        return read_numeral(ls, seminfo);
484556      }
485557      case EOZ: {
486558        return TK_EOS;
r242885r242886
495567                                  luaZ_bufflen(ls->buff));
496568          seminfo->ts = ts;
497569          if (isreserved(ts))  /* reserved word? */
498            return ts->tsv.extra - 1 + FIRST_RESERVED;
570            return ts->extra - 1 + FIRST_RESERVED;
499571          else {
500572            return TK_NAME;
501573          }
trunk/3rdparty/lua/src/llex.h
r242885r242886
11/*
2** $Id: llex.h,v 1.72.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: llex.h,v 1.78 2014/10/29 15:38:24 roberto Exp $
33** Lexical Analyzer
44** See Copyright Notice in lua.h
55*/
r242885r242886
1414#define FIRST_RESERVED   257
1515
1616
17#if !defined(LUA_ENV)
18#define LUA_ENV      "_ENV"
19#endif
1720
21
1822/*
1923* WARNING: if you change the order of this enumeration,
2024* grep "ORDER RESERVED"
r242885r242886
2630  TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
2731  TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
2832  /* other terminal symbols */
29  TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_DBCOLON, TK_EOS,
30  TK_NUMBER, TK_NAME, TK_STRING
33  TK_IDIV, TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE,
34  TK_SHL, TK_SHR,
35  TK_DBCOLON, TK_EOS,
36  TK_FLT, TK_INT, TK_NAME, TK_STRING
3137};
3238
3339/* number of reserved words */
r242885r242886
3642
3743typedef union {
3844  lua_Number r;
45  lua_Integer i;
3946  TString *ts;
4047} SemInfo;  /* semantics information */
4148
r242885r242886
5158typedef struct LexState {
5259  int current;  /* current character (charint) */
5360  int linenumber;  /* input line counter */
54  int lastline;  /* line of last token `consumed' */
61  int lastline;  /* line of last token 'consumed' */
5562  Token t;  /* current token */
5663  Token lookahead;  /* look ahead token */
5764  struct FuncState *fs;  /* current function (parser) */
5865  struct lua_State *L;
5966  ZIO *z;  /* input stream */
6067  Mbuffer *buff;  /* buffer for tokens */
68  Table *h;  /* to avoid collection/reuse strings */
6169  struct Dyndata *dyd;  /* dynamic structures used by the parser */
6270  TString *source;  /* current source name */
6371  TString *envn;  /* environment variable name */
trunk/3rdparty/lua/src/llimits.h
r242885r242886
11/*
2** $Id: llimits.h,v 1.103.1.1 2013/04/12 18:48:47 roberto Exp $
3** Limits, basic types, and some other `installation-dependent' definitions
2** $Id: llimits.h,v 1.125 2014/12/19 13:30:23 roberto Exp $
3** Limits, basic types, and some other 'installation-dependent' definitions
44** See Copyright Notice in lua.h
55*/
66
r242885r242886
1414
1515#include "lua.h"
1616
17
18typedef unsigned LUA_INT32 lu_int32;
19
17/*
18** 'lu_mem' and 'l_mem' are unsigned/signed integers big enough to count
19** the total memory used by Lua (in bytes). Usually, 'size_t' and
20** 'ptrdiff_t' should work, but we use 'long' for 16-bit machines.
21*/
22#if defined(LUAI_MEM)      /* { external definitions? */
2023typedef LUAI_UMEM lu_mem;
21
2224typedef LUAI_MEM l_mem;
25#elif LUAI_BITSINT >= 32   /* }{ */
26typedef size_t lu_mem;
27typedef ptrdiff_t l_mem;
28#else  /* 16-bit ints */   /* }{ */
29typedef unsigned long lu_mem;
30typedef long l_mem;
31#endif            /* } */
2332
2433
25
26/* chars used as small naturals (so that `char' is reserved for characters) */
34/* chars used as small naturals (so that 'char' is reserved for characters) */
2735typedef unsigned char lu_byte;
2836
2937
30#define MAX_SIZET   ((size_t)(~(size_t)0)-2)
38/* maximum value for size_t */
39#define MAX_SIZET   ((size_t)(~(size_t)0))
3140
32#define MAX_LUMEM   ((lu_mem)(~(lu_mem)0)-2)
41/* maximum size visible for Lua (must be representable in a lua_Integer */
42#define MAX_SIZE   (sizeof(size_t) < sizeof(lua_Integer) ? MAX_SIZET \
43                          : (size_t)(LUA_MAXINTEGER))
3344
34#define MAX_LMEM   ((l_mem) ((MAX_LUMEM >> 1) - 2))
3545
46#define MAX_LUMEM   ((lu_mem)(~(lu_mem)0))
3647
37#define MAX_INT (INT_MAX-2)  /* maximum value of an int (-2 for safety) */
48#define MAX_LMEM   ((l_mem)(MAX_LUMEM >> 1))
3849
50
51#define MAX_INT      INT_MAX  /* maximum value of an int */
52
53
3954/*
40** conversion of pointer to integer
55** conversion of pointer to integer:
4156** this is for hashing only; there is no problem if the integer
4257** cannot hold the whole pointer value
4358*/
44#define IntPoint(p)  ((unsigned int)(lu_mem)(p))
59#define point2int(p)   ((unsigned int)((size_t)(p) & UINT_MAX))
4560
4661
4762
4863/* type to ensure maximum alignment */
49#if !defined(LUAI_USER_ALIGNMENT_T)
50#define LUAI_USER_ALIGNMENT_T   union { double u; void *s; long l; }
64#if defined(LUAI_USER_ALIGNMENT_T)
65typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
66#else
67typedef union { double u; void *s; lua_Integer i; long l; } L_Umaxalign;
5168#endif
5269
53typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
5470
5571
56/* result of a `usual argument conversion' over lua_Number */
72/* types of 'usual argument conversions' for lua_Number and lua_Integer */
5773typedef LUAI_UACNUMBER l_uacNumber;
74typedef LUAI_UACINT l_uacInt;
5875
5976
6077/* internal assertions for in-house debugging */
r242885r242886
7188/*
7289** assertion for checking API calls
7390*/
74#if !defined(luai_apicheck)
75
7691#if defined(LUA_USE_APICHECK)
7792#include <assert.h>
78#define luai_apicheck(L,e)   assert(e)
93#define luai_apicheck(e)   assert(e)
7994#else
80#define luai_apicheck(L,e)   lua_assert(e)
95#define luai_apicheck(e)   lua_assert(e)
8196#endif
8297
83#endif
8498
85#define api_check(l,e,msg)   luai_apicheck(l,(e) && msg)
99#define api_check(e,msg)   luai_apicheck((e) && msg)
86100
87101
88102#if !defined(UNUSED)
r242885r242886
92106
93107#define cast(t, exp)   ((t)(exp))
94108
109#define cast_void(i)   cast(void, (i))
95110#define cast_byte(i)   cast(lu_byte, (i))
96111#define cast_num(i)   cast(lua_Number, (i))
97112#define cast_int(i)   cast(int, (i))
98113#define cast_uchar(i)   cast(unsigned char, (i))
99114
100115
116/* cast a signed lua_Integer to lua_Unsigned */
117#if !defined(l_castS2U)
118#define l_castS2U(i)   ((lua_Unsigned)(i))
119#endif
120
101121/*
122** cast a lua_Unsigned to a signed lua_Integer; this cast is
123** not strict ISO C, but two-complement architectures should
124** work fine.
125*/
126#if !defined(l_castU2S)
127#define l_castU2S(i)   ((lua_Integer)(i))
128#endif
129
130
131/*
102132** non-return type
103133*/
104134#if defined(__GNUC__)
105135#define l_noret      void __attribute__((noreturn))
106#elif defined(_MSC_VER)
136#elif defined(_MSC_VER) && _MSC_VER >= 1200
107137#define l_noret      void __declspec(noreturn)
108138#else
109139#define l_noret      void
r242885r242886
127157
128158
129159/*
130** type for virtual-machine instructions
160** type for virtual-machine instructions;
131161** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
132162*/
133typedef lu_int32 Instruction;
163#if LUAI_BITSINT >= 32
164typedef unsigned int Instruction;
165#else
166typedef unsigned long Instruction;
167#endif
134168
135169
136170
137/* maximum stack for a Lua function */
138#define MAXSTACK   250
139171
140
141
142172/* minimum size for the string table (must be power of 2) */
143173#if !defined(MINSTRTABSIZE)
144#define MINSTRTABSIZE   32
174#define MINSTRTABSIZE   64   /* minimum size for "predefined" strings */
145175#endif
146176
147177
r242885r242886
152182
153183
154184#if !defined(lua_lock)
155#define lua_lock(L)     ((void) 0)
156#define lua_unlock(L)   ((void) 0)
185#define lua_lock(L)   ((void) 0)
186#define lua_unlock(L)   ((void) 0)
157187#endif
158188
159189#if !defined(luai_threadyield)
160#define luai_threadyield(L)     {lua_unlock(L); lua_lock(L);}
190#define luai_threadyield(L)   {lua_unlock(L); lua_lock(L);}
161191#endif
162192
163193
r242885r242886
183213#endif
184214
185215#if !defined(luai_userstateresume)
186#define luai_userstateresume(L,n)       ((void)L)
216#define luai_userstateresume(L,n)   ((void)L)
187217#endif
188218
189219#if !defined(luai_userstateyield)
190#define luai_userstateyield(L,n)        ((void)L)
220#define luai_userstateyield(L,n)   ((void)L)
191221#endif
192222
193/*
194** lua_number2int is a macro to convert lua_Number to int.
195** lua_number2integer is a macro to convert lua_Number to lua_Integer.
196** lua_number2unsigned is a macro to convert a lua_Number to a lua_Unsigned.
197** lua_unsigned2number is a macro to convert a lua_Unsigned to a lua_Number.
198** luai_hashnum is a macro to hash a lua_Number value into an integer.
199** The hash must be deterministic and give reasonable values for
200** both small and large values (outside the range of integers).
201*/
202223
203#if defined(MS_ASMTRICK) || defined(LUA_MSASMTRICK)   /* { */
204/* trick with Microsoft assembler for X86 */
205224
206#define lua_number2int(i,n)  __asm {__asm fld n   __asm fistp i}
207#define lua_number2integer(i,n)      lua_number2int(i, n)
208#define lua_number2unsigned(i,n)  \
209  {__int64 l; __asm {__asm fld n   __asm fistp l} i = (unsigned int)l;}
210
211
212#elif defined(LUA_IEEE754TRICK)      /* }{ */
213/* the next trick should work on any machine using IEEE754 with
214   a 32-bit int type */
215
216union luai_Cast { double l_d; LUA_INT32 l_p[2]; };
217
218#if !defined(LUA_IEEEENDIAN)   /* { */
219#define LUAI_EXTRAIEEE   \
220  static const union luai_Cast ieeeendian = {-(33.0 + 6755399441055744.0)};
221#define LUA_IEEEENDIANLOC   (ieeeendian.l_p[1] == 33)
222#else
223#define LUA_IEEEENDIANLOC   LUA_IEEEENDIAN
224#define LUAI_EXTRAIEEE      /* empty */
225#endif            /* } */
226
227#define lua_number2int32(i,n,t) \
228  { LUAI_EXTRAIEEE \
229    volatile union luai_Cast u; u.l_d = (n) + 6755399441055744.0; \
230    (i) = (t)u.l_p[LUA_IEEEENDIANLOC]; }
231
232#define luai_hashnum(i,n)  \
233  { volatile union luai_Cast u; u.l_d = (n) + 1.0;  /* avoid -0 */ \
234    (i) = u.l_p[0]; (i) += u.l_p[1]; }  /* add double bits for his hash */
235
236#define lua_number2int(i,n)      lua_number2int32(i, n, int)
237#define lua_number2unsigned(i,n)   lua_number2int32(i, n, lua_Unsigned)
238
239/* the trick can be expanded to lua_Integer when it is a 32-bit value */
240#if defined(LUA_IEEELL)
241#define lua_number2integer(i,n)      lua_number2int32(i, n, lua_Integer)
242#endif
243
244#endif            /* } */
245
246
247/* the following definitions always work, but may be slow */
248
249#if !defined(lua_number2int)
250#define lua_number2int(i,n)   ((i)=(int)(n))
251#endif
252
253#if !defined(lua_number2integer)
254#define lua_number2integer(i,n)   ((i)=(lua_Integer)(n))
255#endif
256
257#if !defined(lua_number2unsigned)   /* { */
258/* the following definition assures proper modulo behavior */
259#if defined(LUA_NUMBER_DOUBLE) || defined(LUA_NUMBER_FLOAT)
260#include <math.h>
261#define SUPUNSIGNED   ((lua_Number)(~(lua_Unsigned)0) + 1)
262#define lua_number2unsigned(i,n)  \
263   ((i)=(lua_Unsigned)((n) - floor((n)/SUPUNSIGNED)*SUPUNSIGNED))
264#else
265#define lua_number2unsigned(i,n)   ((i)=(lua_Unsigned)(n))
266#endif
267#endif            /* } */
268
269
270#if !defined(lua_unsigned2number)
271/* on several machines, coercion from unsigned to double is slow,
272   so it may be worth to avoid */
273#define lua_unsigned2number(u)  \
274    (((u) <= (lua_Unsigned)INT_MAX) ? (lua_Number)(int)(u) : (lua_Number)(u))
275#endif
276
277
278
279#if defined(ltable_c) && !defined(luai_hashnum)
280
281#include <float.h>
282#include <math.h>
283
284#define luai_hashnum(i,n) { int e;  \
285  n = l_mathop(frexp)(n, &e) * (lua_Number)(INT_MAX - DBL_MAX_EXP);  \
286  lua_number2int(i, n); i += e; }
287
288#endif
289
290
291
292225/*
293226** macro to control inclusion of some hard tests on stack reallocation
294227*/
trunk/3rdparty/lua/src/lmathlib.c
r242885r242886
11/*
2** $Id: lmathlib.c,v 1.83.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lmathlib.c,v 1.114 2014/12/27 20:32:26 roberto Exp $
33** Standard mathematical library
44** See Copyright Notice in lua.h
55*/
66
7#define lmathlib_c
8#define LUA_LIB
79
10#include "lprefix.h"
11
12
813#include <stdlib.h>
914#include <math.h>
1015
11#define lmathlib_c
12#define LUA_LIB
13
1416#include "lua.h"
1517
1618#include "lauxlib.h"
r242885r242886
1820
1921
2022#undef PI
21#define PI   ((lua_Number)(3.1415926535897932384626433832795))
22#define RADIANS_PER_DEGREE   ((lua_Number)(PI/180.0))
23#define PI   (l_mathop(3.141592653589793238462643383279502884))
2324
2425
26#if !defined(l_rand)      /* { */
27#if defined(LUA_USE_POSIX)
28#define l_rand()   random()
29#define l_srand(x)   srandom(x)
30#define L_RANDMAX   2147483647   /* (2^31 - 1), following POSIX */
31#else
32#define l_rand()   rand()
33#define l_srand(x)   srand(x)
34#define L_RANDMAX   RAND_MAX
35#endif
36#endif            /* } */
2537
38
2639static int math_abs (lua_State *L) {
27  lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
40  if (lua_isinteger(L, 1)) {
41    lua_Integer n = lua_tointeger(L, 1);
42    if (n < 0) n = (lua_Integer)(0u - n);
43    lua_pushinteger(L, n);
44  }
45  else
46    lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
2847  return 1;
2948}
3049
r242885r242886
3352  return 1;
3453}
3554
36static int math_sinh (lua_State *L) {
37  lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
38  return 1;
39}
40
4155static int math_cos (lua_State *L) {
4256  lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));
4357  return 1;
4458}
4559
46static int math_cosh (lua_State *L) {
47  lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
48  return 1;
49}
50
5160static int math_tan (lua_State *L) {
5261  lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));
5362  return 1;
5463}
5564
56static int math_tanh (lua_State *L) {
57  lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
58  return 1;
59}
60
6165static int math_asin (lua_State *L) {
6266  lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));
6367  return 1;
r242885r242886
6973}
7074
7175static int math_atan (lua_State *L) {
72  lua_pushnumber(L, l_mathop(atan)(luaL_checknumber(L, 1)));
76  lua_Number y = luaL_checknumber(L, 1);
77  lua_Number x = luaL_optnumber(L, 2, 1);
78  lua_pushnumber(L, l_mathop(atan2)(y, x));
7379  return 1;
7480}
7581
76static int math_atan2 (lua_State *L) {
77  lua_pushnumber(L, l_mathop(atan2)(luaL_checknumber(L, 1),
78                                luaL_checknumber(L, 2)));
82
83static int math_toint (lua_State *L) {
84  int valid;
85  lua_Integer n = lua_tointegerx(L, 1, &valid);
86  if (valid)
87    lua_pushinteger(L, n);
88  else {
89    luaL_checkany(L, 1);
90    lua_pushnil(L);  /* value is not convertible to integer */
91  }
7992  return 1;
8093}
8194
82static int math_ceil (lua_State *L) {
83  lua_pushnumber(L, l_mathop(ceil)(luaL_checknumber(L, 1)));
84  return 1;
95
96static void pushnumint (lua_State *L, lua_Number d) {
97  lua_Integer n;
98  if (lua_numbertointeger(d, &n))  /* does 'd' fit in an integer? */
99    lua_pushinteger(L, n);  /* result is integer */
100  else
101    lua_pushnumber(L, d);  /* result is float */
85102}
86103
104
87105static int math_floor (lua_State *L) {
88  lua_pushnumber(L, l_mathop(floor)(luaL_checknumber(L, 1)));
106  if (lua_isinteger(L, 1))
107    lua_settop(L, 1);  /* integer is its own floor */
108  else {
109    lua_Number d = l_mathop(floor)(luaL_checknumber(L, 1));
110    pushnumint(L, d);
111  }
89112  return 1;
90113}
91114
115
116static int math_ceil (lua_State *L) {
117  if (lua_isinteger(L, 1))
118    lua_settop(L, 1);  /* integer is its own ceil */
119  else {
120    lua_Number d = l_mathop(ceil)(luaL_checknumber(L, 1));
121    pushnumint(L, d);
122  }
123  return 1;
124}
125
126
92127static int math_fmod (lua_State *L) {
93  lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
94                               luaL_checknumber(L, 2)));
128  if (lua_isinteger(L, 1) && lua_isinteger(L, 2)) {
129    lua_Integer d = lua_tointeger(L, 2);
130    if ((lua_Unsigned)d + 1u <= 1u) {  /* special cases: -1 or 0 */
131      luaL_argcheck(L, d != 0, 2, "zero");
132      lua_pushinteger(L, 0);  /* avoid overflow with 0x80000... / -1 */
133    }
134    else
135      lua_pushinteger(L, lua_tointeger(L, 1) % d);
136  }
137  else
138    lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
139                                     luaL_checknumber(L, 2)));
95140  return 1;
96141}
97142
143
144/*
145** next function does not use 'modf', avoiding problems with 'double*'
146** (which is not compatible with 'float*') when lua_Number is not
147** 'double'.
148*/
98149static int math_modf (lua_State *L) {
99  lua_Number ip;
100  lua_Number fp = l_mathop(modf)(luaL_checknumber(L, 1), &ip);
101  lua_pushnumber(L, ip);
102  lua_pushnumber(L, fp);
150  if (lua_isinteger(L ,1)) {
151    lua_settop(L, 1);  /* number is its own integer part */
152    lua_pushnumber(L, 0);  /* no fractional part */
153  }
154  else {
155    lua_Number n = luaL_checknumber(L, 1);
156    /* integer part (rounds toward zero) */
157    lua_Number ip = (n < 0) ? l_mathop(ceil)(n) : l_mathop(floor)(n);
158    pushnumint(L, ip);
159    /* fractional part (test needed for inf/-inf) */
160    lua_pushnumber(L, (n == ip) ? l_mathop(0.0) : (n - ip));
161  }
103162  return 2;
104163}
105164
165
106166static int math_sqrt (lua_State *L) {
107167  lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));
108168  return 1;
109169}
110170
111static int math_pow (lua_State *L) {
112  lua_Number x = luaL_checknumber(L, 1);
113  lua_Number y = luaL_checknumber(L, 2);
114  lua_pushnumber(L, l_mathop(pow)(x, y));
171
172static int math_ult (lua_State *L) {
173  lua_Integer a = luaL_checkinteger(L, 1);
174  lua_Integer b = luaL_checkinteger(L, 2);
175  lua_pushboolean(L, (lua_Unsigned)a < (lua_Unsigned)b);
115176  return 1;
116177}
117178
r242885r242886
122183    res = l_mathop(log)(x);
123184  else {
124185    lua_Number base = luaL_checknumber(L, 2);
125    if (base == (lua_Number)10.0) res = l_mathop(log10)(x);
186    if (base == 10.0) res = l_mathop(log10)(x);
126187    else res = l_mathop(log)(x)/l_mathop(log)(base);
127188  }
128189  lua_pushnumber(L, res);
129190  return 1;
130191}
131192
132#if defined(LUA_COMPAT_LOG10)
133static int math_log10 (lua_State *L) {
134  lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
135  return 1;
136}
137#endif
138
139193static int math_exp (lua_State *L) {
140194  lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));
141195  return 1;
142196}
143197
144198static int math_deg (lua_State *L) {
145  lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE);
199  lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
146200  return 1;
147201}
148202
149203static int math_rad (lua_State *L) {
150  lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE);
204  lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
151205  return 1;
152206}
153207
154static int math_frexp (lua_State *L) {
155  int e;
156  lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));
157  lua_pushinteger(L, e);
158  return 2;
159}
160208
161static int math_ldexp (lua_State *L) {
162  lua_Number x = luaL_checknumber(L, 1);
163  int ep = luaL_checkint(L, 2);
164  lua_pushnumber(L, l_mathop(ldexp)(x, ep));
165  return 1;
166}
167
168
169
170209static int math_min (lua_State *L) {
171210  int n = lua_gettop(L);  /* number of arguments */
172  lua_Number dmin = luaL_checknumber(L, 1);
211  int imin = 1;  /* index of current minimum value */
173212  int i;
174  for (i=2; i<=n; i++) {
175    lua_Number d = luaL_checknumber(L, i);
176    if (d < dmin)
177      dmin = d;
213  luaL_argcheck(L, n >= 1, 1, "value expected");
214  for (i = 2; i <= n; i++) {
215    if (lua_compare(L, i, imin, LUA_OPLT))
216      imin = i;
178217  }
179  lua_pushnumber(L, dmin);
218  lua_pushvalue(L, imin);
180219  return 1;
181220}
182221
183222
184223static int math_max (lua_State *L) {
185224  int n = lua_gettop(L);  /* number of arguments */
186  lua_Number dmax = luaL_checknumber(L, 1);
225  int imax = 1;  /* index of current maximum value */
187226  int i;
188  for (i=2; i<=n; i++) {
189    lua_Number d = luaL_checknumber(L, i);
190    if (d > dmax)
191      dmax = d;
227  luaL_argcheck(L, n >= 1, 1, "value expected");
228  for (i = 2; i <= n; i++) {
229    if (lua_compare(L, imax, i, LUA_OPLT))
230      imax = i;
192231  }
193  lua_pushnumber(L, dmax);
232  lua_pushvalue(L, imax);
194233  return 1;
195234}
196235
197
236/*
237** This function uses 'double' (instead of 'lua_Number') to ensure that
238** all bits from 'l_rand' can be represented, and that 'RANDMAX + 1.0'
239** will keep full precision (ensuring that 'r' is always less than 1.0.)
240*/
198241static int math_random (lua_State *L) {
199  /* the `%' avoids the (rare) case of r==1, and is needed also because on
200     some systems (SunOS!) `rand()' may return a value larger than RAND_MAX */
201  lua_Number r = (lua_Number)(rand()%RAND_MAX) / (lua_Number)RAND_MAX;
242  lua_Integer low, up;
243  double r = (double)l_rand() * (1.0 / ((double)L_RANDMAX + 1.0));
202244  switch (lua_gettop(L)) {  /* check number of arguments */
203245    case 0: {  /* no arguments */
204      lua_pushnumber(L, r);  /* Number between 0 and 1 */
205      break;
246      lua_pushnumber(L, (lua_Number)r);  /* Number between 0 and 1 */
247      return 1;
206248    }
207249    case 1: {  /* only upper limit */
208      lua_Number u = luaL_checknumber(L, 1);
209      luaL_argcheck(L, (lua_Number)1.0 <= u, 1, "interval is empty");
210      lua_pushnumber(L, l_mathop(floor)(r*u) + (lua_Number)(1.0));  /* [1, u] */
250      low = 1;
251      up = luaL_checkinteger(L, 1);
211252      break;
212253    }
213254    case 2: {  /* lower and upper limits */
214      lua_Number l = luaL_checknumber(L, 1);
215      lua_Number u = luaL_checknumber(L, 2);
216      luaL_argcheck(L, l <= u, 2, "interval is empty");
217      lua_pushnumber(L, l_mathop(floor)(r*(u-l+1)) + l);  /* [l, u] */
255      low = luaL_checkinteger(L, 1);
256      up = luaL_checkinteger(L, 2);
218257      break;
219258    }
220259    default: return luaL_error(L, "wrong number of arguments");
221260  }
261  /* random integer in the interval [low, up] */
262  luaL_argcheck(L, low <= up, 1, "interval is empty");
263  luaL_argcheck(L, low >= 0 || up <= LUA_MAXINTEGER + low, 1,
264                   "interval too large");
265  r *= (double)(up - low) + 1.0;
266  lua_pushinteger(L, (lua_Integer)r + low);
222267  return 1;
223268}
224269
225270
226271static int math_randomseed (lua_State *L) {
227  srand(luaL_checkunsigned(L, 1));
272  l_srand((unsigned int)(lua_Integer)luaL_checknumber(L, 1));
228273  (void)rand(); /* discard first value to avoid undesirable correlations */
229274  return 0;
230275}
231276
232277
278static int math_type (lua_State *L) {
279  if (lua_type(L, 1) == LUA_TNUMBER) {
280      if (lua_isinteger(L, 1))
281        lua_pushliteral(L, "integer");
282      else
283        lua_pushliteral(L, "float");
284  }
285  else {
286    luaL_checkany(L, 1);
287    lua_pushnil(L);
288  }
289  return 1;
290}
291
292
293/*
294** {==================================================================
295** Deprecated functions (for compatibility only)
296** ===================================================================
297*/
298#if defined(LUA_COMPAT_MATHLIB)
299
300static int math_cosh (lua_State *L) {
301  lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
302  return 1;
303}
304
305static int math_sinh (lua_State *L) {
306  lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
307  return 1;
308}
309
310static int math_tanh (lua_State *L) {
311  lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
312  return 1;
313}
314
315static int math_pow (lua_State *L) {
316  lua_Number x = luaL_checknumber(L, 1);
317  lua_Number y = luaL_checknumber(L, 2);
318  lua_pushnumber(L, l_mathop(pow)(x, y));
319  return 1;
320}
321
322static int math_frexp (lua_State *L) {
323  int e;
324  lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));
325  lua_pushinteger(L, e);
326  return 2;
327}
328
329static int math_ldexp (lua_State *L) {
330  lua_Number x = luaL_checknumber(L, 1);
331  int ep = (int)luaL_checkinteger(L, 2);
332  lua_pushnumber(L, l_mathop(ldexp)(x, ep));
333  return 1;
334}
335
336static int math_log10 (lua_State *L) {
337  lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
338  return 1;
339}
340
341#endif
342/* }================================================================== */
343
344
345
233346static const luaL_Reg mathlib[] = {
234347  {"abs",   math_abs},
235348  {"acos",  math_acos},
236349  {"asin",  math_asin},
237  {"atan2", math_atan2},
238350  {"atan",  math_atan},
239351  {"ceil",  math_ceil},
240  {"cosh",   math_cosh},
241352  {"cos",   math_cos},
242353  {"deg",   math_deg},
243354  {"exp",   math_exp},
355  {"tointeger", math_toint},
244356  {"floor", math_floor},
245357  {"fmod",   math_fmod},
246  {"frexp", math_frexp},
247  {"ldexp", math_ldexp},
248#if defined(LUA_COMPAT_LOG10)
249  {"log10", math_log10},
250#endif
358  {"ult",   math_ult},
251359  {"log",   math_log},
252360  {"max",   math_max},
253361  {"min",   math_min},
254362  {"modf",   math_modf},
255  {"pow",   math_pow},
256363  {"rad",   math_rad},
257364  {"random",     math_random},
258365  {"randomseed", math_randomseed},
259  {"sinh",   math_sinh},
260366  {"sin",   math_sin},
261367  {"sqrt",  math_sqrt},
368  {"tan",   math_tan},
369  {"type", math_type},
370#if defined(LUA_COMPAT_MATHLIB)
371  {"atan2", math_atan},
372  {"cosh",   math_cosh},
373  {"sinh",   math_sinh},
262374  {"tanh",   math_tanh},
263  {"tan",   math_tan},
375  {"pow",   math_pow},
376  {"frexp", math_frexp},
377  {"ldexp", math_ldexp},
378  {"log10", math_log10},
379#endif
380  /* placeholders */
381  {"pi", NULL},
382  {"huge", NULL},
383  {"maxinteger", NULL},
384  {"mininteger", NULL},
264385  {NULL, NULL}
265386};
266387
r242885r242886
272393  luaL_newlib(L, mathlib);
273394  lua_pushnumber(L, PI);
274395  lua_setfield(L, -2, "pi");
275  lua_pushnumber(L, HUGE_VAL);
396  lua_pushnumber(L, (lua_Number)HUGE_VAL);
276397  lua_setfield(L, -2, "huge");
398  lua_pushinteger(L, LUA_MAXINTEGER);
399  lua_setfield(L, -2, "maxinteger");
400  lua_pushinteger(L, LUA_MININTEGER);
401  lua_setfield(L, -2, "mininteger");
277402  return 1;
278403}
279404
trunk/3rdparty/lua/src/lmem.c
r242885r242886
11/*
2** $Id: lmem.c,v 1.84.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lmem.c,v 1.89 2014/11/02 19:33:33 roberto Exp $
33** Interface to Memory Manager
44** See Copyright Notice in lua.h
55*/
66
7#define lmem_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <stddef.h>
914
10#define lmem_c
11#define LUA_CORE
12
1315#include "lua.h"
1416
1517#include "ldebug.h"
r242885r242886
2426/*
2527** About the realloc function:
2628** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
27** (`osize' is the old size, `nsize' is the new size)
29** ('osize' is the old size, 'nsize' is the new size)
2830**
29** * frealloc(ud, NULL, x, s) creates a new block of size `s' (no
31** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no
3032** matter 'x').
3133**
32** * frealloc(ud, p, x, 0) frees the block `p'
34** * frealloc(ud, p, x, 0) frees the block 'p'
3335** (in this specific case, frealloc must return NULL);
3436** particularly, frealloc(ud, NULL, 0, 0) does nothing
35** (which is equivalent to free(NULL) in ANSI C)
37** (which is equivalent to free(NULL) in ISO C)
3638**
3739** frealloc returns NULL if it cannot create or reallocate the area
3840** (any reallocation to an equal or smaller size cannot fail!)
r242885r242886
8385#endif
8486  newblock = (*g->frealloc)(g->ud, block, osize, nsize);
8587  if (newblock == NULL && nsize > 0) {
86    api_check(L, nsize > realosize,
88    api_check( nsize > realosize,
8789                 "realloc cannot fail when shrinking a block");
88    if (g->gcrunning) {
89      luaC_fullgc(L, 1);  /* try to free some memory... */
90      newblock = (*g->frealloc)(g->ud, block, osize, nsize);  /* try again */
91    }
90    luaC_fullgc(L, 1);  /* try to free some memory... */
91    newblock = (*g->frealloc)(g->ud, block, osize, nsize);  /* try again */
9292    if (newblock == NULL)
9393      luaD_throw(L, LUA_ERRMEM);
9494  }
trunk/3rdparty/lua/src/lmem.h
r242885r242886
11/*
2** $Id: lmem.h,v 1.40.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lmem.h,v 1.43 2014/12/19 17:26:14 roberto Exp $
33** Interface to Memory Manager
44** See Copyright Notice in lua.h
55*/
r242885r242886
1515
1616
1717/*
18** This macro avoids the runtime division MAX_SIZET/(e), as 'e' is
19** always constant.
20** The macro is somewhat complex to avoid warnings:
21** +1 avoids warnings of "comparison has constant result";
22** cast to 'void' avoids warnings of "value unused".
18** This macro reallocs a vector 'b' from 'on' to 'n' elements, where
19** each element has size 'e'. In case of arithmetic overflow of the
20** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because
21** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e).
22**
23** (The macro is somewhat complex to avoid warnings:  The 'sizeof'
24** comparison avoids a runtime comparison when overflow cannot occur.
25** The compiler should be able to optimize the real test by itself, but
26** when it does it, it may give a warning about "comparison is always
27** false due to limited range of data type"; the +1 tricks the compiler,
28** avoiding this warning but also this optimization.)
2329*/
2430#define luaM_reallocv(L,b,on,n,e) \
25  (cast(void, \
26     (cast(size_t, (n)+1) > MAX_SIZET/(e)) ? (luaM_toobig(L), 0) : 0), \
31  (((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \
32      ? luaM_toobig(L) : cast_void(0)) , \
2733   luaM_realloc_(L, (b), (on)*(e), (n)*(e)))
2834
35/*
36** Arrays of chars do not need any test
37*/
38#define luaM_reallocvchar(L,b,on,n)  \
39    cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))
40
2941#define luaM_freemem(L, b, s)   luaM_realloc_(L, (b), (s), 0)
3042#define luaM_free(L, b)      luaM_realloc_(L, (b), sizeof(*(b)), 0)
31#define luaM_freearray(L, b, n)   luaM_reallocv(L, (b), n, 0, sizeof((b)[0]))
43#define luaM_freearray(L, b, n)   luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0)
3244
3345#define luaM_malloc(L,s)   luaM_realloc_(L, NULL, 0, (s))
3446#define luaM_new(L,t)      cast(t *, luaM_malloc(L, sizeof(t)))
trunk/3rdparty/lua/src/loadlib.c
r242885r242886
11/*
2** $Id: loadlib.c,v 1.111.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: loadlib.c,v 1.124 2015/01/05 13:51:39 roberto Exp $
33** Dynamic library loader for Lua
44** See Copyright Notice in lua.h
55**
r242885r242886
88** systems.
99*/
1010
11#define loadlib_c
12#define LUA_LIB
1113
12/*
13** if needed, includes windows header before everything else
14*/
15#if defined(_WIN32)
16#include <windows.h>
17#endif
14#include "lprefix.h"
1815
1916
2017#include <stdlib.h>
2118#include <string.h>
2219
23
24#define loadlib_c
25#define LUA_LIB
26
2720#include "lua.h"
2821
2922#include "lauxlib.h"
r242885r242886
3124
3225
3326/*
34** LUA_PATH and LUA_CPATH are the names of the environment
27** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
3528** variables that Lua check to set its paths.
3629*/
37#if !defined(LUA_PATH)
38#define LUA_PATH   "LUA_PATH"
30#if !defined(LUA_PATH_VAR)
31#define LUA_PATH_VAR   "LUA_PATH"
3932#endif
4033
41#if !defined(LUA_CPATH)
42#define LUA_CPATH   "LUA_CPATH"
34#if !defined(LUA_CPATH_VAR)
35#define LUA_CPATH_VAR   "LUA_CPATH"
4336#endif
4437
4538#define LUA_PATHSUFFIX      "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
4639
47#define LUA_PATHVERSION      LUA_PATH LUA_PATHSUFFIX
48#define LUA_CPATHVERSION   LUA_CPATH LUA_PATHSUFFIX
40#define LUA_PATHVARVERSION      LUA_PATH_VAR LUA_PATHSUFFIX
41#define LUA_CPATHVARVERSION      LUA_CPATH_VAR LUA_PATHSUFFIX
4942
5043/*
5144** LUA_PATH_SEP is the character that separates templates in a path.
r242885r242886
9285#define LUA_OFSEP   "_"
9386
9487
95/* table (in the registry) that keeps handles for all loaded C libraries */
96#define CLIBS      "_CLIBS"
88/*
89** unique key for table in the registry that keeps handles
90** for all loaded C libraries
91*/
92static const int CLIBS = 0;
9793
9894#define LIB_FAIL   "open"
9995
100
101/* error codes for ll_loadfunc */
102#define ERRLIB      1
103#define ERRFUNC      2
104
10596#define setprogdir(L)      ((void)0)
10697
10798
10899/*
109100** system-dependent functions
110101*/
111static void ll_unloadlib (void *lib);
112static void *ll_load (lua_State *L, const char *path, int seeglb);
113static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
114102
103/*
104** unload library 'lib'
105*/
106static void lsys_unloadlib (void *lib);
115107
108/*
109** load C library in file 'path'. If 'seeglb', load with all names in
110** the library global.
111** Returns the library; in case of error, returns NULL plus an
112** error string in the stack.
113*/
114static void *lsys_load (lua_State *L, const char *path, int seeglb);
116115
117#if defined(LUA_USE_DLOPEN)
118116/*
117** Try to find a function named 'sym' in library 'lib'.
118** Returns the function; in case of error, returns NULL plus an
119** error string in the stack.
120*/
121static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);
122
123
124
125
126#if defined(LUA_USE_DLOPEN)   /* { */
127/*
119128** {========================================================================
120129** This is an implementation of loadlib based on the dlfcn interface.
121130** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
r242885r242886
126135
127136#include <dlfcn.h>
128137
129static void ll_unloadlib (void *lib) {
138/*
139** Macro to covert pointer to void* to pointer to function. This cast
140** is undefined according to ISO C, but POSIX assumes that it must work.
141** (The '__extension__' in gnu compilers is only to avoid warnings.)
142*/
143#if defined(__GNUC__)
144#define cast_func(p) (__extension__ (lua_CFunction)(p))
145#else
146#define cast_func(p) ((lua_CFunction)(p))
147#endif
148
149
150static void lsys_unloadlib (void *lib) {
130151  dlclose(lib);
131152}
132153
133154
134static void *ll_load (lua_State *L, const char *path, int seeglb) {
155static void *lsys_load (lua_State *L, const char *path, int seeglb) {
135156  void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
136157  if (lib == NULL) lua_pushstring(L, dlerror());
137158  return lib;
138159}
139160
140161
141static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
142  lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
162static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
163  lua_CFunction f = cast_func(dlsym(lib, sym));
143164  if (f == NULL) lua_pushstring(L, dlerror());
144165  return f;
145166}
r242885r242886
148169
149170
150171
151#elif defined(LUA_DL_DLL)
172#elif defined(LUA_DL_DLL)   /* }{ */
152173/*
153174** {======================================================================
154175** This is an implementation of loadlib for Windows using native functions.
155176** =======================================================================
156177*/
157178
179#include <windows.h>
180
158181#undef setprogdir
159182
160183/*
r242885r242886
190213    lua_pushfstring(L, "system error %d\n", error);
191214}
192215
193static void ll_unloadlib (void *lib) {
216static void lsys_unloadlib (void *lib) {
194217  FreeLibrary((HMODULE)lib);
195218}
196219
197220
198static void *ll_load (lua_State *L, const char *path, int seeglb) {
221static void *lsys_load (lua_State *L, const char *path, int seeglb) {
199222  HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
200223  (void)(seeglb);  /* not used: symbols are 'global' by default */
201224  if (lib == NULL) pusherror(L);
r242885r242886
203226}
204227
205228
206static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
229static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
207230  lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym);
208231  if (f == NULL) pusherror(L);
209232  return f;
r242885r242886
212235/* }====================================================== */
213236
214237
215#else
238#else            /* }{ */
216239/*
217240** {======================================================
218241** Fallback for other systems
r242885r242886
226249#define DLMSG   "dynamic libraries not enabled; check your Lua installation"
227250
228251
229static void ll_unloadlib (void *lib) {
252static void lsys_unloadlib (void *lib) {
230253  (void)(lib);  /* not used */
231254}
232255
233256
234static void *ll_load (lua_State *L, const char *path, int seeglb) {
257static void *lsys_load (lua_State *L, const char *path, int seeglb) {
235258  (void)(path); (void)(seeglb);  /* not used */
236259  lua_pushliteral(L, DLMSG);
237260  return NULL;
238261}
239262
240263
241static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
264static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
242265  (void)(lib); (void)(sym);  /* not used */
243266  lua_pushliteral(L, DLMSG);
244267  return NULL;
245268}
246269
247270/* }====================================================== */
248#endif
271#endif            /* } */
249272
250273
251static void *ll_checkclib (lua_State *L, const char *path) {
274/*
275** return registry.CLIBS[path]
276*/
277static void *checkclib (lua_State *L, const char *path) {
252278  void *plib;
253  lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
279  lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
254280  lua_getfield(L, -1, path);
255281  plib = lua_touserdata(L, -1);  /* plib = CLIBS[path] */
256282  lua_pop(L, 2);  /* pop CLIBS table and 'plib' */
r242885r242886
258284}
259285
260286
261static void ll_addtoclib (lua_State *L, const char *path, void *plib) {
262  lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
287/*
288** registry.CLIBS[path] = plib        -- for queries
289** registry.CLIBS[#CLIBS + 1] = plib  -- also keep a list of all libraries
290*/
291static void addtoclib (lua_State *L, const char *path, void *plib) {
292  lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
263293  lua_pushlightuserdata(L, plib);
264294  lua_pushvalue(L, -1);
265295  lua_setfield(L, -3, path);  /* CLIBS[path] = plib */
r242885r242886
269299
270300
271301/*
272** __gc tag method for CLIBS table: calls 'll_unloadlib' for all lib
302** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
273303** handles in list CLIBS
274304*/
275305static int gctm (lua_State *L) {
276  int n = luaL_len(L, 1);
306  lua_Integer n = luaL_len(L, 1);
277307  for (; n >= 1; n--) {  /* for each handle, in reverse order */
278308    lua_rawgeti(L, 1, n);  /* get handle CLIBS[n] */
279    ll_unloadlib(lua_touserdata(L, -1));
309    lsys_unloadlib(lua_touserdata(L, -1));
280310    lua_pop(L, 1);  /* pop handle */
281311  }
282312  return 0;
283313}
284314
285315
286static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
287  void *reg = ll_checkclib(L, path);  /* check loaded C libraries */
316
317/* error codes for 'lookforfunc' */
318#define ERRLIB      1
319#define ERRFUNC      2
320
321/*
322** Look for a C function named 'sym' in a dynamically loaded library
323** 'path'.
324** First, check whether the library is already loaded; if not, try
325** to load it.
326** Then, if 'sym' is '*', return true (as library has been loaded).
327** Otherwise, look for symbol 'sym' in the library and push a
328** C function with that symbol.
329** Return 0 and 'true' or a function in the stack; in case of
330** errors, return an error code and an error message in the stack.
331*/
332static int lookforfunc (lua_State *L, const char *path, const char *sym) {
333  void *reg = checkclib(L, path);  /* check loaded C libraries */
288334  if (reg == NULL) {  /* must load library? */
289    reg = ll_load(L, path, *sym == '*');
335    reg = lsys_load(L, path, *sym == '*');  /* global symbols if 'sym'=='*' */
290336    if (reg == NULL) return ERRLIB;  /* unable to load library */
291    ll_addtoclib(L, path, reg);
337    addtoclib(L, path, reg);
292338  }
293339  if (*sym == '*') {  /* loading only library (no function)? */
294340    lua_pushboolean(L, 1);  /* return 'true' */
295341    return 0;  /* no errors */
296342  }
297343  else {
298    lua_CFunction f = ll_sym(L, reg, sym);
344    lua_CFunction f = lsys_sym(L, reg, sym);
299345    if (f == NULL)
300346      return ERRFUNC;  /* unable to find function */
301347    lua_pushcfunction(L, f);  /* else create new function */
r242885r242886
307353static int ll_loadlib (lua_State *L) {
308354  const char *path = luaL_checkstring(L, 1);
309355  const char *init = luaL_checkstring(L, 2);
310  int stat = ll_loadfunc(L, path, init);
356  int stat = lookforfunc(L, path, init);
311357  if (stat == 0)  /* no errors? */
312358    return 1;  /* return the loaded function */
313359  else {  /* error; error message is on stack top */
r242885r242886
360406    lua_remove(L, -2);  /* remove path template */
361407    if (readable(filename))  /* does file exist and is readable? */
362408      return filename;  /* return that file name */
363    lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
409    lua_pushfstring(L, "\n\tno file '%s'", filename);
364410    lua_remove(L, -2);  /* remove file name */
365411    luaL_addvalue(&msg);  /* concatenate error msg. entry */
366412  }
r242885r242886
390436  lua_getfield(L, lua_upvalueindex(1), pname);
391437  path = lua_tostring(L, -1);
392438  if (path == NULL)
393    luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
439    luaL_error(L, "'package.%s' must be a string", pname);
394440  return searchpath(L, name, path, ".", dirsep);
395441}
396442
r242885r242886
401447    return 2;  /* return open function and file name */
402448  }
403449  else
404    return luaL_error(L, "error loading module " LUA_QS
405                         " from file " LUA_QS ":\n\t%s",
450    return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
406451                          lua_tostring(L, 1), filename, lua_tostring(L, -1));
407452}
408453
r242885r242886
416461}
417462
418463
464/*
465** Try to find a load function for module 'modname' at file 'filename'.
466** First, change '.' to '_' in 'modname'; then, if 'modname' has
467** the form X-Y (that is, it has an "ignore mark"), build a function
468** name "luaopen_X" and look for it. (For compatibility, if that
469** fails, it also tries "luaopen_Y".) If there is no ignore mark,
470** look for a function named "luaopen_modname".
471*/
419472static int loadfunc (lua_State *L, const char *filename, const char *modname) {
420  const char *funcname;
473  const char *openfunc;
421474  const char *mark;
422475  modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
423476  mark = strchr(modname, *LUA_IGMARK);
424477  if (mark) {
425478    int stat;
426    funcname = lua_pushlstring(L, modname, mark - modname);
427    funcname = lua_pushfstring(L, LUA_POF"%s", funcname);
428    stat = ll_loadfunc(L, filename, funcname);
479    openfunc = lua_pushlstring(L, modname, mark - modname);
480    openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
481    stat = lookforfunc(L, filename, openfunc);
429482    if (stat != ERRFUNC) return stat;
430483    modname = mark + 1;  /* else go ahead and try old-style name */
431484  }
432  funcname = lua_pushfstring(L, LUA_POF"%s", modname);
433  return ll_loadfunc(L, filename, funcname);
485  openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
486  return lookforfunc(L, filename, openfunc);
434487}
435488
436489
r242885r242886
455508    if (stat != ERRFUNC)
456509      return checkload(L, 0, filename);  /* real error */
457510    else {  /* open function not found */
458      lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
459                         name, filename);
511      lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename);
460512      return 1;
461513    }
462514  }
r242885r242886
468520static int searcher_preload (lua_State *L) {
469521  const char *name = luaL_checkstring(L, 1);
470522  lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
471  lua_getfield(L, -1, name);
472  if (lua_isnil(L, -1))  /* not found? */
523  if (lua_getfield(L, -1, name) == LUA_TNIL)  /* not found? */
473524    lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
474525  return 1;
475526}
r242885r242886
479530  int i;
480531  luaL_Buffer msg;  /* to build error message */
481532  luaL_buffinit(L, &msg);
482  lua_getfield(L, lua_upvalueindex(1), "searchers");  /* will be at index 3 */
483  if (!lua_istable(L, 3))
484    luaL_error(L, LUA_QL("package.searchers") " must be a table");
533  /* push 'package.searchers' to index 3 in the stack */
534  if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE)
535    luaL_error(L, "'package.searchers' must be a table");
485536  /*  iterate over available searchers to find a loader */
486537  for (i = 1; ; i++) {
487    lua_rawgeti(L, 3, i);  /* get a searcher */
488    if (lua_isnil(L, -1)) {  /* no more searchers? */
538    if (lua_rawgeti(L, 3, i) == LUA_TNIL) {  /* no more searchers? */
489539      lua_pop(L, 1);  /* remove nil */
490540      luaL_pushresult(&msg);  /* create error message */
491      luaL_error(L, "module " LUA_QS " not found:%s",
492                    name, lua_tostring(L, -1));
541      luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
493542    }
494543    lua_pushstring(L, name);
495544    lua_call(L, 1, 2);  /* call it */
r242885r242886
520569  lua_call(L, 2, 1);  /* run loader to load module */
521570  if (!lua_isnil(L, -1))  /* non-nil return? */
522571    lua_setfield(L, 2, name);  /* _LOADED[name] = returned value */
523  lua_getfield(L, 2, name);
524  if (lua_isnil(L, -1)) {   /* module did not set a value? */
572  if (lua_getfield(L, 2, name) == LUA_TNIL) {   /* module set no value? */
525573    lua_pushboolean(L, 1);  /* use true as result */
526574    lua_pushvalue(L, -1);  /* extra copy to be returned */
527575    lua_setfield(L, 2, name);  /* _LOADED[name] = true */
r242885r242886
548596  if (lua_getstack(L, 1, &ar) == 0 ||
549597      lua_getinfo(L, "f", &ar) == 0 ||  /* get calling function */
550598      lua_iscfunction(L, -1))
551    luaL_error(L, LUA_QL("module") " not called from a Lua function");
599    luaL_error(L, "'module' not called from a Lua function");
552600  lua_pushvalue(L, -2);  /* copy new environment table to top */
553601  lua_setupvalue(L, -2, 1);
554602  lua_pop(L, 1);  /* remove function */
r242885r242886
587635  int lastarg = lua_gettop(L);  /* last parameter */
588636  luaL_pushmodule(L, modname, 1);  /* get/create module table */
589637  /* check whether table already has a _NAME field */
590  lua_getfield(L, -1, "_NAME");
591  if (!lua_isnil(L, -1))  /* is table an initialized module? */
592    lua_pop(L, 1);
638  if (lua_getfield(L, -1, "_NAME") != LUA_TNIL)
639    lua_pop(L, 1);  /* table is an initialized module */
593640  else {  /* no; initialize it */
594641    lua_pop(L, 1);
595642    modinit(L, modname);
r242885r242886
659706#if defined(LUA_COMPAT_MODULE)
660707  {"seeall", ll_seeall},
661708#endif
709  /* placeholders */
710  {"preload", NULL},
711  {"cpath", NULL},
712  {"path", NULL},
713  {"searchers", NULL},
714  {"loaded", NULL},
662715  {NULL, NULL}
663716};
664717
r242885r242886
684737    lua_pushcclosure(L, searchers[i], 1);
685738    lua_rawseti(L, -2, i+1);
686739  }
740#if defined(LUA_COMPAT_LOADERS)
741  lua_pushvalue(L, -1);  /* make a copy of 'searchers' table */
742  lua_setfield(L, -3, "loaders");  /* put it in field 'loaders' */
743#endif
744  lua_setfield(L, -2, "searchers");  /* put it in field 'searchers' */
687745}
688746
689747
690LUAMOD_API int luaopen_package (lua_State *L) {
691  /* create table CLIBS to keep track of loaded C libraries */
692  luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS);
693  lua_createtable(L, 0, 1);  /* metatable for CLIBS */
748/*
749** create table CLIBS to keep track of loaded C libraries,
750** setting a finalizer to close all libraries when closing state.
751*/
752static void createclibstable (lua_State *L) {
753  lua_newtable(L);  /* create CLIBS table */
754  lua_createtable(L, 0, 1);  /* create metatable for CLIBS */
694755  lua_pushcfunction(L, gctm);
695756  lua_setfield(L, -2, "__gc");  /* set finalizer for CLIBS table */
696757  lua_setmetatable(L, -2);
697  /* create `package' table */
698  luaL_newlib(L, pk_funcs);
758  lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS);  /* set CLIBS table in registry */
759}
760
761
762LUAMOD_API int luaopen_package (lua_State *L) {
763  createclibstable(L);
764  luaL_newlib(L, pk_funcs);  /* create 'package' table */
699765  createsearcherstable(L);
700#if defined(LUA_COMPAT_LOADERS)
701  lua_pushvalue(L, -1);  /* make a copy of 'searchers' table */
702  lua_setfield(L, -3, "loaders");  /* put it in field `loaders' */
703#endif
704  lua_setfield(L, -2, "searchers");  /* put it in field 'searchers' */
705766  /* set field 'path' */
706  setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT);
767  setpath(L, "path", LUA_PATHVARVERSION, LUA_PATH_VAR, LUA_PATH_DEFAULT);
707768  /* set field 'cpath' */
708  setpath(L, "cpath", LUA_CPATHVERSION, LUA_CPATH, LUA_CPATH_DEFAULT);
769  setpath(L, "cpath", LUA_CPATHVARVERSION, LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
709770  /* store config information */
710771  lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
711772                     LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
712773  lua_setfield(L, -2, "config");
713  /* set field `loaded' */
774  /* set field 'loaded' */
714775  luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
715776  lua_setfield(L, -2, "loaded");
716  /* set field `preload' */
777  /* set field 'preload' */
717778  luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
718779  lua_setfield(L, -2, "preload");
719780  lua_pushglobaltable(L);
trunk/3rdparty/lua/src/lobject.c
r242885r242886
11/*
2** $Id: lobject.c,v 2.58.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lobject.c,v 2.101 2014/12/26 14:43:45 roberto Exp $
33** Some generic functions over Lua objects
44** See Copyright Notice in lua.h
55*/
66
7#define lobject_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12
713#include <stdarg.h>
814#include <stdio.h>
915#include <stdlib.h>
1016#include <string.h>
1117
12#define lobject_c
13#define LUA_CORE
14
1518#include "lua.h"
1619
1720#include "lctype.h"
r242885r242886
7073}
7174
7275
73lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) {
76static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
77                                                   lua_Integer v2) {
7478  switch (op) {
75    case LUA_OPADD: return luai_numadd(NULL, v1, v2);
76    case LUA_OPSUB: return luai_numsub(NULL, v1, v2);
77    case LUA_OPMUL: return luai_nummul(NULL, v1, v2);
78    case LUA_OPDIV: return luai_numdiv(NULL, v1, v2);
79    case LUA_OPMOD: return luai_nummod(NULL, v1, v2);
80    case LUA_OPPOW: return luai_numpow(NULL, v1, v2);
81    case LUA_OPUNM: return luai_numunm(NULL, v1);
79    case LUA_OPADD: return intop(+, v1, v2);
80    case LUA_OPSUB:return intop(-, v1, v2);
81    case LUA_OPMUL:return intop(*, v1, v2);
82    case LUA_OPMOD: return luaV_mod(L, v1, v2);
83    case LUA_OPIDIV: return luaV_div(L, v1, v2);
84    case LUA_OPBAND: return intop(&, v1, v2);
85    case LUA_OPBOR: return intop(|, v1, v2);
86    case LUA_OPBXOR: return intop(^, v1, v2);
87    case LUA_OPSHL: return luaV_shiftl(v1, v2);
88    case LUA_OPSHR: return luaV_shiftl(v1, -v2);
89    case LUA_OPUNM: return intop(-, 0, v1);
90    case LUA_OPBNOT: return intop(^, ~l_castS2U(0), v1);
8291    default: lua_assert(0); return 0;
8392  }
8493}
8594
8695
96static lua_Number numarith (lua_State *L, int op, lua_Number v1,
97                                                  lua_Number v2) {
98  switch (op) {
99    case LUA_OPADD: return luai_numadd(L, v1, v2);
100    case LUA_OPSUB: return luai_numsub(L, v1, v2);
101    case LUA_OPMUL: return luai_nummul(L, v1, v2);
102    case LUA_OPDIV: return luai_numdiv(L, v1, v2);
103    case LUA_OPPOW: return luai_numpow(L, v1, v2);
104    case LUA_OPIDIV: return luai_numidiv(L, v1, v2);
105    case LUA_OPUNM: return luai_numunm(L, v1);
106    case LUA_OPMOD: {
107      lua_Number m;
108      luai_nummod(L, v1, v2, m);
109      return m;
110    }
111    default: lua_assert(0); return 0;
112  }
113}
114
115
116void luaO_arith (lua_State *L, int op, const TValue *p1, const TValue *p2,
117                 TValue *res) {
118  switch (op) {
119    case LUA_OPBAND: case LUA_OPBOR: case LUA_OPBXOR:
120    case LUA_OPSHL: case LUA_OPSHR:
121    case LUA_OPBNOT: {  /* operate only on integers */
122      lua_Integer i1; lua_Integer i2;
123      if (tointeger(p1, &i1) && tointeger(p2, &i2)) {
124        setivalue(res, intarith(L, op, i1, i2));
125        return;
126      }
127      else break;  /* go to the end */
128    }
129    case LUA_OPDIV: case LUA_OPPOW: {  /* operate only on floats */
130      lua_Number n1; lua_Number n2;
131      if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
132        setfltvalue(res, numarith(L, op, n1, n2));
133        return;
134      }
135      else break;  /* go to the end */
136    }
137    default: {  /* other operations */
138      lua_Number n1; lua_Number n2;
139      if (ttisinteger(p1) && ttisinteger(p2)) {
140        setivalue(res, intarith(L, op, ivalue(p1), ivalue(p2)));
141        return;
142      }
143      else if (tonumber(p1, &n1) && tonumber(p2, &n2)) {
144        setfltvalue(res, numarith(L, op, n1, n2));
145        return;
146      }
147      else break;  /* go to the end */
148    }
149  }
150  /* could not perform raw operation; try metamethod */
151  lua_assert(L != NULL);  /* should not fail when folding (compile time) */
152  luaT_trybinTM(L, p1, p2, res, cast(TMS, op - LUA_OPADD + TM_ADD));
153}
154
155
87156int luaO_hexavalue (int c) {
88157  if (lisdigit(c)) return c - '0';
89158  else return ltolower(c) - 'a' + 10;
90159}
91160
92161
93#if !defined(lua_strx2number)
94
95#include <math.h>
96
97
98162static int isneg (const char **s) {
99163  if (**s == '-') { (*s)++; return 1; }
100164  else if (**s == '+') (*s)++;
r242885r242886
102166}
103167
104168
105static lua_Number readhexa (const char **s, lua_Number r, int *count) {
106  for (; lisxdigit(cast_uchar(**s)); (*s)++) {  /* read integer part */
107    r = (r * cast_num(16.0)) + cast_num(1.0*luaO_hexavalue(cast_uchar(**s)));
108    (*count)++;
109  }
110  return r;
111}
112169
170/*
171** {==================================================================
172** Lua's implementation for 'lua_strx2number'
173** ===================================================================
174*/
175#if !defined(lua_strx2number)
113176
177#include <math.h>
178
179/* maximum number of significant digits to read (to avoid overflows
180   even with single floats) */
181#define MAXSIGDIG   30
182
114183/*
115184** convert an hexadecimal numeric string to a number, following
116185** C99 specification for 'strtod'
117186*/
118187static lua_Number lua_strx2number (const char *s, char **endptr) {
119  lua_Number r = 0.0;
120  int e = 0, i = 0;
121  int neg = 0;  /* 1 if number is negative */
188  lua_Number r = 0.0;  /* result (accumulator) */
189  int sigdig = 0;  /* number of significant digits */
190  int nosigdig = 0;  /* number of non-significant digits */
191  int e = 0;  /* exponent correction */
192  int neg;  /* 1 if number is negative */
193  int dot = 0;  /* true after seen a dot */
122194  *endptr = cast(char *, s);  /* nothing is valid yet */
123195  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
124196  neg = isneg(&s);  /* check signal */
125197  if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X')))  /* check '0x' */
126198    return 0.0;  /* invalid format (no '0x') */
127  s += 2;  /* skip '0x' */
128  r = readhexa(&s, r, &i);  /* read integer part */
129  if (*s == '.') {
130    s++;  /* skip dot */
131    r = readhexa(&s, r, &e);  /* read fractional part */
199  for (s += 2; ; s++) {  /* skip '0x' and read numeral */
200    if (*s == '.') {
201      if (dot) break;  /* second dot? stop loop */
202      else dot = 1;
203    }
204    else if (lisxdigit(cast_uchar(*s))) {
205      if (sigdig == 0 && *s == '0')  /* non-significant digit (zero)? */
206        nosigdig++;
207      else if (++sigdig <= MAXSIGDIG)  /* can read it without overflow? */
208          r = (r * cast_num(16.0)) + luaO_hexavalue(*s);
209      else e++; /* too many digits; ignore, but still count for exponent */
210      if (dot) e--;  /* decimal digit? correct exponent */
211    }
212    else break;  /* neither a dot nor a digit */
132213  }
133  if (i == 0 && e == 0)
134    return 0.0;  /* invalid format (no digit) */
135  e *= -4;  /* each fractional digit divides value by 2^-4 */
214  if (nosigdig + sigdig == 0)  /* no digits? */
215    return 0.0;  /* invalid format */
136216  *endptr = cast(char *, s);  /* valid up to here */
217  e *= 4;  /* each digit multiplies/divides value by 2^4 */
137218  if (*s == 'p' || *s == 'P') {  /* exponent part? */
138    int exp1 = 0;
139    int neg1;
219    int exp1 = 0;  /* exponent value */
220    int neg1;  /* exponent signal */
140221    s++;  /* skip 'p' */
141222    neg1 = isneg(&s);  /* signal */
142223    if (!lisdigit(cast_uchar(*s)))
143      goto ret;  /* must have at least one digit */
224      return 0.0;  /* invalid; must have at least one digit */
144225    while (lisdigit(cast_uchar(*s)))  /* read exponent */
145226      exp1 = exp1 * 10 + *(s++) - '0';
146227    if (neg1) exp1 = -exp1;
147228    e += exp1;
229    *endptr = cast(char *, s);  /* valid up to here */
148230  }
149  *endptr = cast(char *, s);  /* valid up to here */
150 ret:
151231  if (neg) r = -r;
152232  return l_mathop(ldexp)(r, e);
153233}
154234
155235#endif
236/* }====================================================== */
156237
157238
158int luaO_str2d (const char *s, size_t len, lua_Number *result) {
239static const char *l_str2d (const char *s, lua_Number *result) {
159240  char *endptr;
160241  if (strpbrk(s, "nN"))  /* reject 'inf' and 'nan' */
161    return 0;
162  else if (strpbrk(s, "xX"))  /* hexa? */
242    return NULL;
243  else if (strpbrk(s, "xX"))  /* hex? */
163244    *result = lua_strx2number(s, &endptr);
164245  else
165246    *result = lua_str2number(s, &endptr);
166247  if (endptr == s) return 0;  /* nothing recognized */
167248  while (lisspace(cast_uchar(*endptr))) endptr++;
168  return (endptr == s + len);  /* OK if no trailing characters */
249  return (*endptr == '\0' ? endptr : NULL);  /* OK if no trailing characters */
169250}
170251
171252
253static const char *l_str2int (const char *s, lua_Integer *result) {
254  lua_Unsigned a = 0;
255  int empty = 1;
256  int neg;
257  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
258  neg = isneg(&s);
259  if (s[0] == '0' &&
260      (s[1] == 'x' || s[1] == 'X')) {  /* hex? */
261    s += 2;  /* skip '0x' */
262    for (; lisxdigit(cast_uchar(*s)); s++) {
263      a = a * 16 + luaO_hexavalue(*s);
264      empty = 0;
265    }
266  }
267  else {  /* decimal */
268    for (; lisdigit(cast_uchar(*s)); s++) {
269      a = a * 10 + *s - '0';
270      empty = 0;
271    }
272  }
273  while (lisspace(cast_uchar(*s))) s++;  /* skip trailing spaces */
274  if (empty || *s != '\0') return NULL;  /* something wrong in the numeral */
275  else {
276    *result = l_castU2S((neg) ? 0u - a : a);
277    return s;
278  }
279}
172280
281
282size_t luaO_str2num (const char *s, TValue *o) {
283  lua_Integer i; lua_Number n;
284  const char *e;
285  if ((e = l_str2int(s, &i)) != NULL) {  /* try as an integer */
286    setivalue(o, i);
287  }
288  else if ((e = l_str2d(s, &n)) != NULL) {  /* else try as a float */
289    setfltvalue(o, n);
290  }
291  else
292    return 0;  /* conversion failed */
293  return (e - s + 1);  /* success; return string size */
294}
295
296
297int luaO_utf8esc (char *buff, unsigned long x) {
298  int n = 1;  /* number of bytes put in buffer (backwards) */
299  lua_assert(x <= 0x10FFFF);
300  if (x < 0x80)  /* ascii? */
301    buff[UTF8BUFFSZ - 1] = cast(char, x);
302  else {  /* need continuation bytes */
303    unsigned int mfb = 0x3f;  /* maximum that fits in first byte */
304    do {  /* add continuation bytes */
305      buff[UTF8BUFFSZ - (n++)] = cast(char, 0x80 | (x & 0x3f));
306      x >>= 6;  /* remove added bits */
307      mfb >>= 1;  /* now there is one less bit available in first byte */
308    } while (x > mfb);  /* still needs continuation byte? */
309    buff[UTF8BUFFSZ - n] = cast(char, (~mfb << 1) | x);  /* add first byte */
310  }
311  return n;
312}
313
314
315/* maximum length of the conversion of a number to a string */
316#define MAXNUMBER2STR   50
317
318
319/*
320** Convert a number object to a string
321*/
322void luaO_tostring (lua_State *L, StkId obj) {
323  char buff[MAXNUMBER2STR];
324  size_t len;
325  lua_assert(ttisnumber(obj));
326  if (ttisinteger(obj))
327    len = lua_integer2str(buff, ivalue(obj));
328  else {
329    len = lua_number2str(buff, fltvalue(obj));
330#if !defined(LUA_COMPAT_FLOATSTRING)
331    if (buff[strspn(buff, "-0123456789")] == '\0') {  /* looks like an int? */
332      buff[len++] = '.';
333      buff[len++] = '0';  /* adds '.0' to result */
334    }
335#endif
336  }
337  setsvalue2s(L, obj, luaS_newlstr(L, buff, len));
338}
339
340
173341static void pushstr (lua_State *L, const char *str, size_t l) {
174342  setsvalue2s(L, L->top++, luaS_newlstr(L, str, l));
175343}
176344
177345
178/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
346/* this function handles only '%d', '%c', '%f', '%p', and '%s'
347   conventional formats, plus Lua-specific '%I' and '%U' */
179348const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
180349  int n = 0;
181350  for (;;) {
r242885r242886
191360        break;
192361      }
193362      case 'c': {
194        char buff;
195        buff = cast(char, va_arg(argp, int));
196        pushstr(L, &buff, 1);
363        char buff = cast(char, va_arg(argp, int));
364        if (lisprint(cast_uchar(buff)))
365          pushstr(L, &buff, 1);
366        else  /* non-printable character; print its code */
367          luaO_pushfstring(L, "<\\%d>", cast_uchar(buff));
197368        break;
198369      }
199370      case 'd': {
200        setnvalue(L->top++, cast_num(va_arg(argp, int)));
371        setivalue(L->top++, va_arg(argp, int));
372        luaO_tostring(L, L->top - 1);
201373        break;
202374      }
375      case 'I': {
376        setivalue(L->top++, cast(lua_Integer, va_arg(argp, l_uacInt)));
377        luaO_tostring(L, L->top - 1);
378        break;
379      }
203380      case 'f': {
204        setnvalue(L->top++, cast_num(va_arg(argp, l_uacNumber)));
381        setfltvalue(L->top++, cast_num(va_arg(argp, l_uacNumber)));
382        luaO_tostring(L, L->top - 1);
205383        break;
206384      }
207385      case 'p': {
208        char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
386        char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */
209387        int l = sprintf(buff, "%p", va_arg(argp, void *));
210388        pushstr(L, buff, l);
211389        break;
212390      }
391      case 'U': {
392        char buff[UTF8BUFFSZ];
393        int l = luaO_utf8esc(buff, cast(long, va_arg(argp, long)));
394        pushstr(L, buff + UTF8BUFFSZ - l, l);
395        break;
396      }
213397      case '%': {
214398        pushstr(L, "%", 1);
215399        break;
216400      }
217401      default: {
218        luaG_runerror(L,
219            "invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"),
220            *(e + 1));
402        luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
403                         *(e + 1));
221404      }
222405    }
223406    n += 2;
trunk/3rdparty/lua/src/lobject.h
r242885r242886
11/*
2** $Id: lobject.h,v 2.71.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lobject.h,v 2.106 2015/01/05 13:52:37 roberto Exp $
33** Type definitions for Lua objects
44** See Copyright Notice in lua.h
55*/
r242885r242886
2020** Extra tags for non-values
2121*/
2222#define LUA_TPROTO   LUA_NUMTAGS
23#define LUA_TUPVAL   (LUA_NUMTAGS+1)
24#define LUA_TDEADKEY   (LUA_NUMTAGS+2)
23#define LUA_TDEADKEY   (LUA_NUMTAGS+1)
2524
2625/*
2726** number of all possible tags (including LUA_TNONE but excluding DEADKEY)
2827*/
29#define LUA_TOTALTAGS   (LUA_TUPVAL+2)
28#define LUA_TOTALTAGS   (LUA_TPROTO + 2)
3029
3130
3231/*
r242885r242886
5756#define LUA_TLNGSTR   (LUA_TSTRING | (1 << 4))  /* long strings */
5857
5958
59/* Variant tags for numbers */
60#define LUA_TNUMFLT   (LUA_TNUMBER | (0 << 4))  /* float numbers */
61#define LUA_TNUMINT   (LUA_TNUMBER | (1 << 4))  /* integer numbers */
62
63
6064/* Bit mark for collectable types */
6165#define BIT_ISCOLLECTABLE   (1 << 6)
6266
r242885r242886
6569
6670
6771/*
68** Union of all collectable objects
72** Common type for all collectable objects
6973*/
70typedef union GCObject GCObject;
74typedef struct GCObject GCObject;
7175
7276
7377/*
r242885r242886
7882
7983
8084/*
81** Common header in struct form
85** Common type has only the common header
8286*/
83typedef struct GCheader {
87struct GCObject {
8488  CommonHeader;
85} GCheader;
89};
8690
8791
8892
r242885r242886
9296typedef union Value Value;
9397
9498
95#define numfield   lua_Number n;    /* numbers */
9699
97100
98
99101/*
100102** Tagged Values. This is the basic representation of values in Lua,
101103** an actual value plus a tag with its type.
r242885r242886
111113
112114
113115#define val_(o)      ((o)->value_)
114#define num_(o)      (val_(o).n)
115116
116117
117118/* raw type tag of a TValue */
r242885r242886
124125#define ttype(o)   (rttype(o) & 0x3F)
125126
126127/* type tag of a TValue with no variants (bits 0-3) */
127#define ttypenv(o)   (novariant(rttype(o)))
128#define ttnov(o)   (novariant(rttype(o)))
128129
129130
130131/* Macros to test type */
131132#define checktag(o,t)      (rttype(o) == (t))
132#define checktype(o,t)      (ttypenv(o) == (t))
133#define ttisnumber(o)      checktag((o), LUA_TNUMBER)
133#define checktype(o,t)      (ttnov(o) == (t))
134#define ttisnumber(o)      checktype((o), LUA_TNUMBER)
135#define ttisfloat(o)      checktag((o), LUA_TNUMFLT)
136#define ttisinteger(o)      checktag((o), LUA_TNUMINT)
134137#define ttisnil(o)      checktag((o), LUA_TNIL)
135138#define ttisboolean(o)      checktag((o), LUA_TBOOLEAN)
136139#define ttislightuserdata(o)   checktag((o), LUA_TLIGHTUSERDATA)
r242885r242886
143146#define ttisCclosure(o)      checktag((o), ctb(LUA_TCCL))
144147#define ttisLclosure(o)      checktag((o), ctb(LUA_TLCL))
145148#define ttislcf(o)      checktag((o), LUA_TLCF)
146#define ttisuserdata(o)      checktag((o), ctb(LUA_TUSERDATA))
149#define ttisfulluserdata(o)   checktag((o), ctb(LUA_TUSERDATA))
147150#define ttisthread(o)      checktag((o), ctb(LUA_TTHREAD))
148151#define ttisdeadkey(o)      checktag((o), LUA_TDEADKEY)
149152
150#define ttisequal(o1,o2)   (rttype(o1) == rttype(o2))
151153
152154/* Macros to access values */
153#define nvalue(o)   check_exp(ttisnumber(o), num_(o))
155#define ivalue(o)   check_exp(ttisinteger(o), val_(o).i)
156#define fltvalue(o)   check_exp(ttisfloat(o), val_(o).n)
157#define nvalue(o)   check_exp(ttisnumber(o), \
158   (ttisinteger(o) ? cast_num(ivalue(o)) : fltvalue(o)))
154159#define gcvalue(o)   check_exp(iscollectable(o), val_(o).gc)
155160#define pvalue(o)   check_exp(ttislightuserdata(o), val_(o).p)
156#define rawtsvalue(o)   check_exp(ttisstring(o), &val_(o).gc->ts)
157#define tsvalue(o)   (&rawtsvalue(o)->tsv)
158#define rawuvalue(o)   check_exp(ttisuserdata(o), &val_(o).gc->u)
159#define uvalue(o)   (&rawuvalue(o)->uv)
160#define clvalue(o)   check_exp(ttisclosure(o), &val_(o).gc->cl)
161#define clLvalue(o)   check_exp(ttisLclosure(o), &val_(o).gc->cl.l)
162#define clCvalue(o)   check_exp(ttisCclosure(o), &val_(o).gc->cl.c)
161#define tsvalue(o)   check_exp(ttisstring(o), gco2ts(val_(o).gc))
162#define uvalue(o)   check_exp(ttisfulluserdata(o), gco2u(val_(o).gc))
163#define clvalue(o)   check_exp(ttisclosure(o), gco2cl(val_(o).gc))
164#define clLvalue(o)   check_exp(ttisLclosure(o), gco2lcl(val_(o).gc))
165#define clCvalue(o)   check_exp(ttisCclosure(o), gco2ccl(val_(o).gc))
163166#define fvalue(o)   check_exp(ttislcf(o), val_(o).f)
164#define hvalue(o)   check_exp(ttistable(o), &val_(o).gc->h)
167#define hvalue(o)   check_exp(ttistable(o), gco2t(val_(o).gc))
165168#define bvalue(o)   check_exp(ttisboolean(o), val_(o).b)
166#define thvalue(o)   check_exp(ttisthread(o), &val_(o).gc->th)
169#define thvalue(o)   check_exp(ttisthread(o), gco2th(val_(o).gc))
167170/* a dead value may get the 'gc' field, but cannot access its contents */
168171#define deadvalue(o)   check_exp(ttisdeadkey(o), cast(void *, val_(o).gc))
169172
r242885r242886
174177
175178
176179/* Macros for internal tests */
177#define righttt(obj)      (ttype(obj) == gcvalue(obj)->gch.tt)
180#define righttt(obj)      (ttype(obj) == gcvalue(obj)->tt)
178181
179182#define checkliveness(g,obj) \
180183   lua_longassert(!iscollectable(obj) || \
r242885r242886
184187/* Macros to set values */
185188#define settt_(o,t)   ((o)->tt_=(t))
186189
187#define setnvalue(obj,x) \
188  { TValue *io=(obj); num_(io)=(x); settt_(io, LUA_TNUMBER); }
190#define setfltvalue(obj,x) \
191  { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_TNUMFLT); }
189192
193#define setivalue(obj,x) \
194  { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_TNUMINT); }
195
190196#define setnilvalue(obj) settt_(obj, LUA_TNIL)
191197
192198#define setfvalue(obj,x) \
r242885r242886
199205  { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }
200206
201207#define setgcovalue(L,obj,x) \
202  { TValue *io=(obj); GCObject *i_g=(x); \
203    val_(io).gc=i_g; settt_(io, ctb(gch(i_g)->tt)); }
208  { TValue *io = (obj); GCObject *i_g=(x); \
209    val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); }
204210
205211#define setsvalue(L,obj,x) \
206  { TValue *io=(obj); \
207    TString *x_ = (x); \
208    val_(io).gc=cast(GCObject *, x_); settt_(io, ctb(x_->tsv.tt)); \
212  { TValue *io = (obj); TString *x_ = (x); \
213    val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \
209214    checkliveness(G(L),io); }
210215
211216#define setuvalue(L,obj,x) \
212  { TValue *io=(obj); \
213    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TUSERDATA)); \
217  { TValue *io = (obj); Udata *x_ = (x); \
218    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TUSERDATA)); \
214219    checkliveness(G(L),io); }
215220
216221#define setthvalue(L,obj,x) \
217  { TValue *io=(obj); \
218    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTHREAD)); \
222  { TValue *io = (obj); lua_State *x_ = (x); \
223    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTHREAD)); \
219224    checkliveness(G(L),io); }
220225
221226#define setclLvalue(L,obj,x) \
222  { TValue *io=(obj); \
223    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TLCL)); \
227  { TValue *io = (obj); LClosure *x_ = (x); \
228    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TLCL)); \
224229    checkliveness(G(L),io); }
225230
226231#define setclCvalue(L,obj,x) \
227  { TValue *io=(obj); \
228    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TCCL)); \
232  { TValue *io = (obj); CClosure *x_ = (x); \
233    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TCCL)); \
229234    checkliveness(G(L),io); }
230235
231236#define sethvalue(L,obj,x) \
232  { TValue *io=(obj); \
233    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTABLE)); \
237  { TValue *io = (obj); Table *x_ = (x); \
238    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTABLE)); \
234239    checkliveness(G(L),io); }
235240
236241#define setdeadvalue(obj)   settt_(obj, LUA_TDEADKEY)
r242885r242886
238243
239244
240245#define setobj(L,obj1,obj2) \
241   { const TValue *io2=(obj2); TValue *io1=(obj1); \
242     io1->value_ = io2->value_; io1->tt_ = io2->tt_; \
243     checkliveness(G(L),io1); }
246   { TValue *io1=(obj1); *io1 = *(obj2); \
247     (void)L; checkliveness(G(L),io1); }
244248
245249
246250/*
r242885r242886
263267#define setsvalue2n   setsvalue
264268
265269
266/* check whether a number is valid (useful only for NaN trick) */
267#define luai_checknum(L,o,c)   { /* empty */ }
268270
269271
270272/*
271273** {======================================================
272** NaN Trick
273** =======================================================
274*/
275#if defined(LUA_NANTRICK)
276
277/*
278** numbers are represented in the 'd_' field. All other values have the
279** value (NNMARK | tag) in 'tt__'. A number with such pattern would be
280** a "signaled NaN", which is never generated by regular operations by
281** the CPU (nor by 'strtod')
282*/
283
284/* allows for external implementation for part of the trick */
285#if !defined(NNMARK)   /* { */
286
287
288#if !defined(LUA_IEEEENDIAN)
289#error option 'LUA_NANTRICK' needs 'LUA_IEEEENDIAN'
290#endif
291
292
293#define NNMARK      0x7FF7A500
294#define NNMASK      0x7FFFFF00
295
296#undef TValuefields
297#undef NILCONSTANT
298
299#if (LUA_IEEEENDIAN == 0)   /* { */
300
301/* little endian */
302#define TValuefields  \
303   union { struct { Value v__; int tt__; } i; double d__; } u
304#define NILCONSTANT   {{{NULL}, tag2tt(LUA_TNIL)}}
305/* field-access macros */
306#define v_(o)      ((o)->u.i.v__)
307#define d_(o)      ((o)->u.d__)
308#define tt_(o)      ((o)->u.i.tt__)
309
310#else            /* }{ */
311
312/* big endian */
313#define TValuefields  \
314   union { struct { int tt__; Value v__; } i; double d__; } u
315#define NILCONSTANT   {{tag2tt(LUA_TNIL), {NULL}}}
316/* field-access macros */
317#define v_(o)      ((o)->u.i.v__)
318#define d_(o)      ((o)->u.d__)
319#define tt_(o)      ((o)->u.i.tt__)
320
321#endif            /* } */
322
323#endif         /* } */
324
325
326/* correspondence with standard representation */
327#undef val_
328#define val_(o)      v_(o)
329#undef num_
330#define num_(o)      d_(o)
331
332
333#undef numfield
334#define numfield   /* no such field; numbers are the entire struct */
335
336/* basic check to distinguish numbers from non-numbers */
337#undef ttisnumber
338#define ttisnumber(o)   ((tt_(o) & NNMASK) != NNMARK)
339
340#define tag2tt(t)   (NNMARK | (t))
341
342#undef rttype
343#define rttype(o)   (ttisnumber(o) ? LUA_TNUMBER : tt_(o) & 0xff)
344
345#undef settt_
346#define settt_(o,t)   (tt_(o) = tag2tt(t))
347
348#undef setnvalue
349#define setnvalue(obj,x) \
350   { TValue *io_=(obj); num_(io_)=(x); lua_assert(ttisnumber(io_)); }
351
352#undef setobj
353#define setobj(L,obj1,obj2) \
354   { const TValue *o2_=(obj2); TValue *o1_=(obj1); \
355     o1_->u = o2_->u; \
356     checkliveness(G(L),o1_); }
357
358
359/*
360** these redefinitions are not mandatory, but these forms are more efficient
361*/
362
363#undef checktag
364#undef checktype
365#define checktag(o,t)   (tt_(o) == tag2tt(t))
366#define checktype(o,t)   (ctb(tt_(o) | VARBITS) == ctb(tag2tt(t) | VARBITS))
367
368#undef ttisequal
369#define ttisequal(o1,o2)  \
370   (ttisnumber(o1) ? ttisnumber(o2) : (tt_(o1) == tt_(o2)))
371
372
373#undef luai_checknum
374#define luai_checknum(L,o,c)   { if (!ttisnumber(o)) c; }
375
376#endif
377/* }====================================================== */
378
379
380
381/*
382** {======================================================
383274** types and prototypes
384275** =======================================================
385276*/
r242885r242886
390281  void *p;         /* light userdata */
391282  int b;           /* booleans */
392283  lua_CFunction f; /* light C functions */
393  numfield         /* numbers */
284  lua_Integer i;   /* integer numbers */
285  lua_Number n;    /* float numbers */
394286};
395287
396288
r242885r242886
406298
407299/*
408300** Header for string value; string bytes follow the end of this structure
301** (aligned according to 'UTString'; see next).
409302*/
410typedef union TString {
411  L_Umaxalign dummy;  /* ensures maximum alignment for strings */
412  struct {
413    CommonHeader;
414    lu_byte extra;  /* reserved words for short strings; "has hash" for longs */
415    unsigned int hash;
416    size_t len;  /* number of characters in string */
417  } tsv;
303typedef struct TString {
304  CommonHeader;
305  lu_byte extra;  /* reserved words for short strings; "has hash" for longs */
306  unsigned int hash;
307  size_t len;  /* number of characters in string */
308  struct TString *hnext;  /* linked list for hash table */
418309} TString;
419310
420311
421/* get the actual string (array of bytes) from a TString */
422#define getstr(ts)   cast(const char *, (ts) + 1)
312/*
313** Ensures that address after this type is always fully aligned.
314*/
315typedef union UTString {
316  L_Umaxalign dummy;  /* ensures maximum alignment for strings */
317  TString tsv;
318} UTString;
423319
320
321/*
322** Get the actual string (array of bytes) from a 'TString'.
323** (Access to 'extra' ensures that value is really a 'TString'.)
324*/
325#define getaddrstr(ts)   (cast(char *, (ts)) + sizeof(UTString))
326#define getstr(ts)  \
327  check_exp(sizeof((ts)->extra), cast(const char*, getaddrstr(ts)))
328
424329/* get the actual string (array of bytes) from a Lua value */
425#define svalue(o)       getstr(rawtsvalue(o))
330#define svalue(o)       getstr(tsvalue(o))
426331
427332
428333/*
429334** Header for userdata; memory area follows the end of this structure
335** (aligned according to 'UUdata'; see next).
430336*/
431typedef union Udata {
432  L_Umaxalign dummy;  /* ensures maximum alignment for `local' udata */
433  struct {
434    CommonHeader;
435    struct Table *metatable;
436    struct Table *env;
437    size_t len;  /* number of bytes */
438  } uv;
337typedef struct Udata {
338  CommonHeader;
339  lu_byte ttuv_;  /* user value's tag */
340  struct Table *metatable;
341  size_t len;  /* number of bytes */
342  union Value user_;  /* user value */
439343} Udata;
440344
441345
346/*
347** Ensures that address after this type is always fully aligned.
348*/
349typedef union UUdata {
350  L_Umaxalign dummy;  /* ensures maximum alignment for 'local' udata */
351  Udata uv;
352} UUdata;
442353
354
443355/*
356**  Get the address of memory block inside 'Udata'.
357** (Access to 'ttuv_' ensures that value is really a 'Udata'.)
358*/
359#define getudatamem(u)  \
360  check_exp(sizeof((u)->ttuv_), (cast(char*, (u)) + sizeof(UUdata)))
361
362#define setuservalue(L,u,o) \
363   { const TValue *io=(o); Udata *iu = (u); \
364     iu->user_ = io->value_; iu->ttuv_ = io->tt_; \
365     checkliveness(G(L),io); }
366
367
368#define getuservalue(L,u,o) \
369   { TValue *io=(o); const Udata *iu = (u); \
370     io->value_ = iu->user_; io->tt_ = iu->ttuv_; \
371     checkliveness(G(L),io); }
372
373
374/*
444375** Description of an upvalue for function prototypes
445376*/
446377typedef struct Upvaldesc {
r242885r242886
466397*/
467398typedef struct Proto {
468399  CommonHeader;
400  lu_byte numparams;  /* number of fixed parameters */
401  lu_byte is_vararg;
402  lu_byte maxstacksize;  /* maximum stack used by this function */
403  int sizeupvalues;  /* size of 'upvalues' */
404  int sizek;  /* size of 'k' */
405  int sizecode;
406  int sizelineinfo;
407  int sizep;  /* size of 'p' */
408  int sizelocvars;
409  int linedefined;
410  int lastlinedefined;
469411  TValue *k;  /* constants used by the function */
470412  Instruction *code;
471413  struct Proto **p;  /* functions defined inside the function */
472414  int *lineinfo;  /* map from opcodes to source lines (debug information) */
473415  LocVar *locvars;  /* information about local variables (debug information) */
474416  Upvaldesc *upvalues;  /* upvalue information */
475  union Closure *cache;  /* last created closure with this prototype */
417  struct LClosure *cache;  /* last created closure with this prototype */
476418  TString  *source;  /* used for debug information */
477  int sizeupvalues;  /* size of 'upvalues' */
478  int sizek;  /* size of `k' */
479  int sizecode;
480  int sizelineinfo;
481  int sizep;  /* size of `p' */
482  int sizelocvars;
483  int linedefined;
484  int lastlinedefined;
485419  GCObject *gclist;
486  lu_byte numparams;  /* number of fixed parameters */
487  lu_byte is_vararg;
488  lu_byte maxstacksize;  /* maximum stack used by this function */
489420} Proto;
490421
491422
r242885r242886
493424/*
494425** Lua Upvalues
495426*/
496typedef struct UpVal {
497  CommonHeader;
498  TValue *v;  /* points to stack or to its own value */
499  union {
500    TValue value;  /* the value (when closed) */
501    struct {  /* double linked list (when open) */
502      struct UpVal *prev;
503      struct UpVal *next;
504    } l;
505  } u;
506} UpVal;
427typedef struct UpVal UpVal;
507428
508429
509430/*
r242885r242886
545466typedef union TKey {
546467  struct {
547468    TValuefields;
548    struct Node *next;  /* for chaining */
469    int next;  /* for chaining (offset for next node) */
549470  } nk;
550471  TValue tvk;
551472} TKey;
552473
553474
475/* copy a value into a key without messing up field 'next' */
476#define setnodekey(L,key,obj) \
477   { TKey *k_=(key); const TValue *io_=(obj); \
478     k_->nk.value_ = io_->value_; k_->nk.tt_ = io_->tt_; \
479     (void)L; checkliveness(G(L),io_); }
480
481
554482typedef struct Node {
555483  TValue i_val;
556484  TKey i_key;
r242885r242886
560488typedef struct Table {
561489  CommonHeader;
562490  lu_byte flags;  /* 1<<p means tagmethod(p) is not present */
563  lu_byte lsizenode;  /* log2 of size of `node' array */
564  struct Table *metatable;
491  lu_byte lsizenode;  /* log2 of size of 'node' array */
492  unsigned int sizearray;  /* size of 'array' array */
565493  TValue *array;  /* array part */
566494  Node *node;
567495  Node *lastfree;  /* any free position is before this position */
496  struct Table *metatable;
568497  GCObject *gclist;
569  int sizearray;  /* size of `array' array */
570498} Table;
571499
572500
573501
574502/*
575** `module' operation for hashing (size is always a power of 2)
503** 'module' operation for hashing (size is always a power of 2)
576504*/
577505#define lmod(s,size) \
578506   (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))
r242885r242886
590518
591519LUAI_DDEC const TValue luaO_nilobject_;
592520
521/* size of buffer for 'luaO_utf8esc' function */
522#define UTF8BUFFSZ   8
593523
594524LUAI_FUNC int luaO_int2fb (unsigned int x);
595525LUAI_FUNC int luaO_fb2int (int x);
526LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x);
596527LUAI_FUNC int luaO_ceillog2 (unsigned int x);
597LUAI_FUNC lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2);
598LUAI_FUNC int luaO_str2d (const char *s, size_t len, lua_Number *result);
528LUAI_FUNC void luaO_arith (lua_State *L, int op, const TValue *p1,
529                           const TValue *p2, TValue *res);
530LUAI_FUNC size_t luaO_str2num (const char *s, TValue *o);
599531LUAI_FUNC int luaO_hexavalue (int c);
532LUAI_FUNC void luaO_tostring (lua_State *L, StkId obj);
600533LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
601534                                                       va_list argp);
602535LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
trunk/3rdparty/lua/src/lopcodes.c
r242885r242886
11/*
2** $Id: lopcodes.c,v 1.49.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lopcodes.c,v 1.55 2015/01/05 13:48:33 roberto Exp $
33** Opcodes for Lua virtual machine
44** See Copyright Notice in lua.h
55*/
66
7
87#define lopcodes_c
98#define LUA_CORE
109
10#include "lprefix.h"
1111
12
13#include <stddef.h>
14
1215#include "lopcodes.h"
1316
1417
r242885r242886
3134  "ADD",
3235  "SUB",
3336  "MUL",
34  "DIV",
3537  "MOD",
3638  "POW",
39  "DIV",
40  "IDIV",
41  "BAND",
42  "BOR",
43  "BXOR",
44  "SHL",
45  "SHR",
3746  "UNM",
47  "BNOT",
3848  "NOT",
3949  "LEN",
4050  "CONCAT",
r242885r242886
7989 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_ADD */
8090 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_SUB */
8191 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_MUL */
82 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_DIV */
8392 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_MOD */
8493 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_POW */
94 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_DIV */
95 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_IDIV */
96 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_BAND */
97 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_BOR */
98 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_BXOR */
99 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_SHL */
100 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_SHR */
85101 ,opmode(0, 1, OpArgR, OpArgN, iABC)      /* OP_UNM */
102 ,opmode(0, 1, OpArgR, OpArgN, iABC)      /* OP_BNOT */
86103 ,opmode(0, 1, OpArgR, OpArgN, iABC)      /* OP_NOT */
87104 ,opmode(0, 1, OpArgR, OpArgN, iABC)      /* OP_LEN */
88105 ,opmode(0, 1, OpArgR, OpArgR, iABC)      /* OP_CONCAT */
trunk/3rdparty/lua/src/lopcodes.h
r242885r242886
11/*
2** $Id: lopcodes.h,v 1.142.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lopcodes.h,v 1.148 2014/10/25 11:50:46 roberto Exp $
33** Opcodes for Lua virtual machine
44** See Copyright Notice in lua.h
55*/
r242885r242886
1414  We assume that instructions are unsigned numbers.
1515  All instructions have an opcode in the first 6 bits.
1616  Instructions can have the following fields:
17   `A' : 8 bits
18   `B' : 9 bits
19   `C' : 9 bits
17   'A' : 8 bits
18   'B' : 9 bits
19   'C' : 9 bits
2020   'Ax' : 26 bits ('A', 'B', and 'C' together)
21   `Bx' : 18 bits (`B' and `C' together)
22   `sBx' : signed Bx
21   'Bx' : 18 bits ('B' and 'C' together)
22   'sBx' : signed Bx
2323
2424  A signed argument is represented in excess K; that is, the number
2525  value is the unsigned value minus K. K is exactly the maximum value
r242885r242886
5858*/
5959#if SIZE_Bx < LUAI_BITSINT-1
6060#define MAXARG_Bx        ((1<<SIZE_Bx)-1)
61#define MAXARG_sBx        (MAXARG_Bx>>1)         /* `sBx' is signed */
61#define MAXARG_sBx        (MAXARG_Bx>>1)         /* 'sBx' is signed */
6262#else
6363#define MAXARG_Bx        MAX_INT
6464#define MAXARG_sBx        MAX_INT
r242885r242886
7676#define MAXARG_C        ((1<<SIZE_C)-1)
7777
7878
79/* creates a mask with `n' 1 bits at position `p' */
79/* creates a mask with 'n' 1 bits at position 'p' */
8080#define MASK1(n,p)   ((~((~(Instruction)0)<<(n)))<<(p))
8181
82/* creates a mask with `n' 0 bits at position `p' */
82/* creates a mask with 'n' 0 bits at position 'p' */
8383#define MASK0(n,p)   (~MASK1(n,p))
8484
8585/*
r242885r242886
187187OP_ADD,/*   A B C   R(A) := RK(B) + RK(C)            */
188188OP_SUB,/*   A B C   R(A) := RK(B) - RK(C)            */
189189OP_MUL,/*   A B C   R(A) := RK(B) * RK(C)            */
190OP_DIV,/*   A B C   R(A) := RK(B) / RK(C)            */
191190OP_MOD,/*   A B C   R(A) := RK(B) % RK(C)            */
192191OP_POW,/*   A B C   R(A) := RK(B) ^ RK(C)            */
192OP_DIV,/*   A B C   R(A) := RK(B) / RK(C)            */
193OP_IDIV,/*   A B C   R(A) := RK(B) // RK(C)            */
194OP_BAND,/*   A B C   R(A) := RK(B) & RK(C)            */
195OP_BOR,/*   A B C   R(A) := RK(B) | RK(C)            */
196OP_BXOR,/*   A B C   R(A) := RK(B) ~ RK(C)            */
197OP_SHL,/*   A B C   R(A) := RK(B) << RK(C)            */
198OP_SHR,/*   A B C   R(A) := RK(B) >> RK(C)            */
193199OP_UNM,/*   A B   R(A) := -R(B)               */
200OP_BNOT,/*   A B   R(A) := ~R(B)               */
194201OP_NOT,/*   A B   R(A) := not R(B)            */
195202OP_LEN,/*   A B   R(A) := length of R(B)            */
196203
197204OP_CONCAT,/*   A B C   R(A) := R(B).. ... ..R(C)         */
198205
199OP_JMP,/*   A sBx   pc+=sBx; if (A) close all upvalues >= R(A) + 1   */
206OP_JMP,/*   A sBx   pc+=sBx; if (A) close all upvalues >= R(A - 1)   */
200207OP_EQ,/*   A B C   if ((RK(B) == RK(C)) ~= A) then pc++      */
201208OP_LT,/*   A B C   if ((RK(B) <  RK(C)) ~= A) then pc++      */
202209OP_LE,/*   A B C   if ((RK(B) <= RK(C)) ~= A) then pc++      */
r242885r242886
231238
232239/*===========================================================================
233240  Notes:
234  (*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then `top' is
241  (*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then 'top' is
235242  set to last_result+1, so next open instruction (OP_CALL, OP_RETURN,
236  OP_SETLIST) may use `top'.
243  OP_SETLIST) may use 'top'.
237244
238245  (*) In OP_VARARG, if (B == 0) then use actual number of varargs and
239246  set top (like in OP_CALL with C == 0).
240247
241  (*) In OP_RETURN, if (B == 0) then return up to `top'.
248  (*) In OP_RETURN, if (B == 0) then return up to 'top'.
242249
243  (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next
250  (*) In OP_SETLIST, if (B == 0) then B = 'top'; if (C == 0) then next
244251  'instruction' is EXTRAARG(real C).
245252
246253  (*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.
r242885r242886
248255  (*) For comparisons, A specifies what condition the test should accept
249256  (true or false).
250257
251  (*) All `skips' (pc++) assume that next instruction is a jump.
258  (*) All 'skips' (pc++) assume that next instruction is a jump.
252259
253260===========================================================================*/
254261
trunk/3rdparty/lua/src/loslib.c
r242885r242886
11/*
2** $Id: loslib.c,v 1.40.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: loslib.c,v 1.54 2014/12/26 14:46:07 roberto Exp $
33** Standard Operating System library
44** See Copyright Notice in lua.h
55*/
66
7#define loslib_c
8#define LUA_LIB
79
10#include "lprefix.h"
11
12
813#include <errno.h>
914#include <locale.h>
1015#include <stdlib.h>
1116#include <string.h>
1217#include <time.h>
1318
14#define loslib_c
15#define LUA_LIB
16
1719#include "lua.h"
1820
1921#include "lauxlib.h"
2022#include "lualib.h"
2123
2224
25#if !defined(LUA_STRFTIMEOPTIONS)   /* { */
2326/*
2427** list of valid conversion specifiers for the 'strftime' function
2528*/
26#if !defined(LUA_STRFTIMEOPTIONS)
2729
28#if !defined(LUA_USE_POSIX)
30#if defined(LUA_USE_C89)
2931#define LUA_STRFTIMEOPTIONS   { "aAbBcdHIjmMpSUwWxXyYz%", "" }
30#else
32#else  /* C99 specification */
3133#define LUA_STRFTIMEOPTIONS \
32   { "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "" \
33     "", "E", "cCxXyY",  \
34   { "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "", \
35     "E", "cCxXyY",  \
3436     "O", "deHImMSuUVwWy" }
3537#endif
3638
37#endif
39#endif               /* } */
3840
3941
4042
43#if !defined(l_time_t)      /* { */
4144/*
45** type to represent time_t in Lua
46*/
47#define l_timet         lua_Integer
48#define l_pushtime(L,t)      lua_pushinteger(L,(lua_Integer)(t))
49#define l_checktime(L,a)   ((time_t)luaL_checkinteger(L,a))
50
51#endif            /* } */
52
53
54
55#if !defined(lua_tmpnam)   /* { */
56/*
4257** By default, Lua uses tmpnam except when POSIX is available, where it
4358** uses mkstemp.
4459*/
45#if defined(LUA_USE_MKSTEMP)
60
61#if defined(LUA_USE_POSIX)   /* { */
62
4663#include <unistd.h>
64
4765#define LUA_TMPNAMBUFSIZE   32
66
67#if !defined(LUA_TMPNAMTEMPLATE)
68#define LUA_TMPNAMTEMPLATE   "/tmp/lua_XXXXXX"
69#endif
70
4871#define lua_tmpnam(b,e) { \
49        strcpy(b, "/tmp/lua_XXXXXX"); \
72        strcpy(b, LUA_TMPNAMTEMPLATE); \
5073        e = mkstemp(b); \
5174        if (e != -1) close(e); \
5275        e = (e == -1); }
5376
54#elif !defined(lua_tmpnam)
77#else            /* }{ */
5578
79/* ISO C definitions */
5680#define LUA_TMPNAMBUFSIZE   L_tmpnam
5781#define lua_tmpnam(b,e)      { e = (tmpnam(b) == NULL); }
5882
59#endif
83#endif            /* } */
6084
85#endif            /* } */
6186
87
88
89#if !defined(l_gmtime)      /* { */
6290/*
6391** By default, Lua uses gmtime/localtime, except when POSIX is available,
6492** where it uses gmtime_r/localtime_r
6593*/
66#if defined(LUA_USE_GMTIME_R)
6794
95#if defined(LUA_USE_POSIX)   /* { */
96
6897#define l_gmtime(t,r)      gmtime_r(t,r)
6998#define l_localtime(t,r)   localtime_r(t,r)
7099
71#elif !defined(l_gmtime)
100#else            /* }{ */
72101
73#define l_gmtime(t,r)      ((void)r, gmtime(t))
74#define l_localtime(t,r)     ((void)r, localtime(t))
102/* ISO C definitions */
103#define l_gmtime(t,r)      ((void)(r)->tm_sec, gmtime(t))
104#define l_localtime(t,r)     ((void)(r)->tm_sec, localtime(t))
75105
76#endif
106#endif            /* } */
77107
108#endif            /* } */
78109
79110
111
80112static int os_execute (lua_State *L) {
81113  const char *cmd = luaL_optstring(L, 1, NULL);
82114  int stat = system(cmd);
r242885r242886
120152
121153
122154static int os_clock (lua_State *L) {
123  lua_pushnumber(L, ((lua_Number)(1.0*clock()))/(lua_Number)CLOCKS_PER_SEC);
155  lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
124156  return 1;
125157}
126158
r242885r242886
147179
148180static int getboolfield (lua_State *L, const char *key) {
149181  int res;
150  lua_getfield(L, -1, key);
151  res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1);
182  res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
152183  lua_pop(L, 1);
153184  return res;
154185}
r242885r242886
160191  res = (int)lua_tointegerx(L, -1, &isnum);
161192  if (!isnum) {
162193    if (d < 0)
163      return luaL_error(L, "field " LUA_QS " missing in date table", key);
194      return luaL_error(L, "field '%s' missing in date table", key);
164195    res = d;
165196  }
166197  lua_pop(L, 1);
r242885r242886
194225
195226static int os_date (lua_State *L) {
196227  const char *s = luaL_optstring(L, 1, "%c");
197  time_t t = luaL_opt(L, luaL_checknumber, 2, time(NULL));
228  time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
198229  struct tm tmr, *stm;
199230  if (*s == '!') {  /* UTC? */
200231    stm = l_gmtime(&t, &tmr);
201    s++;  /* skip `!' */
232    s++;  /* skip '!' */
202233  }
203234  else
204235    stm = l_localtime(&t, &tmr);
r242885r242886
255286    ts.tm_isdst = getboolfield(L, "isdst");
256287    t = mktime(&ts);
257288  }
258  if (t == (time_t)(-1))
289  if (t != (time_t)(l_timet)t)
290    luaL_error(L, "time result cannot be represented in this Lua instalation");
291  else if (t == (time_t)(-1))
259292    lua_pushnil(L);
260293  else
261    lua_pushnumber(L, (lua_Number)t);
294    l_pushtime(L, t);
262295  return 1;
263296}
264297
265298
266299static int os_difftime (lua_State *L) {
267  lua_pushnumber(L, difftime((luaL_checknumber(L, 1)),
268                             (luaL_optnumber(L, 2, 0))));
300  double res = difftime((l_checktime(L, 1)), (l_checktime(L, 2)));
301  lua_pushnumber(L, (lua_Number)res);
269302  return 1;
270303}
271304
r242885r242886
289322  if (lua_isboolean(L, 1))
290323    status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
291324  else
292    status = luaL_optint(L, 1, EXIT_SUCCESS);
325    status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
293326  if (lua_toboolean(L, 2))
294327    lua_close(L);
295328  if (L) exit(status);  /* 'if' to avoid warnings for unreachable 'return' */
trunk/3rdparty/lua/src/lparser.c
r242885r242886
11/*
2** $Id: lparser.c,v 2.130.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lparser.c,v 2.147 2014/12/27 20:31:43 roberto Exp $
33** Lua Parser
44** See Copyright Notice in lua.h
55*/
66
7#define lparser_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <string.h>
914
10#define lparser_c
11#define LUA_CORE
12
1315#include "lua.h"
1416
1517#include "lcode.h"
r242885r242886
3537#define hasmultret(k)      ((k) == VCALL || (k) == VVARARG)
3638
3739
40/* because all strings are unified by the scanner, the parser
41   can use pointer equality for string equality */
42#define eqstr(a,b)   ((a) == (b))
3843
44
3945/*
4046** nodes for block list (list of active blocks)
4147*/
4248typedef struct BlockCnt {
4349  struct BlockCnt *previous;  /* chain */
44  short firstlabel;  /* index of first label in this block */
45  short firstgoto;  /* index of first pending goto in this block */
50  int firstlabel;  /* index of first label in this block */
51  int firstgoto;  /* index of first pending goto in this block */
4652  lu_byte nactvar;  /* # active locals outside the block */
4753  lu_byte upval;  /* true if some variable in the block is an upvalue */
48  lu_byte isloop;  /* true if `block' is a loop */
54  lu_byte isloop;  /* true if 'block' is a loop */
4955} BlockCnt;
5056
5157
r242885r242886
5763static void expr (LexState *ls, expdesc *v);
5864
5965
60static void anchor_token (LexState *ls) {
61  /* last token from outer function must be EOS */
62  lua_assert(ls->fs != NULL || ls->t.token == TK_EOS);
63  if (ls->t.token == TK_NAME || ls->t.token == TK_STRING) {
64    TString *ts = ls->t.seminfo.ts;
65    luaX_newstring(ls, getstr(ts), ts->tsv.len);
66  }
67}
68
69
7066/* semantic error */
7167static l_noret semerror (LexState *ls, const char *msg) {
72  ls->t.token = 0;  /* remove 'near to' from final message */
68  ls->t.token = 0;  /* remove "near <token>" from final message */
7369  luaX_syntaxerror(ls, msg);
7470}
7571
r242885r242886
222218  int i;
223219  Upvaldesc *up = fs->f->upvalues;
224220  for (i = 0; i < fs->nups; i++) {
225    if (luaS_eqstr(up[i].name, name)) return i;
221    if (eqstr(up[i].name, name)) return i;
226222  }
227223  return -1;  /* not found */
228224}
r242885r242886
246242static int searchvar (FuncState *fs, TString *n) {
247243  int i;
248244  for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
249    if (luaS_eqstr(n, getlocvar(fs, i)->varname))
245    if (eqstr(n, getlocvar(fs, i)->varname))
250246      return i;
251247  }
252248  return -1;  /* not found */
r242885r242886
342338  FuncState *fs = ls->fs;
343339  Labellist *gl = &ls->dyd->gt;
344340  Labeldesc *gt = &gl->arr[g];
345  lua_assert(luaS_eqstr(gt->name, label->name));
341  lua_assert(eqstr(gt->name, label->name));
346342  if (gt->nactvar < label->nactvar) {
347343    TString *vname = getlocvar(fs, gt->nactvar)->varname;
348344    const char *msg = luaO_pushfstring(ls->L,
349      "<goto %s> at line %d jumps into the scope of local " LUA_QS,
345      "<goto %s> at line %d jumps into the scope of local '%s'",
350346      getstr(gt->name), gt->line, getstr(vname));
351347    semerror(ls, msg);
352348  }
r242885r242886
369365  /* check labels in current block for a match */
370366  for (i = bl->firstlabel; i < dyd->label.n; i++) {
371367    Labeldesc *lb = &dyd->label.arr[i];
372    if (luaS_eqstr(lb->name, gt->name)) {  /* correct label? */
368    if (eqstr(lb->name, gt->name)) {  /* correct label? */
373369      if (gt->nactvar > lb->nactvar &&
374370          (bl->upval || dyd->label.n > bl->firstlabel))
375371        luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
r242885r242886
390386  l->arr[n].line = line;
391387  l->arr[n].nactvar = ls->fs->nactvar;
392388  l->arr[n].pc = pc;
393  l->n++;
389  l->n = n + 1;
394390  return n;
395391}
396392
r242885r242886
403399  Labellist *gl = &ls->dyd->gt;
404400  int i = ls->fs->bl->firstgoto;
405401  while (i < gl->n) {
406    if (luaS_eqstr(gl->arr[i].name, lb->name))
402    if (eqstr(gl->arr[i].name, lb->name))
407403      closegoto(ls, i, lb);
408404    else
409405      i++;
r242885r242886
412408
413409
414410/*
415** "export" pending gotos to outer level, to check them against
411** export pending gotos to outer level, to check them against
416412** outer labels; if the block being exited has upvalues, and
417413** the goto exits the scope of any variable (which can be the
418414** upvalue), close those variables being exited.
r242885r242886
448444
449445
450446/*
451** create a label named "break" to resolve break statements
447** create a label named 'break' to resolve break statements
452448*/
453449static void breaklabel (LexState *ls) {
454450  TString *n = luaS_new(ls->L, "break");
r242885r242886
463459static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
464460  const char *msg = isreserved(gt->name)
465461                    ? "<%s> at line %d not inside a loop"
466                    : "no visible label " LUA_QS " for <goto> at line %d";
462                    : "no visible label '%s' for <goto> at line %d";
467463  msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
468464  semerror(ls, msg);
469465}
r242885r242886
525521
526522
527523static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
528  lua_State *L = ls->L;
529524  Proto *f;
530525  fs->prev = ls->fs;  /* linked list of funcstates */
531526  fs->ls = ls;
r242885r242886
544539  f = fs->f;
545540  f->source = ls->source;
546541  f->maxstacksize = 2;  /* registers 0/1 are always valid */
547  fs->h = luaH_new(L);
548  /* anchor table of constants (to avoid being collected) */
549  sethvalue2s(L, L->top, fs->h);
550  incr_top(L);
551542  enterblock(fs, bl, 0);
552543}
553544
r242885r242886
572563  f->sizeupvalues = fs->nups;
573564  lua_assert(fs->bl == NULL);
574565  ls->fs = fs->prev;
575  /* last token read was anchored in defunct function; must re-anchor it */
576  anchor_token(ls);
577  L->top--;  /* pop table of constants */
578566  luaC_checkGC(L);
579567}
580568
r242885r242886
588576/*
589577** check whether current token is in the follow set of a block.
590578** 'until' closes syntactical blocks, but do not close scope,
591** so it handled in separate.
579** so it is handled in separate.
592580*/
593581static int block_follow (LexState *ls, int withuntil) {
594582  switch (ls->t.token) {
r242885r242886
602590
603591
604592static void statlist (LexState *ls) {
605  /* statlist -> { stat [`;'] } */
593  /* statlist -> { stat [';'] } */
606594  while (!block_follow(ls, 1)) {
607595    if (ls->t.token == TK_RETURN) {
608596      statement(ls);
r242885r242886
643631struct ConsControl {
644632  expdesc v;  /* last list item read */
645633  expdesc *t;  /* table descriptor */
646  int nh;  /* total number of `record' elements */
634  int nh;  /* total number of 'record' elements */
647635  int na;  /* total number of array elements */
648636  int tostore;  /* number of array elements pending to be stored */
649637};
650638
651639
652640static void recfield (LexState *ls, struct ConsControl *cc) {
653  /* recfield -> (NAME | `['exp1`]') = exp1 */
641  /* recfield -> (NAME | '['exp1']') = exp1 */
654642  FuncState *fs = ls->fs;
655643  int reg = ls->fs->freereg;
656644  expdesc key, val;
r242885r242886
757745
758746
759747static void parlist (LexState *ls) {
760  /* parlist -> [ param { `,' param } ] */
748  /* parlist -> [ param { ',' param } ] */
761749  FuncState *fs = ls->fs;
762750  Proto *f = fs->f;
763751  int nparams = 0;
764752  f->is_vararg = 0;
765  if (ls->t.token != ')') {  /* is `parlist' not empty? */
753  if (ls->t.token != ')') {  /* is 'parlist' not empty? */
766754    do {
767755      switch (ls->t.token) {
768756        case TK_NAME: {  /* param -> NAME */
r242885r242886
770758          nparams++;
771759          break;
772760        }
773        case TK_DOTS: {  /* param -> `...' */
761        case TK_DOTS: {  /* param -> '...' */
774762          luaX_next(ls);
775763          f->is_vararg = 1;
776764          break;
777765        }
778        default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
766        default: luaX_syntaxerror(ls, "<name> or '...' expected");
779767      }
780768    } while (!f->is_vararg && testnext(ls, ','));
781769  }
r242885r242886
786774
787775
788776static void body (LexState *ls, expdesc *e, int ismethod, int line) {
789  /* body ->  `(' parlist `)' block END */
777  /* body ->  '(' parlist ')' block END */
790778  FuncState new_fs;
791779  BlockCnt bl;
792780  new_fs.f = addprototype(ls);
r242885r242886
808796
809797
810798static int explist (LexState *ls, expdesc *v) {
811  /* explist -> expr { `,' expr } */
799  /* explist -> expr { ',' expr } */
812800  int n = 1;  /* at least one expression */
813801  expr(ls, v);
814802  while (testnext(ls, ',')) {
r242885r242886
825813  expdesc args;
826814  int base, nparams;
827815  switch (ls->t.token) {
828    case '(': {  /* funcargs -> `(' [ explist ] `)' */
816    case '(': {  /* funcargs -> '(' [ explist ] ')' */
829817      luaX_next(ls);
830818      if (ls->t.token == ')')  /* arg list is empty? */
831819        args.k = VVOID;
r242885r242886
842830    }
843831    case TK_STRING: {  /* funcargs -> STRING */
844832      codestring(ls, &args, ls->t.seminfo.ts);
845      luaX_next(ls);  /* must use `seminfo' before `next' */
833      luaX_next(ls);  /* must use 'seminfo' before 'next' */
846834      break;
847835    }
848836    default: {
r242885r242886
908896        fieldsel(ls, v);
909897        break;
910898      }
911      case '[': {  /* `[' exp1 `]' */
899      case '[': {  /* '[' exp1 ']' */
912900        expdesc key;
913901        luaK_exp2anyregup(fs, v);
914902        yindex(ls, &key);
915903        luaK_indexed(fs, v, &key);
916904        break;
917905      }
918      case ':': {  /* `:' NAME funcargs */
906      case ':': {  /* ':' NAME funcargs */
919907        expdesc key;
920908        luaX_next(ls);
921909        checkname(ls, &key);
r242885r242886
935923
936924
937925static void simpleexp (LexState *ls, expdesc *v) {
938  /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
926  /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
939927                  constructor | FUNCTION body | suffixedexp */
940928  switch (ls->t.token) {
941    case TK_NUMBER: {
942      init_exp(v, VKNUM, 0);
929    case TK_FLT: {
930      init_exp(v, VKFLT, 0);
943931      v->u.nval = ls->t.seminfo.r;
944932      break;
945933    }
934    case TK_INT: {
935      init_exp(v, VKINT, 0);
936      v->u.ival = ls->t.seminfo.i;
937      break;
938    }
946939    case TK_STRING: {
947940      codestring(ls, v, ls->t.seminfo.ts);
948941      break;
r242885r242886
962955    case TK_DOTS: {  /* vararg */
963956      FuncState *fs = ls->fs;
964957      check_condition(ls, fs->f->is_vararg,
965                      "cannot use " LUA_QL("...") " outside a vararg function");
958                      "cannot use '...' outside a vararg function");
966959      init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
967960      break;
968961    }
r242885r242886
988981  switch (op) {
989982    case TK_NOT: return OPR_NOT;
990983    case '-': return OPR_MINUS;
984    case '~': return OPR_BNOT;
991985    case '#': return OPR_LEN;
992986    default: return OPR_NOUNOPR;
993987  }
r242885r242886
999993    case '+': return OPR_ADD;
1000994    case '-': return OPR_SUB;
1001995    case '*': return OPR_MUL;
1002    case '/': return OPR_DIV;
1003996    case '%': return OPR_MOD;
1004997    case '^': return OPR_POW;
998    case '/': return OPR_DIV;
999    case TK_IDIV: return OPR_IDIV;
1000    case '&': return OPR_BAND;
1001    case '|': return OPR_BOR;
1002    case '~': return OPR_BXOR;
1003    case TK_SHL: return OPR_SHL;
1004    case TK_SHR: return OPR_SHR;
10051005    case TK_CONCAT: return OPR_CONCAT;
10061006    case TK_NE: return OPR_NE;
10071007    case TK_EQ: return OPR_EQ;
r242885r242886
10201020  lu_byte left;  /* left priority for each binary operator */
10211021  lu_byte right; /* right priority */
10221022} priority[] = {  /* ORDER OPR */
1023   {6, 6}, {6, 6}, {7, 7}, {7, 7}, {7, 7},  /* `+' `-' `*' `/' `%' */
1024   {10, 9}, {5, 4},                 /* ^, .. (right associative) */
1025   {3, 3}, {3, 3}, {3, 3},          /* ==, <, <= */
1026   {3, 3}, {3, 3}, {3, 3},          /* ~=, >, >= */
1027   {2, 2}, {1, 1}                   /* and, or */
1023   {10, 10}, {10, 10},           /* '+' '-' */
1024   {11, 11}, {11, 11},           /* '*' '%' */
1025   {14, 13},                  /* '^' (right associative) */
1026   {11, 11}, {11, 11},           /* '/' '//' */
1027   {6, 6}, {4, 4}, {5, 5},   /* '&' '|' '~' */
1028   {7, 7}, {7, 7},           /* '<<' '>>' */
1029   {9, 8},                   /* '..' (right associative) */
1030   {3, 3}, {3, 3}, {3, 3},   /* ==, <, <= */
1031   {3, 3}, {3, 3}, {3, 3},   /* ~=, >, >= */
1032   {2, 2}, {1, 1}            /* and, or */
10281033};
10291034
1030#define UNARY_PRIORITY   8  /* priority for unary operators */
1035#define UNARY_PRIORITY   12  /* priority for unary operators */
10311036
10321037
10331038/*
10341039** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1035** where `binop' is any binary operator with a priority higher than `limit'
1040** where 'binop' is any binary operator with a priority higher than 'limit'
10361041*/
10371042static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
10381043  BinOpr op;
r242885r242886
10461051    luaK_prefix(ls->fs, uop, v, line);
10471052  }
10481053  else simpleexp(ls, v);
1049  /* expand while operators have priorities higher than `limit' */
1054  /* expand while operators have priorities higher than 'limit' */
10501055  op = getbinopr(ls->t.token);
10511056  while (op != OPR_NOBINOPR && priority[op].left > limit) {
10521057    expdesc v2;
r242885r242886
11461151                    "C levels");
11471152    assignment(ls, &nv, nvars+1);
11481153  }
1149  else {  /* assignment -> `=' explist */
1154  else {  /* assignment -> '=' explist */
11501155    int nexps;
11511156    checknext(ls, '=');
11521157    nexps = explist(ls, &e);
r242885r242886
11701175  /* cond -> exp */
11711176  expdesc v;
11721177  expr(ls, &v);  /* read condition */
1173  if (v.k == VNIL) v.k = VFALSE;  /* `falses' are all equal here */
1178  if (v.k == VNIL) v.k = VFALSE;  /* 'falses' are all equal here */
11741179  luaK_goiftrue(ls->fs, &v);
11751180  return v.f;
11761181}
r242885r242886
11951200static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
11961201  int i;
11971202  for (i = fs->bl->firstlabel; i < ll->n; i++) {
1198    if (luaS_eqstr(label, ll->arr[i].name)) {
1203    if (eqstr(label, ll->arr[i].name)) {
11991204      const char *msg = luaO_pushfstring(fs->ls->L,
1200                          "label " LUA_QS " already defined on line %d",
1205                          "label '%s' already defined on line %d",
12011206                          getstr(label), ll->arr[i].line);
12021207      semerror(fs->ls, msg);
12031208    }
r242885r242886
13211326  if (testnext(ls, ','))
13221327    exp1(ls);  /* optional step */
13231328  else {  /* default step = 1 */
1324    luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
1329    luaK_codek(fs, fs->freereg, luaK_intK(fs, 1));
13251330    luaK_reserveregs(fs, 1);
13261331  }
13271332  forbody(ls, base, line, 1, 1);
r242885r242886
13591364  TString *varname;
13601365  BlockCnt bl;
13611366  enterblock(fs, &bl, 1);  /* scope for loop and control variables */
1362  luaX_next(ls);  /* skip `for' */
1367  luaX_next(ls);  /* skip 'for' */
13631368  varname = str_checkname(ls);  /* first variable name */
13641369  switch (ls->t.token) {
13651370    case '=': fornum(ls, varname, line); break;
13661371    case ',': case TK_IN: forlist(ls, varname); break;
1367    default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
1372    default: luaX_syntaxerror(ls, "'=' or 'in' expected");
13681373  }
13691374  check_match(ls, TK_END, TK_FOR, line);
1370  leaveblock(fs);  /* loop scope (`break' jumps to this point) */
1375  leaveblock(fs);  /* loop scope ('break' jumps to this point) */
13711376}
13721377
13731378
r242885r242886
13971402    enterblock(fs, &bl, 0);
13981403    jf = v.f;
13991404  }
1400  statlist(ls);  /* `then' part */
1405  statlist(ls);  /* 'then' part */
14011406  leaveblock(fs);
14021407  if (ls->t.token == TK_ELSE ||
14031408      ls->t.token == TK_ELSEIF)  /* followed by 'else'/'elseif'? */
r242885r242886
14141419  while (ls->t.token == TK_ELSEIF)
14151420    test_then_block(ls, &escapelist);  /* ELSEIF cond THEN block */
14161421  if (testnext(ls, TK_ELSE))
1417    block(ls);  /* `else' part */
1422    block(ls);  /* 'else' part */
14181423  check_match(ls, TK_END, TK_IF, line);
14191424  luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
14201425}
r242885r242886
14321437
14331438
14341439static void localstat (LexState *ls) {
1435  /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
1440  /* stat -> LOCAL NAME {',' NAME} ['=' explist] */
14361441  int nvars = 0;
14371442  int nexps;
14381443  expdesc e;
r242885r242886
14521457
14531458
14541459static int funcname (LexState *ls, expdesc *v) {
1455  /* funcname -> NAME {fieldsel} [`:' NAME] */
1460  /* funcname -> NAME {fieldsel} [':' NAME] */
14561461  int ismethod = 0;
14571462  singlevar(ls, v);
14581463  while (ls->t.token == '.')
r242885r242886
14731478  ismethod = funcname(ls, &v);
14741479  body(ls, &b, ismethod, line);
14751480  luaK_storevar(ls->fs, &v, &b);
1476  luaK_fixline(ls->fs, line);  /* definition `happens' in the first line */
1481  luaK_fixline(ls->fs, line);  /* definition "happens" in the first line */
14771482}
14781483
14791484
r242885r242886
15151520      if (nret == 1)  /* only one single value? */
15161521        first = luaK_exp2anyreg(fs, &e);
15171522      else {
1518        luaK_exp2nextreg(fs, &e);  /* values must go to the `stack' */
1519        first = fs->nactvar;  /* return all `active' values */
1523        luaK_exp2nextreg(fs, &e);  /* values must go to the stack */
1524        first = fs->nactvar;  /* return all active values */
15201525        lua_assert(nret == fs->freereg - first);
15211526      }
15221527    }
r242885r242886
16151620}
16161621
16171622
1618Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1619                      Dyndata *dyd, const char *name, int firstchar) {
1623LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1624                       Dyndata *dyd, const char *name, int firstchar) {
16201625  LexState lexstate;
16211626  FuncState funcstate;
1622  Closure *cl = luaF_newLclosure(L, 1);  /* create main closure */
1623  /* anchor closure (to avoid being collected) */
1624  setclLvalue(L, L->top, cl);
1627  LClosure *cl = luaF_newLclosure(L, 1);  /* create main closure */
1628  setclLvalue(L, L->top, cl);  /* anchor it (to avoid being collected) */
16251629  incr_top(L);
1626  funcstate.f = cl->l.p = luaF_newproto(L);
1630  lexstate.h = luaH_new(L);  /* create table for scanner */
1631  sethvalue(L, L->top, lexstate.h);  /* anchor it */
1632  incr_top(L);
1633  funcstate.f = cl->p = luaF_newproto(L);
16271634  funcstate.f->source = luaS_new(L, name);  /* create and anchor TString */
1635  lua_assert(iswhite(funcstate.f));  /* do not need barrier here */
16281636  lexstate.buff = buff;
16291637  lexstate.dyd = dyd;
16301638  dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
r242885r242886
16331641  lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
16341642  /* all scopes should be correctly finished */
16351643  lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1636  return cl;  /* it's on the stack too */
1644  L->top--;  /* remove scanner's table */
1645  return cl;  /* closure is on the stack, too */
16371646}
16381647
trunk/3rdparty/lua/src/lparser.h
r242885r242886
11/*
2** $Id: lparser.h,v 1.70.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lparser.h,v 1.74 2014/10/25 11:50:46 roberto Exp $
33** Lua Parser
44** See Copyright Notice in lua.h
55*/
r242885r242886
2121  VNIL,
2222  VTRUE,
2323  VFALSE,
24  VK,      /* info = index of constant in `k' */
25  VKNUM,   /* nval = numerical value */
24  VK,      /* info = index of constant in 'k' */
25  VKFLT,   /* nval = numerical float value */
26  VKINT,   /* nval = numerical integer value */
2627  VNONRELOC,   /* info = result register */
2728  VLOCAL,   /* info = local register */
2829  VUPVAL,       /* info = index of upvalue in 'upvalues' */
r242885r242886
4647      lu_byte vt;  /* whether 't' is register (VLOCAL) or upvalue (VUPVAL) */
4748    } ind;
4849    int info;  /* for generic use */
49    lua_Number nval;  /* for VKNUM */
50    lua_Number nval;  /* for VKFLT */
51    lua_Integer ival;    /* for VKINT */
5052  } u;
51  int t;  /* patch list of `exit when true' */
52  int f;  /* patch list of `exit when false' */
53  int t;  /* patch list of 'exit when true' */
54  int f;  /* patch list of 'exit when false' */
5355} expdesc;
5456
5557
r242885r242886
9597/* state needed to generate code for a given function */
9698typedef struct FuncState {
9799  Proto *f;  /* current function header */
98  Table *h;  /* table to find (and reuse) elements in `k' */
99100  struct FuncState *prev;  /* enclosing function */
100101  struct LexState *ls;  /* lexical state */
101102  struct BlockCnt *bl;  /* chain of current blocks */
102  int pc;  /* next position to code (equivalent to `ncode') */
103  int pc;  /* next position to code (equivalent to 'ncode') */
103104  int lasttarget;   /* 'label' of last 'jump label' */
104  int jpc;  /* list of pending jumps to `pc' */
105  int nk;  /* number of elements in `k' */
106  int np;  /* number of elements in `p' */
105  int jpc;  /* list of pending jumps to 'pc' */
106  int nk;  /* number of elements in 'k' */
107  int np;  /* number of elements in 'p' */
107108  int firstlocal;  /* index of first local var (in Dyndata array) */
108109  short nlocvars;  /* number of elements in 'f->locvars' */
109110  lu_byte nactvar;  /* number of active local variables */
r242885r242886
112113} FuncState;
113114
114115
115LUAI_FUNC Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
116                                Dyndata *dyd, const char *name, int firstchar);
116LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
117                                 Dyndata *dyd, const char *name, int firstchar);
117118
118119
119120#endif
trunk/3rdparty/lua/src/lprefix.h
r0r242886
1/*
2** $Id: lprefix.h,v 1.2 2014/12/29 16:54:13 roberto Exp $
3** Definitions for Lua code that must come before any other header file
4** See Copyright Notice in lua.h
5*/
6
7#ifndef lprefix_h
8#define lprefix_h
9
10
11/*
12** Allows POSIX/XSI stuff
13*/
14#if !defined(LUA_USE_C89)   /* { */
15
16#if !defined(_XOPEN_SOURCE)
17#define _XOPEN_SOURCE           600
18#elif _XOPEN_SOURCE == 0
19#undef _XOPEN_SOURCE  /* use -D_XOPEN_SOURCE=0 to undefine it */
20#endif
21
22/*
23** Allows manipulation of large files in gcc and some other compilers
24*/
25#if !defined(LUA_32BITS) && !defined(_FILE_OFFSET_BITS)
26#define _LARGEFILE_SOURCE       1
27#define _FILE_OFFSET_BITS       64
28#endif
29
30#endif            /* } */
31
32
33/*
34** Windows stuff
35*/
36#if defined(_WIN32)    /* { */
37
38#if !defined(_CRT_SECURE_NO_WARNINGS)
39#define _CRT_SECURE_NO_WARNINGS  /* avoid warnings about ISO C functions */
40#endif
41
42#endif         /* } */
43
44#endif
45
trunk/3rdparty/lua/src/lstate.c
r242885r242886
11/*
2** $Id: lstate.c,v 2.99.1.2 2013/11/08 17:45:31 roberto Exp $
2** $Id: lstate.c,v 2.127 2014/11/02 19:33:33 roberto Exp $
33** Global State
44** See Copyright Notice in lua.h
55*/
66
7#define lstate_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <stddef.h>
914#include <string.h>
1015
11#define lstate_c
12#define LUA_CORE
13
1416#include "lua.h"
1517
1618#include "lapi.h"
r242885r242886
3032#define LUAI_GCPAUSE   200  /* 200% */
3133#endif
3234
33#if !defined(LUAI_GCMAJOR)
34#define LUAI_GCMAJOR   200  /* 200% */
35#endif
36
3735#if !defined(LUAI_GCMUL)
3836#define LUAI_GCMUL   200 /* GC runs 'twice the speed' of memory allocation */
3937#endif
r242885r242886
5755** thread state + extra space
5856*/
5957typedef struct LX {
60#if defined(LUAI_EXTRASPACE)
61  char buff[LUAI_EXTRASPACE];
62#endif
58  lu_byte extra_[LUA_EXTRASPACE];
6359  lua_State l;
6460} LX;
6561
r242885r242886
7874
7975
8076/*
81** Compute an initial seed as random as possible. In ANSI, rely on
82** Address Space Layout Randomization (if present) to increase
83** randomness..
77** Compute an initial seed as random as possible. Rely on Address Space
78** Layout Randomization (if present) to increase randomness..
8479*/
8580#define addbuff(b,p,e) \
8681  { size_t t = cast(size_t, e); \
r242885r242886
119114}
120115
121116
117/*
118** free all CallInfo structures not in use by a thread
119*/
122120void luaE_freeCI (lua_State *L) {
123121  CallInfo *ci = L->ci;
124122  CallInfo *next = ci->next;
r242885r242886
130128}
131129
132130
131/*
132** free half of the CallInfo structures not in use by a thread
133*/
134void luaE_shrinkCI (lua_State *L) {
135  CallInfo *ci = L->ci;
136  while (ci->next != NULL) {  /* while there is 'next' */
137    CallInfo *next2 = ci->next->next;  /* next's next */
138    if (next2 == NULL) break;
139    luaM_free(L, ci->next);  /* remove next */
140    ci->next = next2;  /* remove 'next' from the list */
141    next2->previous = ci;
142    ci = next2;
143  }
144}
145
146
133147static void stack_init (lua_State *L1, lua_State *L) {
134148  int i; CallInfo *ci;
135149  /* initialize stack array */
r242885r242886
163177** Create registry table and its predefined values
164178*/
165179static void init_registry (lua_State *L, global_State *g) {
166  TValue mt;
180  TValue temp;
167181  /* create registry */
168182  Table *registry = luaH_new(L);
169183  sethvalue(L, &g->l_registry, registry);
170184  luaH_resize(L, registry, LUA_RIDX_LAST, 0);
171185  /* registry[LUA_RIDX_MAINTHREAD] = L */
172  setthvalue(L, &mt, L);
173  luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &mt);
186  setthvalue(L, &temp, L);  /* temp = L */
187  luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp);
174188  /* registry[LUA_RIDX_GLOBALS] = table of globals */
175  sethvalue(L, &mt, luaH_new(L));
176  luaH_setint(L, registry, LUA_RIDX_GLOBALS, &mt);
189  sethvalue(L, &temp, luaH_new(L));  /* temp = new table (global table) */
190  luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp);
177191}
178192
179193
180194/*
181** open parts of the state that may cause memory-allocation errors
195** open parts of the state that may cause memory-allocation errors.
196** ('g->version' != NULL flags that the state was completely build)
182197*/
183198static void f_luaopen (lua_State *L, void *ud) {
184199  global_State *g = G(L);
r242885r242886
190205  luaX_init(L);
191206  /* pre-create memory-error message */
192207  g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
193  luaS_fix(g->memerrmsg);  /* it should never be collected */
208  luaC_fix(L, obj2gco(g->memerrmsg));  /* it should never be collected */
194209  g->gcrunning = 1;  /* allow gc */
195210  g->version = lua_version(NULL);
196211  luai_userstateopen(L);
r242885r242886
198213
199214
200215/*
201** preinitialize a state with consistent values without allocating
216** preinitialize a thread with consistent values without allocating
202217** any memory (to avoid errors)
203218*/
204static void preinit_state (lua_State *L, global_State *g) {
219static void preinit_thread (lua_State *L, global_State *g) {
205220  G(L) = g;
206221  L->stack = NULL;
207222  L->ci = NULL;
208223  L->stacksize = 0;
224  L->twups = L;  /* thread has no upvalues */
209225  L->errorJmp = NULL;
210226  L->nCcalls = 0;
211227  L->hook = NULL;
r242885r242886
235251
236252
237253LUA_API lua_State *lua_newthread (lua_State *L) {
254  global_State *g = G(L);
238255  lua_State *L1;
239256  lua_lock(L);
240257  luaC_checkGC(L);
241  L1 = &luaC_newobj(L, LUA_TTHREAD, sizeof(LX), NULL, offsetof(LX, l))->th;
258  /* create new thread */
259  L1 = &cast(LX *, luaM_newobject(L, LUA_TTHREAD, sizeof(LX)))->l;
260  L1->marked = luaC_white(g);
261  L1->tt = LUA_TTHREAD;
262  /* link it on list 'allgc' */
263  L1->next = g->allgc;
264  g->allgc = obj2gco(L1);
265  /* anchor it on L stack */
242266  setthvalue(L, L->top, L1);
243267  api_incr_top(L);
244  preinit_state(L1, G(L));
268  preinit_thread(L1, g);
245269  L1->hookmask = L->hookmask;
246270  L1->basehookcount = L->basehookcount;
247271  L1->hook = L->hook;
248272  resethookcount(L1);
273  /* initialize L1 extra space */
274  memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread),
275         LUA_EXTRASPACE);
249276  luai_userstatethread(L, L1);
250277  stack_init(L1, L);  /* init stack */
251278  lua_unlock(L);
r242885r242886
273300  g = &l->g;
274301  L->next = NULL;
275302  L->tt = LUA_TTHREAD;
276  g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);
303  g->currentwhite = bitmask(WHITE0BIT);
277304  L->marked = luaC_white(g);
278  g->gckind = KGC_NORMAL;
279  preinit_state(L, g);
305  preinit_thread(L, g);
280306  g->frealloc = f;
281307  g->ud = ud;
282308  g->mainthread = L;
283309  g->seed = makeseed(L);
284  g->uvhead.u.l.prev = &g->uvhead;
285  g->uvhead.u.l.next = &g->uvhead;
286310  g->gcrunning = 0;  /* no GC while building state */
287311  g->GCestimate = 0;
288  g->strt.size = 0;
289  g->strt.nuse = 0;
312  g->strt.size = g->strt.nuse = 0;
290313  g->strt.hash = NULL;
291314  setnilvalue(&g->l_registry);
292315  luaZ_initbuffer(L, &g->buff);
293316  g->panic = NULL;
294317  g->version = NULL;
295318  g->gcstate = GCSpause;
296  g->allgc = NULL;
297  g->finobj = NULL;
298  g->tobefnz = NULL;
299  g->sweepgc = g->sweepfin = NULL;
319  g->gckind = KGC_NORMAL;
320  g->allgc = g->finobj = g->tobefnz = g->fixedgc = NULL;
321  g->sweepgc = NULL;
300322  g->gray = g->grayagain = NULL;
301323  g->weak = g->ephemeron = g->allweak = NULL;
324  g->twups = NULL;
302325  g->totalbytes = sizeof(LG);
303326  g->GCdebt = 0;
327  g->gcfinnum = 0;
304328  g->gcpause = LUAI_GCPAUSE;
305  g->gcmajorinc = LUAI_GCMAJOR;
306329  g->gcstepmul = LUAI_GCMUL;
307330  for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
308331  if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
trunk/3rdparty/lua/src/lstate.h
r242885r242886
11/*
2** $Id: lstate.h,v 2.82.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lstate.h,v 2.119 2014/10/30 18:53:28 roberto Exp $
33** Global State
44** See Copyright Notice in lua.h
55*/
r242885r242886
1616
1717/*
1818
19** Some notes about garbage-collected objects:  All objects in Lua must
20** be kept somehow accessible until being freed.
19** Some notes about garbage-collected objects: All objects in Lua must
20** be kept somehow accessible until being freed, so all objects always
21** belong to one (and only one) of these lists, using field 'next' of
22** the 'CommonHeader' for the link:
2123**
22** Lua keeps most objects linked in list g->allgc. The link uses field
23** 'next' of the CommonHeader.
24**
25** Strings are kept in several lists headed by the array g->strt.hash.
26**
27** Open upvalues are not subject to independent garbage collection. They
28** are collected together with their respective threads. Lua keeps a
29** double-linked list with all open upvalues (g->uvhead) so that it can
30** mark objects referred by them. (They are always gray, so they must
31** be remarked in the atomic step. Usually their contents would be marked
32** when traversing the respective threads, but the thread may already be
33** dead, while the upvalue is still accessible through closures.)
34**
35** Objects with finalizers are kept in the list g->finobj.
36**
37** The list g->tobefnz links all objects being finalized.
24** 'allgc': all objects not marked for finalization;
25** 'finobj': all objects marked for finalization;
26** 'tobefnz': all objects ready to be finalized;
27** 'fixedgc': all objects that are not to be collected (currently
28** only small strings, such as reserved words).
3829
3930*/
4031
r242885r242886
5344/* kinds of Garbage Collection */
5445#define KGC_NORMAL   0
5546#define KGC_EMERGENCY   1   /* gc was forced by an allocation failure */
56#define KGC_GEN      2   /* generational collection */
5747
5848
5949typedef struct stringtable {
60  GCObject **hash;
61  lu_int32 nuse;  /* number of elements */
50  TString **hash;
51  int nuse;  /* number of elements */
6252  int size;
6353} stringtable;
6454
6555
6656/*
67** information about a call
57** Information about a call.
58** When a thread yields, 'func' is adjusted to pretend that the
59** top function has only the yielded values in its stack; in that
60** case, the actual 'func' value is saved in field 'extra'.
61** When a function calls another with a continuation, 'extra' keeps
62** the function index so that, in case of errors, the continuation
63** function can be called with the correct top.
6864*/
6965typedef struct CallInfo {
7066  StkId func;  /* function index in the stack */
7167  StkId   top;  /* top for this function */
7268  struct CallInfo *previous, *next;  /* dynamic call link */
73  short nresults;  /* expected number of results from this function */
74  lu_byte callstatus;
75  ptrdiff_t extra;
7669  union {
7770    struct {  /* only for Lua functions */
7871      StkId base;  /* base for this function */
7972      const Instruction *savedpc;
8073    } l;
8174    struct {  /* only for C functions */
82      int ctx;  /* context info. in case of yields */
83      lua_CFunction k;  /* continuation in case of yields */
75      lua_KFunction k;  /* continuation in case of yields */
8476      ptrdiff_t old_errfunc;
85      lu_byte old_allowhook;
86      lu_byte status;
77      lua_KContext ctx;  /* context info. in case of yields */
8778    } c;
8879  } u;
80  ptrdiff_t extra;
81  short nresults;  /* expected number of results from this function */
82  lu_byte callstatus;
8983} CallInfo;
9084
9185
9286/*
9387** Bits in CallInfo status
9488*/
95#define CIST_LUA   (1<<0)   /* call is running a Lua function */
96#define CIST_HOOKED   (1<<1)   /* call is running a debug hook */
97#define CIST_REENTRY   (1<<2)   /* call is running on same invocation of
89#define CIST_OAH   (1<<0)   /* original value of 'allowhook' */
90#define CIST_LUA   (1<<1)   /* call is running a Lua function */
91#define CIST_HOOKED   (1<<2)   /* call is running a debug hook */
92#define CIST_REENTRY   (1<<3)   /* call is running on same invocation of
9893                                   luaV_execute of previous call */
99#define CIST_YIELDED   (1<<3)   /* call reentered after suspension */
10094#define CIST_YPCALL   (1<<4)   /* call is a yieldable protected call */
101#define CIST_STAT   (1<<5)   /* call has an error status (pcall) */
102#define CIST_TAIL   (1<<6)   /* call was tail called */
103#define CIST_HOOKYIELD   (1<<7)   /* last hook called yielded */
95#define CIST_TAIL   (1<<5)   /* call was tail called */
96#define CIST_HOOKYIELD   (1<<6)   /* last hook called yielded */
10497
105
10698#define isLua(ci)   ((ci)->callstatus & CIST_LUA)
10799
100/* assume that CIST_OAH has offset 0 and that 'v' is strictly 0/1 */
101#define setoah(st,v)   ((st) = ((st) & ~CIST_OAH) | (v))
102#define getoah(st)   ((st) & CIST_OAH)
108103
104
109105/*
110** `global state', shared by all threads of this state
106** 'global state', shared by all threads of this state
111107*/
112108typedef struct global_State {
113109  lua_Alloc frealloc;  /* function to reallocate memory */
114  void *ud;         /* auxiliary data to `frealloc' */
110  void *ud;         /* auxiliary data to 'frealloc' */
115111  lu_mem totalbytes;  /* number of bytes currently allocated - GCdebt */
116112  l_mem GCdebt;  /* bytes allocated not yet compensated by the collector */
117113  lu_mem GCmemtrav;  /* memory traversed by the GC */
r242885r242886
123119  lu_byte gcstate;  /* state of garbage collector */
124120  lu_byte gckind;  /* kind of GC running */
125121  lu_byte gcrunning;  /* true if GC is running */
126  int sweepstrgc;  /* position of sweep in `strt' */
127122  GCObject *allgc;  /* list of all collectable objects */
123  GCObject **sweepgc;  /* current position of sweep in list */
128124  GCObject *finobj;  /* list of collectable objects with finalizers */
129  GCObject **sweepgc;  /* current position of sweep in list 'allgc' */
130  GCObject **sweepfin;  /* current position of sweep in list 'finobj' */
131125  GCObject *gray;  /* list of gray objects */
132126  GCObject *grayagain;  /* list of objects to be traversed atomically */
133127  GCObject *weak;  /* list of tables with weak values */
134128  GCObject *ephemeron;  /* list of ephemeron tables (weak keys) */
135129  GCObject *allweak;  /* list of all-weak tables */
136130  GCObject *tobefnz;  /* list of userdata to be GC */
137  UpVal uvhead;  /* head of double-linked list of all open upvalues */
131  GCObject *fixedgc;  /* list of objects not to be collected */
132  struct lua_State *twups;  /* list of threads with open upvalues */
138133  Mbuffer buff;  /* temporary buffer for string concatenation */
134  unsigned int gcfinnum;  /* number of finalizers to call in each GC step */
139135  int gcpause;  /* size of pause between successive GCs */
140  int gcmajorinc;  /* pause between major collections (only in gen. mode) */
141  int gcstepmul;  /* GC `granularity' */
136  int gcstepmul;  /* GC 'granularity' */
142137  lua_CFunction panic;  /* to be called in unprotected errors */
143138  struct lua_State *mainthread;
144139  const lua_Number *version;  /* pointer to version number */
r242885r242886
149144
150145
151146/*
152** `per thread' state
147** 'per thread' state
153148*/
154149struct lua_State {
155150  CommonHeader;
r242885r242886
160155  const Instruction *oldpc;  /* last pc traced */
161156  StkId stack_last;  /* last free slot in the stack */
162157  StkId stack;  /* stack base */
158  UpVal *openupval;  /* list of open upvalues in this stack */
159  GCObject *gclist;
160  struct lua_State *twups;  /* list of threads with open upvalues */
161  struct lua_longjmp *errorJmp;  /* current error recover point */
162  CallInfo base_ci;  /* CallInfo for first level (C calling Lua) */
163  lua_Hook hook;
164  ptrdiff_t errfunc;  /* current error handling function (stack index) */
163165  int stacksize;
166  int basehookcount;
167  int hookcount;
164168  unsigned short nny;  /* number of non-yieldable calls in stack */
165169  unsigned short nCcalls;  /* number of nested C calls */
166170  lu_byte hookmask;
167171  lu_byte allowhook;
168  int basehookcount;
169  int hookcount;
170  lua_Hook hook;
171  GCObject *openupval;  /* list of open upvalues in this stack */
172  GCObject *gclist;
173  struct lua_longjmp *errorJmp;  /* current error recover point */
174  ptrdiff_t errfunc;  /* current error handling function (stack index) */
175  CallInfo base_ci;  /* CallInfo for first level (C calling Lua) */
176172};
177173
178174
r242885r242886
180176
181177
182178/*
183** Union of all collectable objects
179** Union of all collectable objects (only for conversions)
184180*/
185union GCObject {
186  GCheader gch;  /* common header */
187  union TString ts;
188  union Udata u;
181union GCUnion {
182  GCObject gc;  /* common header */
183  struct TString ts;
184  struct Udata u;
189185  union Closure cl;
190186  struct Table h;
191187  struct Proto p;
192  struct UpVal uv;
193188  struct lua_State th;  /* thread */
194189};
195190
196191
197#define gch(o)      (&(o)->gch)
192#define cast_u(o)   cast(union GCUnion *, (o))
198193
199194/* macros to convert a GCObject into a specific value */
200#define rawgco2ts(o)  \
201   check_exp(novariant((o)->gch.tt) == LUA_TSTRING, &((o)->ts))
202#define gco2ts(o)   (&rawgco2ts(o)->tsv)
203#define rawgco2u(o)   check_exp((o)->gch.tt == LUA_TUSERDATA, &((o)->u))
204#define gco2u(o)   (&rawgco2u(o)->uv)
205#define gco2lcl(o)   check_exp((o)->gch.tt == LUA_TLCL, &((o)->cl.l))
206#define gco2ccl(o)   check_exp((o)->gch.tt == LUA_TCCL, &((o)->cl.c))
195#define gco2ts(o)  \
196   check_exp(novariant((o)->tt) == LUA_TSTRING, &((cast_u(o))->ts))
197#define gco2u(o)  check_exp((o)->tt == LUA_TUSERDATA, &((cast_u(o))->u))
198#define gco2lcl(o)  check_exp((o)->tt == LUA_TLCL, &((cast_u(o))->cl.l))
199#define gco2ccl(o)  check_exp((o)->tt == LUA_TCCL, &((cast_u(o))->cl.c))
207200#define gco2cl(o)  \
208   check_exp(novariant((o)->gch.tt) == LUA_TFUNCTION, &((o)->cl))
209#define gco2t(o)   check_exp((o)->gch.tt == LUA_TTABLE, &((o)->h))
210#define gco2p(o)   check_exp((o)->gch.tt == LUA_TPROTO, &((o)->p))
211#define gco2uv(o)   check_exp((o)->gch.tt == LUA_TUPVAL, &((o)->uv))
212#define gco2th(o)   check_exp((o)->gch.tt == LUA_TTHREAD, &((o)->th))
201   check_exp(novariant((o)->tt) == LUA_TFUNCTION, &((cast_u(o))->cl))
202#define gco2t(o)  check_exp((o)->tt == LUA_TTABLE, &((cast_u(o))->h))
203#define gco2p(o)  check_exp((o)->tt == LUA_TPROTO, &((cast_u(o))->p))
204#define gco2th(o)  check_exp((o)->tt == LUA_TTHREAD, &((cast_u(o))->th))
213205
214/* macro to convert any Lua object into a GCObject */
215#define obj2gco(v)   (cast(GCObject *, (v)))
216206
207/* macro to convert a Lua object into a GCObject */
208#define obj2gco(v) \
209   check_exp(novariant((v)->tt) < LUA_TDEADKEY, (&(cast_u(v)->gc)))
217210
211
218212/* actual number of total bytes allocated */
219213#define gettotalbytes(g)   ((g)->totalbytes + (g)->GCdebt)
220214
r242885r242886
222216LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
223217LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
224218LUAI_FUNC void luaE_freeCI (lua_State *L);
219LUAI_FUNC void luaE_shrinkCI (lua_State *L);
225220
226221
227222#endif
trunk/3rdparty/lua/src/lstring.c
r242885r242886
11/*
2** $Id: lstring.c,v 2.26.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lstring.c,v 2.45 2014/11/02 19:19:04 roberto Exp $
33** String table (keeps all strings handled by Lua)
44** See Copyright Notice in lua.h
55*/
66
7
8#include <string.h>
9
107#define lstring_c
118#define LUA_CORE
129
10#include "lprefix.h"
11
12
13#include <string.h>
14
1315#include "lua.h"
1416
17#include "ldebug.h"
18#include "ldo.h"
1519#include "lmem.h"
1620#include "lobject.h"
1721#include "lstate.h"
1822#include "lstring.h"
1923
2024
25
2126/*
2227** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to
2328** compute its hash
r242885r242886
3136** equality for long strings
3237*/
3338int luaS_eqlngstr (TString *a, TString *b) {
34  size_t len = a->tsv.len;
35  lua_assert(a->tsv.tt == LUA_TLNGSTR && b->tsv.tt == LUA_TLNGSTR);
39  size_t len = a->len;
40  lua_assert(a->tt == LUA_TLNGSTR && b->tt == LUA_TLNGSTR);
3641  return (a == b) ||  /* same instance or... */
37    ((len == b->tsv.len) &&  /* equal length and ... */
42    ((len == b->len) &&  /* equal length and ... */
3843     (memcmp(getstr(a), getstr(b), len) == 0));  /* equal contents */
3944}
4045
4146
42/*
43** equality for strings
44*/
45int luaS_eqstr (TString *a, TString *b) {
46  return (a->tsv.tt == b->tsv.tt) &&
47         (a->tsv.tt == LUA_TSHRSTR ? eqshrstr(a, b) : luaS_eqlngstr(a, b));
48}
49
50
5147unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {
5248  unsigned int h = seed ^ cast(unsigned int, l);
5349  size_t l1;
r242885r242886
6460void luaS_resize (lua_State *L, int newsize) {
6561  int i;
6662  stringtable *tb = &G(L)->strt;
67  /* cannot resize while GC is traversing strings */
68  luaC_runtilstate(L, ~bitmask(GCSsweepstring));
69  if (newsize > tb->size) {
70    luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);
71    for (i = tb->size; i < newsize; i++) tb->hash[i] = NULL;
63  if (newsize > tb->size) {  /* grow table if needed */
64    luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
65    for (i = tb->size; i < newsize; i++)
66      tb->hash[i] = NULL;
7267  }
73  /* rehash */
74  for (i=0; i<tb->size; i++) {
75    GCObject *p = tb->hash[i];
68  for (i = 0; i < tb->size; i++) {  /* rehash */
69    TString *p = tb->hash[i];
7670    tb->hash[i] = NULL;
7771    while (p) {  /* for each node in the list */
78      GCObject *next = gch(p)->next;  /* save next */
79      unsigned int h = lmod(gco2ts(p)->hash, newsize);  /* new position */
80      gch(p)->next = tb->hash[h];  /* chain it */
72      TString *hnext = p->hnext;  /* save next */
73      unsigned int h = lmod(p->hash, newsize);  /* new position */
74      p->hnext = tb->hash[h];  /* chain it */
8175      tb->hash[h] = p;
82      resetoldbit(p);  /* see MOVE OLD rule */
83      p = next;
76      p = hnext;
8477    }
8578  }
86  if (newsize < tb->size) {
87    /* shrinking slice must be empty */
79  if (newsize < tb->size) {  /* shrink table if needed */
80    /* vanishing slice should be empty */
8881    lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL);
89    luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);
82    luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
9083  }
9184  tb->size = newsize;
9285}
9386
9487
88
9589/*
9690** creates a new string object
9791*/
9892static TString *createstrobj (lua_State *L, const char *str, size_t l,
99                              int tag, unsigned int h, GCObject **list) {
93                              int tag, unsigned int h) {
10094  TString *ts;
95  GCObject *o;
10196  size_t totalsize;  /* total size of TString object */
102  totalsize = sizeof(TString) + ((l + 1) * sizeof(char));
103  ts = &luaC_newobj(L, tag, totalsize, list, 0)->ts;
104  ts->tsv.len = l;
105  ts->tsv.hash = h;
106  ts->tsv.extra = 0;
107  memcpy(ts+1, str, l*sizeof(char));
108  ((char *)(ts+1))[l] = '\0';  /* ending 0 */
97  totalsize = sizelstring(l);
98  o = luaC_newobj(L, tag, totalsize);
99  ts = gco2ts(o);
100  ts->len = l;
101  ts->hash = h;
102  ts->extra = 0;
103  memcpy(getaddrstr(ts), str, l * sizeof(char));
104  getaddrstr(ts)[l] = '\0';  /* ending 0 */
109105  return ts;
110106}
111107
112108
113/*
114** creates a new short string, inserting it into string table
115*/
116static TString *newshrstr (lua_State *L, const char *str, size_t l,
117                                       unsigned int h) {
118  GCObject **list;  /* (pointer to) list where it will be inserted */
109void luaS_remove (lua_State *L, TString *ts) {
119110  stringtable *tb = &G(L)->strt;
120  TString *s;
121  if (tb->nuse >= cast(lu_int32, tb->size) && tb->size <= MAX_INT/2)
122    luaS_resize(L, tb->size*2);  /* too crowded */
123  list = &tb->hash[lmod(h, tb->size)];
124  s = createstrobj(L, str, l, LUA_TSHRSTR, h, list);
125  tb->nuse++;
126  return s;
111  TString **p = &tb->hash[lmod(ts->hash, tb->size)];
112  while (*p != ts)  /* find previous element */
113    p = &(*p)->hnext;
114  *p = (*p)->hnext;  /* remove element from its list */
115  tb->nuse--;
127116}
128117
129118
r242885r242886
131120** checks whether short string exists and reuses it or creates a new one
132121*/
133122static TString *internshrstr (lua_State *L, const char *str, size_t l) {
134  GCObject *o;
123  TString *ts;
135124  global_State *g = G(L);
136125  unsigned int h = luaS_hash(str, l, g->seed);
137  for (o = g->strt.hash[lmod(h, g->strt.size)];
138       o != NULL;
139       o = gch(o)->next) {
140    TString *ts = rawgco2ts(o);
141    if (h == ts->tsv.hash &&
142        l == ts->tsv.len &&
126  TString **list = &g->strt.hash[lmod(h, g->strt.size)];
127  for (ts = *list; ts != NULL; ts = ts->hnext) {
128    if (l == ts->len &&
143129        (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
144      if (isdead(G(L), o))  /* string is dead (but was not collected yet)? */
145        changewhite(o);  /* resurrect it */
130      /* found! */
131      if (isdead(g, ts))  /* dead (but not collected yet)? */
132        changewhite(ts);  /* resurrect it */
146133      return ts;
147134    }
148135  }
149  return newshrstr(L, str, l, h);  /* not found; create a new string */
136  if (g->strt.nuse >= g->strt.size && g->strt.size <= MAX_INT/2) {
137    luaS_resize(L, g->strt.size * 2);
138    list = &g->strt.hash[lmod(h, g->strt.size)];  /* recompute with new size */
139  }
140  ts = createstrobj(L, str, l, LUA_TSHRSTR, h);
141  ts->hnext = *list;
142  *list = ts;
143  g->strt.nuse++;
144  return ts;
150145}
151146
152147
r242885r242886
157152  if (l <= LUAI_MAXSHORTLEN)  /* short string? */
158153    return internshrstr(L, str, l);
159154  else {
160    if (l + 1 > (MAX_SIZET - sizeof(TString))/sizeof(char))
155    if (l + 1 > (MAX_SIZE - sizeof(TString))/sizeof(char))
161156      luaM_toobig(L);
162    return createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed, NULL);
157    return createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed);
163158  }
164159}
165160
r242885r242886
172167}
173168
174169
175Udata *luaS_newudata (lua_State *L, size_t s, Table *e) {
170Udata *luaS_newudata (lua_State *L, size_t s) {
176171  Udata *u;
177  if (s > MAX_SIZET - sizeof(Udata))
172  GCObject *o;
173  if (s > MAX_SIZE - sizeof(Udata))
178174    luaM_toobig(L);
179  u = &luaC_newobj(L, LUA_TUSERDATA, sizeof(Udata) + s, NULL, 0)->u;
180  u->uv.len = s;
181  u->uv.metatable = NULL;
182  u->uv.env = e;
175  o = luaC_newobj(L, LUA_TUSERDATA, sizeludata(s));
176  u = gco2u(o);
177  u->len = s;
178  u->metatable = NULL;
179  setuservalue(L, u, luaO_nilobject);
183180  return u;
184181}
185182
trunk/3rdparty/lua/src/lstring.h
r242885r242886
11/*
2** $Id: lstring.h,v 1.49.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lstring.h,v 1.56 2014/07/18 14:46:47 roberto Exp $
33** String table (keep all strings handled by Lua)
44** See Copyright Notice in lua.h
55*/
r242885r242886
1212#include "lstate.h"
1313
1414
15#define sizestring(s)   (sizeof(union TString)+((s)->len+1)*sizeof(char))
15#define sizelstring(l)  (sizeof(union UTString) + ((l) + 1) * sizeof(char))
16#define sizestring(s)   sizelstring((s)->len)
1617
17#define sizeudata(u)   (sizeof(union Udata)+(u)->len)
18#define sizeludata(l)   (sizeof(union UUdata) + (l))
19#define sizeudata(u)   sizeludata((u)->len)
1820
1921#define luaS_newliteral(L, s)   (luaS_newlstr(L, "" s, \
2022                                 (sizeof(s)/sizeof(char))-1))
2123
22#define luaS_fix(s)   l_setbit((s)->tsv.marked, FIXEDBIT)
2324
24
2525/*
2626** test whether a string is a reserved word
2727*/
28#define isreserved(s)   ((s)->tsv.tt == LUA_TSHRSTR && (s)->tsv.extra > 0)
28#define isreserved(s)   ((s)->tt == LUA_TSHRSTR && (s)->extra > 0)
2929
3030
3131/*
3232** equality for short strings, which are always internalized
3333*/
34#define eqshrstr(a,b)   check_exp((a)->tsv.tt == LUA_TSHRSTR, (a) == (b))
34#define eqshrstr(a,b)   check_exp((a)->tt == LUA_TSHRSTR, (a) == (b))
3535
3636
3737LUAI_FUNC unsigned int luaS_hash (const char *str, size_t l, unsigned int seed);
3838LUAI_FUNC int luaS_eqlngstr (TString *a, TString *b);
39LUAI_FUNC int luaS_eqstr (TString *a, TString *b);
4039LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
41LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);
40LUAI_FUNC void luaS_remove (lua_State *L, TString *ts);
41LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s);
4242LUAI_FUNC TString *luaS_newlstr (lua_State *L, const char *str, size_t l);
4343LUAI_FUNC TString *luaS_new (lua_State *L, const char *str);
4444
trunk/3rdparty/lua/src/lstrlib.c
r242885r242886
11/*
2** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lstrlib.c,v 1.221 2014/12/11 14:03:07 roberto Exp $
33** Standard library for string operations and pattern-matching
44** See Copyright Notice in lua.h
55*/
66
7#define lstrlib_c
8#define LUA_LIB
79
10#include "lprefix.h"
11
12
813#include <ctype.h>
14#include <limits.h>
915#include <stddef.h>
1016#include <stdio.h>
1117#include <stdlib.h>
1218#include <string.h>
1319
14#define lstrlib_c
15#define LUA_LIB
16
1720#include "lua.h"
1821
1922#include "lauxlib.h"
r242885r242886
2932#endif
3033
3134
32/* macro to `unsign' a character */
35/* macro to 'unsign' a character */
3336#define uchar(c)   ((unsigned char)(c))
3437
3538
39/*
40** Some sizes are better limited to fit in 'int', but must also fit in
41** 'size_t'. (We assume that 'lua_Integer' cannot be smaller than 'int'.)
42*/
43#define MAXSIZE  \
44   (sizeof(size_t) < sizeof(int) ? (~(size_t)0) : (size_t)(INT_MAX))
3645
46
47
48
3749static int str_len (lua_State *L) {
3850  size_t l;
3951  luaL_checklstring(L, 1, &l);
r242885r242886
4355
4456
4557/* translate a relative string position: negative means back from end */
46static size_t posrelat (ptrdiff_t pos, size_t len) {
47  if (pos >= 0) return (size_t)pos;
58static lua_Integer posrelat (lua_Integer pos, size_t len) {
59  if (pos >= 0) return pos;
4860  else if (0u - (size_t)pos > len) return 0;
49  else return len - ((size_t)-pos) + 1;
61  else return (lua_Integer)len + pos + 1;
5062}
5163
5264
5365static int str_sub (lua_State *L) {
5466  size_t l;
5567  const char *s = luaL_checklstring(L, 1, &l);
56  size_t start = posrelat(luaL_checkinteger(L, 2), l);
57  size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
68  lua_Integer start = posrelat(luaL_checkinteger(L, 2), l);
69  lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l);
5870  if (start < 1) start = 1;
59  if (end > l) end = l;
71  if (end > (lua_Integer)l) end = l;
6072  if (start <= end)
61    lua_pushlstring(L, s + start - 1, end - start + 1);
73    lua_pushlstring(L, s + start - 1, (size_t)(end - start + 1));
6274  else lua_pushliteral(L, "");
6375  return 1;
6476}
r242885r242886
102114}
103115
104116
105/* reasonable limit to avoid arithmetic overflow */
106#define MAXSIZE      ((~(size_t)0) >> 1)
107
108117static int str_rep (lua_State *L) {
109118  size_t l, lsep;
110119  const char *s = luaL_checklstring(L, 1, &l);
111  int n = luaL_checkint(L, 2);
120  lua_Integer n = luaL_checkinteger(L, 2);
112121  const char *sep = luaL_optlstring(L, 3, "", &lsep);
113122  if (n <= 0) lua_pushliteral(L, "");
114  else if (l + lsep < l || l + lsep >= MAXSIZE / n)  /* may overflow? */
123  else if (l + lsep < l || l + lsep > MAXSIZE / n)  /* may overflow? */
115124    return luaL_error(L, "resulting string too large");
116125  else {
117    size_t totallen = n * l + (n - 1) * lsep;
126    size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
118127    luaL_Buffer b;
119128    char *p = luaL_buffinitsize(L, &b, totallen);
120129    while (n-- > 1) {  /* first n-1 copies (followed by separator) */
121130      memcpy(p, s, l * sizeof(char)); p += l;
122      if (lsep > 0) {  /* avoid empty 'memcpy' (may be expensive) */
123        memcpy(p, sep, lsep * sizeof(char)); p += lsep;
131      if (lsep > 0) {  /* empty 'memcpy' is not that cheap */
132        memcpy(p, sep, lsep * sizeof(char));
133        p += lsep;
124134      }
125135    }
126136    memcpy(p, s, l * sizeof(char));  /* last copy (not followed by separator) */
r242885r242886
133143static int str_byte (lua_State *L) {
134144  size_t l;
135145  const char *s = luaL_checklstring(L, 1, &l);
136  size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
137  size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
146  lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l);
147  lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l);
138148  int n, i;
139149  if (posi < 1) posi = 1;
140  if (pose > l) pose = l;
150  if (pose > (lua_Integer)l) pose = l;
141151  if (posi > pose) return 0;  /* empty interval; return no values */
142152  n = (int)(pose -  posi + 1);
143  if (posi + n <= pose)  /* (size_t -> int) overflow? */
153  if (posi + n <= pose)  /* arithmetic overflow? */
144154    return luaL_error(L, "string slice too long");
145155  luaL_checkstack(L, n, "string slice too long");
146156  for (i=0; i<n; i++)
r242885r242886
155165  luaL_Buffer b;
156166  char *p = luaL_buffinitsize(L, &b, n);
157167  for (i=1; i<=n; i++) {
158    int c = luaL_checkint(L, i);
168    lua_Integer c = luaL_checkinteger(L, i);
159169    luaL_argcheck(L, uchar(c) == c, i, "value out of range");
160170    p[i - 1] = uchar(c);
161171  }
r242885r242886
164174}
165175
166176
167static int writer (lua_State *L, const void* b, size_t size, void* B) {
177static int writer (lua_State *L, const void *b, size_t size, void *B) {
168178  (void)L;
169  luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
179  luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);
170180  return 0;
171181}
172182
173183
174184static int str_dump (lua_State *L) {
175185  luaL_Buffer b;
186  int strip = lua_toboolean(L, 2);
176187  luaL_checktype(L, 1, LUA_TFUNCTION);
177188  lua_settop(L, 1);
178189  luaL_buffinit(L,&b);
179  if (lua_dump(L, writer, &b) != 0)
190  if (lua_dump(L, writer, &b, strip) != 0)
180191    return luaL_error(L, "unable to dump given function");
181192  luaL_pushresult(&b);
182193  return 1;
r242885r242886
243254  switch (*p++) {
244255    case L_ESC: {
245256      if (p == ms->p_end)
246        luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
257        luaL_error(ms->L, "malformed pattern (ends with '%%')");
247258      return p+1;
248259    }
249260    case '[': {
250261      if (*p == '^') p++;
251      do {  /* look for a `]' */
262      do {  /* look for a ']' */
252263        if (p == ms->p_end)
253          luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
264          luaL_error(ms->L, "malformed pattern (missing ']')");
254265        if (*(p++) == L_ESC && p < ms->p_end)
255          p++;  /* skip escapes (e.g. `%]') */
266          p++;  /* skip escapes (e.g. '%]') */
256267      } while (*p != ']');
257268      return p+1;
258269    }
r242885r242886
287298  int sig = 1;
288299  if (*(p+1) == '^') {
289300    sig = 0;
290    p++;  /* skip the `^' */
301    p++;  /* skip the '^' */
291302  }
292303  while (++p < ec) {
293304    if (*p == L_ESC) {
r242885r242886
325336static const char *matchbalance (MatchState *ms, const char *s,
326337                                   const char *p) {
327338  if (p >= ms->p_end - 1)
328    luaL_error(ms->L, "malformed pattern "
329                      "(missing arguments to " LUA_QL("%%b") ")");
339    luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
330340  if (*s != *p) return NULL;
331341  else {
332342    int b = *p;
r242885r242886
425435        break;
426436      }
427437      case '$': {
428        if ((p + 1) != ms->p_end)  /* is the `$' the last char in pattern? */
438        if ((p + 1) != ms->p_end)  /* is the '$' the last char in pattern? */
429439          goto dflt;  /* no; go to default */
430440        s = (s == ms->src_end) ? s : NULL;  /* check end of string */
431441        break;
r242885r242886
443453            const char *ep; char previous;
444454            p += 2;
445455            if (*p != '[')
446              luaL_error(ms->L, "missing " LUA_QL("[") " after "
447                                 LUA_QL("%%f") " in pattern");
456              luaL_error(ms->L, "missing '[' after '%%f' in pattern");
448457            ep = classend(ms, p);  /* points to what is next */
449458            previous = (s == ms->src_init) ? '\0' : *(s - 1);
450459            if (!matchbracketclass(uchar(previous), p, ep - 1) &&
r242885r242886
514523static const char *lmemfind (const char *s1, size_t l1,
515524                               const char *s2, size_t l2) {
516525  if (l2 == 0) return s1;  /* empty strings are everywhere */
517  else if (l2 > l1) return NULL;  /* avoids a negative `l1' */
526  else if (l2 > l1) return NULL;  /* avoids a negative 'l1' */
518527  else {
519    const char *init;  /* to search for a `*s2' inside `s1' */
520    l2--;  /* 1st char will be checked by `memchr' */
521    l1 = l1-l2;  /* `s2' cannot be found after that */
528    const char *init;  /* to search for a '*s2' inside 's1' */
529    l2--;  /* 1st char will be checked by 'memchr' */
530    l1 = l1-l2;  /* 's2' cannot be found after that */
522531    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
523532      init++;   /* 1st char is already checked */
524533      if (memcmp(init, s2+1, l2) == 0)
525534        return init-1;
526      else {  /* correct `l1' and `s1' to try again */
535      else {  /* correct 'l1' and 's1' to try again */
527536        l1 -= init-s1;
528537        s1 = init;
529538      }
r242885r242886
539548    if (i == 0)  /* ms->level == 0, too */
540549      lua_pushlstring(ms->L, s, e - s);  /* add whole match */
541550    else
542      luaL_error(ms->L, "invalid capture index");
551      luaL_error(ms->L, "invalid capture index %%%d", i + 1);
543552  }
544553  else {
545554    ptrdiff_t l = ms->capture[i].len;
r242885r242886
578587  size_t ls, lp;
579588  const char *s = luaL_checklstring(L, 1, &ls);
580589  const char *p = luaL_checklstring(L, 2, &lp);
581  size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
590  lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls);
582591  if (init < 1) init = 1;
583  else if (init > ls + 1) {  /* start after string's end? */
592  else if (init > (lua_Integer)ls + 1) {  /* start after string's end? */
584593    lua_pushnil(L);  /* cannot find anything */
585594    return 1;
586595  }
587596  /* explicit request or no special characters? */
588597  if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
589598    /* do a plain search */
590    const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
599    const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp);
591600    if (s2) {
592601      lua_pushinteger(L, s2 - s + 1);
593602      lua_pushinteger(L, s2 - s + lp);
r242885r242886
678687static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
679688                                                   const char *e) {
680689  size_t l, i;
681  const char *news = lua_tolstring(ms->L, 3, &l);
690  lua_State *L = ms->L;
691  const char *news = lua_tolstring(L, 3, &l);
682692  for (i = 0; i < l; i++) {
683693    if (news[i] != L_ESC)
684694      luaL_addchar(b, news[i]);
r242885r242886
686696      i++;  /* skip ESC */
687697      if (!isdigit(uchar(news[i]))) {
688698        if (news[i] != L_ESC)
689          luaL_error(ms->L, "invalid use of " LUA_QL("%c")
690                           " in replacement string", L_ESC);
699          luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
691700        luaL_addchar(b, news[i]);
692701      }
693702      else if (news[i] == '0')
694703          luaL_addlstring(b, s, e - s);
695704      else {
696705        push_onecapture(ms, news[i] - '1', s, e);
706        luaL_tolstring(L, -1, NULL);  /* if number, convert it to string */
707        lua_remove(L, -2);  /* remove original value */
697708        luaL_addvalue(b);  /* add capture to accumulated result */
698709      }
699710    }
r242885r242886
737748  const char *src = luaL_checklstring(L, 1, &srcl);
738749  const char *p = luaL_checklstring(L, 2, &lp);
739750  int tr = lua_type(L, 3);
740  size_t max_s = luaL_optinteger(L, 4, srcl+1);
751  lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1);
741752  int anchor = (*p == '^');
742  size_t n = 0;
753  lua_Integer n = 0;
743754  MatchState ms;
744755  luaL_Buffer b;
745756  luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
r242885r242886
786797** =======================================================
787798*/
788799
789/*
790** LUA_INTFRMLEN is the length modifier for integer conversions in
791** 'string.format'; LUA_INTFRM_T is the integer type corresponding to
792** the previous length
793*/
794#if !defined(LUA_INTFRMLEN)   /* { */
795#if defined(LUA_USE_LONGLONG)
796
797#define LUA_INTFRMLEN      "ll"
798#define LUA_INTFRM_T      long long
799
800#else
801
802#define LUA_INTFRMLEN      "l"
803#define LUA_INTFRM_T      long
804
805#endif
806#endif            /* } */
807
808
809/*
810** LUA_FLTFRMLEN is the length modifier for float conversions in
811** 'string.format'; LUA_FLTFRM_T is the float type corresponding to
812** the previous length
813*/
814#if !defined(LUA_FLTFRMLEN)
815
816#define LUA_FLTFRMLEN      ""
817#define LUA_FLTFRM_T      double
818
819#endif
820
821
822800/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
823801#define MAX_ITEM   512
802
824803/* valid flags in a format specification */
825804#define FLAGS   "-+ #0"
805
826806/*
827** maximum size of each format specification (such as '%-099.99d')
828** (+10 accounts for %99.99x plus margin of error)
807** maximum size of each format specification (such as "%-099.99d")
808** (+2 for length modifiers; +10 accounts for %99.99x plus margin of error)
829809*/
830#define MAX_FORMAT   (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
810#define MAX_FORMAT   (sizeof(FLAGS) + 2 + 10)
831811
832812
833813static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
r242885r242886
903883    else if (*++strfrmt == L_ESC)
904884      luaL_addchar(&b, *strfrmt++);  /* %% */
905885    else { /* format item */
906      char form[MAX_FORMAT];  /* to store the format (`%...') */
886      char form[MAX_FORMAT];  /* to store the format ('%...') */
907887      char *buff = luaL_prepbuffsize(&b, MAX_ITEM);  /* to put formatted item */
908888      int nb = 0;  /* number of bytes in added item */
909889      if (++arg > top)
r242885r242886
911891      strfrmt = scanformat(L, strfrmt, form);
912892      switch (*strfrmt++) {
913893        case 'c': {
914          nb = sprintf(buff, form, luaL_checkint(L, arg));
894          nb = sprintf(buff, form, (int)luaL_checkinteger(L, arg));
915895          break;
916896        }
917        case 'd': case 'i': {
918          lua_Number n = luaL_checknumber(L, arg);
919          LUA_INTFRM_T ni = (LUA_INTFRM_T)n;
920          lua_Number diff = n - (lua_Number)ni;
921          luaL_argcheck(L, -1 < diff && diff < 1, arg,
922                        "not a number in proper range");
923          addlenmod(form, LUA_INTFRMLEN);
924          nb = sprintf(buff, form, ni);
925          break;
926        }
897        case 'd': case 'i':
927898        case 'o': case 'u': case 'x': case 'X': {
928          lua_Number n = luaL_checknumber(L, arg);
929          unsigned LUA_INTFRM_T ni = (unsigned LUA_INTFRM_T)n;
930          lua_Number diff = n - (lua_Number)ni;
931          luaL_argcheck(L, -1 < diff && diff < 1, arg,
932                        "not a non-negative number in proper range");
933          addlenmod(form, LUA_INTFRMLEN);
934          nb = sprintf(buff, form, ni);
899          lua_Integer n = luaL_checkinteger(L, arg);
900          addlenmod(form, LUA_INTEGER_FRMLEN);
901          nb = sprintf(buff, form, n);
935902          break;
936903        }
937        case 'e': case 'E': case 'f':
938904#if defined(LUA_USE_AFORMAT)
939905        case 'a': case 'A':
940906#endif
907        case 'e': case 'E': case 'f':
941908        case 'g': case 'G': {
942          addlenmod(form, LUA_FLTFRMLEN);
943          nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
909          addlenmod(form, LUA_NUMBER_FRMLEN);
910          nb = sprintf(buff, form, luaL_checknumber(L, arg));
944911          break;
945912        }
946913        case 'q': {
r242885r242886
962929            break;
963930          }
964931        }
965        default: {  /* also treat cases `pnLlh' */
966          return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
967                               LUA_QL("format"), *(strfrmt - 1));
932        default: {  /* also treat cases 'pnLlh' */
933          return luaL_error(L, "invalid option '%%%c' to 'format'",
934                               *(strfrmt - 1));
968935        }
969936      }
970937      luaL_addsize(&b, nb);
r242885r242886
977944/* }====================================================== */
978945
979946
947/*
948** {======================================================
949** PACK/UNPACK
950** =======================================================
951*/
952
953
954/* value used for padding */
955#if !defined(LUA_PACKPADBYTE)
956#define LUA_PACKPADBYTE      0x00
957#endif
958
959/* maximum size for the binary representation of an integer */
960#define MAXINTSIZE   16
961
962/* number of bits in a character */
963#define NB   CHAR_BIT
964
965/* mask for one character (NB 1's) */
966#define MC   ((1 << NB) - 1)
967
968/* size of a lua_Integer */
969#define SZINT   ((int)sizeof(lua_Integer))
970
971
972/* dummy union to get native endianness */
973static const union {
974  int dummy;
975  char little;  /* true iff machine is little endian */
976} nativeendian = {1};
977
978
979/* dummy structure to get native alignment requirements */
980struct cD {
981  char c;
982  union { double d; void *p; lua_Integer i; lua_Number n; } u;
983};
984
985#define MAXALIGN   (offsetof(struct cD, u))
986
987
988/*
989** Union for serializing floats
990*/
991typedef union Ftypes {
992  float f;
993  double d;
994  lua_Number n;
995  char buff[5 * sizeof(lua_Number)];  /* enough for any float type */
996} Ftypes;
997
998
999/*
1000** information to pack/unpack stuff
1001*/
1002typedef struct Header {
1003  lua_State *L;
1004  int islittle;
1005  int maxalign;
1006} Header;
1007
1008
1009/*
1010** options for pack/unpack
1011*/
1012typedef enum KOption {
1013  Kint,      /* signed integers */
1014  Kuint,   /* unsigned integers */
1015  Kfloat,   /* floating-point numbers */
1016  Kchar,   /* fixed-length strings */
1017  Kstring,   /* strings with prefixed length */
1018  Kzstr,   /* zero-terminated strings */
1019  Kpadding,   /* padding */
1020  Kpaddalign,   /* padding for alignment */
1021  Knop      /* no-op (configuration or spaces) */
1022} KOption;
1023
1024
1025/*
1026** Read an integer numeral from string 'fmt' or return 'df' if
1027** there is no numeral
1028*/
1029static int digit (int c) { return '0' <= c && c <= '9'; }
1030
1031static int getnum (const char **fmt, int df) {
1032  if (!digit(**fmt))  /* no number? */
1033    return df;  /* return default value */
1034  else {
1035    int a = 0;
1036    do {
1037      a = a*10 + (*((*fmt)++) - '0');
1038    } while (digit(**fmt) && a <= ((int)MAXSIZE - 9)/10);
1039    return a;
1040  }
1041}
1042
1043
1044/*
1045** Read an integer numeral and raises an error if it is larger
1046** than the maximum size for integers.
1047*/
1048static int getnumlimit (Header *h, const char **fmt, int df) {
1049  int sz = getnum(fmt, df);
1050  if (sz > MAXINTSIZE || sz <= 0)
1051    luaL_error(h->L, "integral size (%d) out of limits [1,%d]",
1052                     sz, MAXINTSIZE);
1053  return sz;
1054}
1055
1056
1057/*
1058** Initialize Header
1059*/
1060static void initheader (lua_State *L, Header *h) {
1061  h->L = L;
1062  h->islittle = nativeendian.little;
1063  h->maxalign = 1;
1064}
1065
1066
1067/*
1068** Read and classify next option. 'size' is filled with option's size.
1069*/
1070static KOption getoption (Header *h, const char **fmt, int *size) {
1071  int opt = *((*fmt)++);
1072  *size = 0;  /* default */
1073  switch (opt) {
1074    case 'b': *size = sizeof(char); return Kint;
1075    case 'B': *size = sizeof(char); return Kuint;
1076    case 'h': *size = sizeof(short); return Kint;
1077    case 'H': *size = sizeof(short); return Kuint;
1078    case 'l': *size = sizeof(long); return Kint;
1079    case 'L': *size = sizeof(long); return Kuint;
1080    case 'j': *size = sizeof(lua_Integer); return Kint;
1081    case 'J': *size = sizeof(lua_Integer); return Kuint;
1082    case 'T': *size = sizeof(size_t); return Kuint;
1083    case 'f': *size = sizeof(float); return Kfloat;
1084    case 'd': *size = sizeof(double); return Kfloat;
1085    case 'n': *size = sizeof(lua_Number); return Kfloat;
1086    case 'i': *size = getnumlimit(h, fmt, sizeof(int)); return Kint;
1087    case 'I': *size = getnumlimit(h, fmt, sizeof(int)); return Kuint;
1088    case 's': *size = getnumlimit(h, fmt, sizeof(size_t)); return Kstring;
1089    case 'c':
1090      *size = getnum(fmt, -1);
1091      if (*size == -1)
1092        luaL_error(h->L, "missing size for format option 'c'");
1093      return Kchar;
1094    case 'z': return Kzstr;
1095    case 'x': *size = 1; return Kpadding;
1096    case 'X': return Kpaddalign;
1097    case ' ': break;
1098    case '<': h->islittle = 1; break;
1099    case '>': h->islittle = 0; break;
1100    case '=': h->islittle = nativeendian.little; break;
1101    case '!': h->maxalign = getnumlimit(h, fmt, MAXALIGN); break;
1102    default: luaL_error(h->L, "invalid format option '%c'", opt);
1103  }
1104  return Knop;
1105}
1106
1107
1108/*
1109** Read, classify, and fill other details about the next option.
1110** 'psize' is filled with option's size, 'notoalign' with its
1111** alignment requirements.
1112** Local variable 'size' gets the size to be aligned. (Kpadal option
1113** always gets its full alignment, other options are limited by
1114** the maximum alignment ('maxalign'). Kchar option needs no alignment
1115** despite its size.
1116*/
1117static KOption getdetails (Header *h, size_t totalsize,
1118                           const char **fmt, int *psize, int *ntoalign) {
1119  KOption opt = getoption(h, fmt, psize);
1120  int align = *psize;  /* usually, alignment follows size */
1121  if (opt == Kpaddalign) {  /* 'X' gets alignment from following option */
1122    if (**fmt == '\0' || getoption(h, fmt, &align) == Kchar || align == 0)
1123      luaL_argerror(h->L, 1, "invalid next option for option 'X'");
1124  }
1125  if (align <= 1 || opt == Kchar)  /* need no alignment? */
1126    *ntoalign = 0;
1127  else {
1128    if (align > h->maxalign)  /* enforce maximum alignment */
1129      align = h->maxalign;
1130    if ((align & (align - 1)) != 0)  /* is 'align' not a power of 2? */
1131      luaL_argerror(h->L, 1, "format asks for alignment not power of 2");
1132    *ntoalign = (align - (int)(totalsize & (align - 1))) & (align - 1);
1133  }
1134  return opt;
1135}
1136
1137
1138/*
1139** Pack integer 'n' with 'size' bytes and 'islittle' endianness.
1140** The final 'if' handles the case when 'size' is larger than
1141** the size of a Lua integer, correcting the extra sign-extension
1142** bytes if necessary (by default they would be zeros).
1143*/
1144static void packint (luaL_Buffer *b, lua_Unsigned n,
1145                     int islittle, int size, int neg) {
1146  char *buff = luaL_prepbuffsize(b, size);
1147  int i;
1148  buff[islittle ? 0 : size - 1] = (char)(n & MC);  /* first byte */
1149  for (i = 1; i < size; i++) {
1150    n >>= NB;
1151    buff[islittle ? i : size - 1 - i] = (char)(n & MC);
1152  }
1153  if (neg && size > SZINT) {  /* negative number need sign extension? */
1154    for (i = SZINT; i < size; i++)  /* correct extra bytes */
1155      buff[islittle ? i : size - 1 - i] = (char)MC;
1156  }
1157  luaL_addsize(b, size);  /* add result to buffer */
1158}
1159
1160
1161/*
1162** Copy 'size' bytes from 'src' to 'dest', correcting endianness if
1163** given 'islittle' is different from native endianness.
1164*/
1165static void copywithendian (volatile char *dest, volatile const char *src,
1166                            int size, int islittle) {
1167  if (islittle == nativeendian.little) {
1168    while (size-- != 0)
1169      *(dest++) = *(src++);
1170  }
1171  else {
1172    dest += size - 1;
1173    while (size-- != 0)
1174      *(dest--) = *(src++);
1175  }
1176}
1177
1178
1179static int str_pack (lua_State *L) {
1180  luaL_Buffer b;
1181  Header h;
1182  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1183  int arg = 1;  /* current argument to pack */
1184  size_t totalsize = 0;  /* accumulate total size of result */
1185  initheader(L, &h);
1186  lua_pushnil(L);  /* mark to separate arguments from string buffer */
1187  luaL_buffinit(L, &b);
1188  while (*fmt != '\0') {
1189    int size, ntoalign;
1190    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1191    totalsize += ntoalign + size;
1192    while (ntoalign-- > 0)
1193     luaL_addchar(&b, LUA_PACKPADBYTE);  /* fill alignment */
1194    arg++;
1195    switch (opt) {
1196      case Kint: {  /* signed integers */
1197        lua_Integer n = luaL_checkinteger(L, arg);
1198        if (size < SZINT) {  /* need overflow check? */
1199          lua_Integer lim = (lua_Integer)1 << ((size * NB) - 1);
1200          luaL_argcheck(L, -lim <= n && n < lim, arg, "integer overflow");
1201        }
1202        packint(&b, (lua_Unsigned)n, h.islittle, size, (n < 0));
1203        break;
1204      }
1205      case Kuint: {  /* unsigned integers */
1206        lua_Integer n = luaL_checkinteger(L, arg);
1207        if (size < SZINT)  /* need overflow check? */
1208          luaL_argcheck(L, (lua_Unsigned)n < ((lua_Unsigned)1 << (size * NB)),
1209                           arg, "unsigned overflow");
1210        packint(&b, (lua_Unsigned)n, h.islittle, size, 0);
1211        break;
1212      }
1213      case Kfloat: {  /* floating-point options */
1214        volatile Ftypes u;
1215        char *buff = luaL_prepbuffsize(&b, size);
1216        lua_Number n = luaL_checknumber(L, arg);  /* get argument */
1217        if (size == sizeof(u.f)) u.f = (float)n;  /* copy it into 'u' */
1218        else if (size == sizeof(u.d)) u.d = (double)n;
1219        else u.n = n;
1220        /* move 'u' to final result, correcting endianness if needed */
1221        copywithendian(buff, u.buff, size, h.islittle);
1222        luaL_addsize(&b, size);
1223        break;
1224      }
1225      case Kchar: {  /* fixed-size string */
1226        size_t len;
1227        const char *s = luaL_checklstring(L, arg, &len);
1228        luaL_argcheck(L, len == (size_t)size, arg, "wrong length");
1229        luaL_addlstring(&b, s, size);
1230        break;
1231      }
1232      case Kstring: {  /* strings with length count */
1233        size_t len;
1234        const char *s = luaL_checklstring(L, arg, &len);
1235        luaL_argcheck(L, size >= (int)sizeof(size_t) ||
1236                         len < ((size_t)1 << (size * NB)),
1237                         arg, "string length does not fit in given size");
1238        packint(&b, (lua_Unsigned)len, h.islittle, size, 0);  /* pack length */
1239        luaL_addlstring(&b, s, len);
1240        totalsize += len;
1241        break;
1242      }
1243      case Kzstr: {  /* zero-terminated string */
1244        size_t len;
1245        const char *s = luaL_checklstring(L, arg, &len);
1246        luaL_argcheck(L, strlen(s) == len, arg, "string contains zeros");
1247        luaL_addlstring(&b, s, len);
1248        luaL_addchar(&b, '\0');  /* add zero at the end */
1249        totalsize += len + 1;
1250        break;
1251      }
1252      case Kpadding: luaL_addchar(&b, LUA_PACKPADBYTE);  /* go through */
1253      case Kpaddalign: case Knop:
1254        arg--;  /* undo increment */
1255        break;
1256    }
1257  }
1258  luaL_pushresult(&b);
1259  return 1;
1260}
1261
1262
1263static int str_packsize (lua_State *L) {
1264  Header h;
1265  const char *fmt = luaL_checkstring(L, 1);  /* format string */
1266  size_t totalsize = 0;  /* accumulate total size of result */
1267  initheader(L, &h);
1268  while (*fmt != '\0') {
1269    int size, ntoalign;
1270    KOption opt = getdetails(&h, totalsize, &fmt, &size, &ntoalign);
1271    size += ntoalign;  /* total space used by option */
1272    luaL_argcheck(L, totalsize <= MAXSIZE - size, 1,
1273                     "format result too large");
1274    totalsize += size;
1275    switch (opt) {
1276      case Kstring:  /* strings with length count */
1277      case Kzstr:    /* zero-terminated string */
1278        luaL_argerror(L, 1, "variable-length format");
1279        break;
1280      default:  break;
1281    }
1282  }
1283  lua_pushinteger(L, (lua_Integer)totalsize);
1284  return 1;
1285}
1286
1287
1288/*
1289** Unpack an integer with 'size' bytes and 'islittle' endianness.
1290** If size is smaller than the size of a Lua integer and integer
1291** is signed, must do sign extension (propagating the sign to the
1292** higher bits); if size is larger than the size of a Lua integer,
1293** it must check the unread bytes to see whether they do not cause an
1294** overflow.
1295*/
1296static lua_Integer unpackint (lua_State *L, const char *str,
1297                              int islittle, int size, int issigned) {
1298  lua_Unsigned res = 0;
1299  int i;
1300  int limit = (size  <= SZINT) ? size : SZINT;
1301  for (i = limit - 1; i >= 0; i--) {
1302    res <<= NB;
1303    res |= (lua_Unsigned)(unsigned char)str[islittle ? i : size - 1 - i];
1304  }
1305  if (size < SZINT) {  /* real size smaller than lua_Integer? */
1306    if (issigned) {  /* needs sign extension? */
1307      lua_Unsigned mask = (lua_Unsigned)1 << (size*NB - 1);
1308      res = ((res ^ mask) - mask);  /* do sign extension */
1309    }
1310  }
1311  else if (size > SZINT) {  /* must check unread bytes */
1312    int mask = (!issigned || (lua_Integer)res >= 0) ? 0 : MC;
1313    for (i = limit; i < size; i++) {
1314      if ((unsigned char)str[islittle ? i : size - 1 - i] != mask)
1315        luaL_error(L, "%d-byte integer does not fit into Lua Integer", size);
1316    }
1317  }
1318  return (lua_Integer)res;
1319}
1320
1321
1322static int str_unpack (lua_State *L) {
1323  Header h;
1324  const char *fmt = luaL_checkstring(L, 1);
1325  size_t ld;
1326  const char *data = luaL_checklstring(L, 2, &ld);
1327  size_t pos = (size_t)posrelat(luaL_optinteger(L, 3, 1), ld) - 1;
1328  int n = 0;  /* number of results */
1329  luaL_argcheck(L, pos <= ld, 3, "initial position out of string");
1330  initheader(L, &h);
1331  while (*fmt != '\0') {
1332    int size, ntoalign;
1333    KOption opt = getdetails(&h, pos, &fmt, &size, &ntoalign);
1334    if ((size_t)ntoalign + size > ~pos || pos + ntoalign + size > ld)
1335      luaL_argerror(L, 2, "data string too short");
1336    pos += ntoalign;  /* skip alignment */
1337    /* stack space for item + next position */
1338    luaL_checkstack(L, 2, "too many results");
1339    n++;
1340    switch (opt) {
1341      case Kint:
1342      case Kuint: {
1343        lua_Integer res = unpackint(L, data + pos, h.islittle, size,
1344                                       (opt == Kint));
1345        lua_pushinteger(L, res);
1346        break;
1347      }
1348      case Kfloat: {
1349        volatile Ftypes u;
1350        lua_Number num;
1351        copywithendian(u.buff, data + pos, size, h.islittle);
1352        if (size == sizeof(u.f)) num = (lua_Number)u.f;
1353        else if (size == sizeof(u.d)) num = (lua_Number)u.d;
1354        else num = u.n;
1355        lua_pushnumber(L, num);
1356        break;
1357      }
1358      case Kchar: {
1359        lua_pushlstring(L, data + pos, size);
1360        break;
1361      }
1362      case Kstring: {
1363        size_t len = (size_t)unpackint(L, data + pos, h.islittle, size, 0);
1364        luaL_argcheck(L, pos + len + size <= ld, 2, "data string too short");
1365        lua_pushlstring(L, data + pos + size, len);
1366        pos += len;  /* skip string */
1367        break;
1368      }
1369      case Kzstr: {
1370        size_t len = (int)strlen(data + pos);
1371        lua_pushlstring(L, data + pos, len);
1372        pos += len + 1;  /* skip string plus final '\0' */
1373        break;
1374      }
1375      case Kpaddalign: case Kpadding: case Knop:
1376        n--;  /* undo increment */
1377        break;
1378    }
1379    pos += size;
1380  }
1381  lua_pushinteger(L, pos + 1);  /* next position */
1382  return n + 1;
1383}
1384
1385/* }====================================================== */
1386
1387
9801388static const luaL_Reg strlib[] = {
9811389  {"byte", str_byte},
9821390  {"char", str_char},
r242885r242886
9921400  {"reverse", str_reverse},
9931401  {"sub", str_sub},
9941402  {"upper", str_upper},
1403  {"pack", str_pack},
1404  {"packsize", str_packsize},
1405  {"unpack", str_unpack},
9951406  {NULL, NULL}
9961407};
9971408
trunk/3rdparty/lua/src/ltable.c
r242885r242886
11/*
2** $Id: ltable.c,v 2.72.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: ltable.c,v 2.100 2015/01/05 13:52:37 roberto Exp $
33** Lua tables (hash)
44** See Copyright Notice in lua.h
55*/
66
7#define ltable_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813/*
914** Implementation of tables (aka arrays, objects, or hash tables).
1015** Tables keep its elements in two parts: an array part and a hash part.
1116** Non-negative integer keys are all candidates to be kept in the array
12** part. The actual size of the array is the largest `n' such that at
17** part. The actual size of the array is the largest 'n' such that at
1318** least half the slots between 0 and n are in use.
1419** Hash uses a mix of chained scatter table with Brent's variation.
1520** A main invariant of these tables is that, if an element is not
16** in its main position (i.e. the `original' position that its hash gives
21** in its main position (i.e. the 'original' position that its hash gives
1722** to it), then the colliding element is in its own main position.
1823** Hence even when the load factor reaches 100%, performance remains good.
1924*/
2025
26#include <float.h>
27#include <math.h>
2128#include <string.h>
29#include <limits.h>
2230
23#define ltable_c
24#define LUA_CORE
25
2631#include "lua.h"
2732
2833#include "ldebug.h"
r242885r242886
3742
3843
3944/*
40** max size of array part is 2^MAXBITS
45** Maximum size of array part (MAXASIZE) is 2^MAXABITS. MAXABITS is
46** the largest integer such that MAXASIZE fits in an unsigned int.
4147*/
42#if LUAI_BITSINT >= 32
43#define MAXBITS      30
44#else
45#define MAXBITS      (LUAI_BITSINT-2)
46#endif
48#define MAXABITS   cast_int(sizeof(int) * CHAR_BIT - 1)
49#define MAXASIZE   (1u << MAXABITS)
4750
48#define MAXASIZE   (1 << MAXBITS)
51/*
52** Maximum size of hash part is 2^MAXHBITS. MAXHBITS is the largest
53** integer such that 2^MAXHBITS fits in a signed int. (Note that the
54** maximum number of elements in a table, 2^MAXABITS + 2^MAXHBITS, still
55** fits comfortably in an unsigned int.)
56*/
57#define MAXHBITS   (MAXABITS - 1)
4958
5059
5160#define hashpow2(t,n)      (gnode(t, lmod((n), sizenode(t))))
5261
53#define hashstr(t,str)      hashpow2(t, (str)->tsv.hash)
62#define hashstr(t,str)      hashpow2(t, (str)->hash)
5463#define hashboolean(t,p)   hashpow2(t, p)
64#define hashint(t,i)      hashpow2(t, i)
5565
5666
5767/*
r242885r242886
6171#define hashmod(t,n)   (gnode(t, ((n) % ((sizenode(t)-1)|1))))
6272
6373
64#define hashpointer(t,p)   hashmod(t, IntPoint(p))
74#define hashpointer(t,p)   hashmod(t, point2int(p))
6575
6676
6777#define dummynode      (&dummynode_)
r242885r242886
7080
7181static const Node dummynode_ = {
7282  {NILCONSTANT},  /* value */
73  {{NILCONSTANT, NULL}}  /* key */
83  {{NILCONSTANT, 0}}  /* key */
7484};
7585
7686
7787/*
78** hash for lua_Numbers
88** Checks whether a float has a value representable as a lua_Integer
89** (and does the conversion if so)
7990*/
80static Node *hashnum (const Table *t, lua_Number n) {
91static int numisinteger (lua_Number x, lua_Integer *p) {
92  if ((x) == l_floor(x))  /* integral value? */
93    return lua_numbertointeger(x, p);  /* try as an integer */
94  else return 0;
95}
96
97
98/*
99** hash for floating-point numbers
100*/
101static Node *hashfloat (const Table *t, lua_Number n) {
81102  int i;
82  luai_hashnum(i, n);
103  n = l_mathop(frexp)(n, &i) * cast_num(INT_MAX - DBL_MAX_EXP);
104  i += cast_int(n);
83105  if (i < 0) {
84106    if (cast(unsigned int, i) == 0u - i)  /* use unsigned to avoid overflows */
85107      i = 0;  /* handle INT_MIN */
r242885r242886
91113
92114
93115/*
94** returns the `main' position of an element in a table (that is, the index
116** returns the 'main' position of an element in a table (that is, the index
95117** of its hash value)
96118*/
97119static Node *mainposition (const Table *t, const TValue *key) {
98120  switch (ttype(key)) {
99    case LUA_TNUMBER:
100      return hashnum(t, nvalue(key));
121    case LUA_TNUMINT:
122      return hashint(t, ivalue(key));
123    case LUA_TNUMFLT:
124      return hashfloat(t, fltvalue(key));
125    case LUA_TSHRSTR:
126      return hashstr(t, tsvalue(key));
101127    case LUA_TLNGSTR: {
102      TString *s = rawtsvalue(key);
103      if (s->tsv.extra == 0) {  /* no hash? */
104        s->tsv.hash = luaS_hash(getstr(s), s->tsv.len, s->tsv.hash);
105        s->tsv.extra = 1;  /* now it has its hash */
128      TString *s = tsvalue(key);
129      if (s->extra == 0) {  /* no hash? */
130        s->hash = luaS_hash(getstr(s), s->len, s->hash);
131        s->extra = 1;  /* now it has its hash */
106132      }
107      return hashstr(t, rawtsvalue(key));
133      return hashstr(t, tsvalue(key));
108134    }
109    case LUA_TSHRSTR:
110      return hashstr(t, rawtsvalue(key));
111135    case LUA_TBOOLEAN:
112136      return hashboolean(t, bvalue(key));
113137    case LUA_TLIGHTUSERDATA:
r242885r242886
121145
122146
123147/*
124** returns the index for `key' if `key' is an appropriate key to live in
125** the array part of the table, -1 otherwise.
148** returns the index for 'key' if 'key' is an appropriate key to live in
149** the array part of the table, 0 otherwise.
126150*/
127static int arrayindex (const TValue *key) {
128  if (ttisnumber(key)) {
129    lua_Number n = nvalue(key);
130    int k;
131    lua_number2int(k, n);
132    if (luai_numeq(cast_num(k), n))
133      return k;
151static unsigned int arrayindex (const TValue *key) {
152  if (ttisinteger(key)) {
153    lua_Integer k = ivalue(key);
154    if (0 < k && (lua_Unsigned)k <= MAXASIZE)
155      return cast(unsigned int, k);  /* 'key' is an appropriate array index */
134156  }
135  return -1;  /* `key' did not match some condition */
157  return 0;  /* 'key' did not match some condition */
136158}
137159
138160
139161/*
140** returns the index of a `key' for table traversals. First goes all
162** returns the index of a 'key' for table traversals. First goes all
141163** elements in the array part, then elements in the hash part. The
142** beginning of a traversal is signaled by -1.
164** beginning of a traversal is signaled by 0.
143165*/
144static int findindex (lua_State *L, Table *t, StkId key) {
145  int i;
146  if (ttisnil(key)) return -1;  /* first iteration */
166static unsigned int findindex (lua_State *L, Table *t, StkId key) {
167  unsigned int i;
168  if (ttisnil(key)) return 0;  /* first iteration */
147169  i = arrayindex(key);
148  if (0 < i && i <= t->sizearray)  /* is `key' inside array part? */
149    return i-1;  /* yes; that's the index (corrected to C) */
170  if (i != 0 && i <= t->sizearray)  /* is 'key' inside array part? */
171    return i;  /* yes; that's the index */
150172  else {
173    int nx;
151174    Node *n = mainposition(t, key);
152    for (;;) {  /* check whether `key' is somewhere in the chain */
153      /* key may be dead already, but it is ok to use it in `next' */
175    for (;;) {  /* check whether 'key' is somewhere in the chain */
176      /* key may be dead already, but it is ok to use it in 'next' */
154177      if (luaV_rawequalobj(gkey(n), key) ||
155178            (ttisdeadkey(gkey(n)) && iscollectable(key) &&
156179             deadvalue(gkey(n)) == gcvalue(key))) {
157180        i = cast_int(n - gnode(t, 0));  /* key index in hash table */
158181        /* hash elements are numbered after array ones */
159        return i + t->sizearray;
182        return (i + 1) + t->sizearray;
160183      }
161      else n = gnext(n);
162      if (n == NULL)
163        luaG_runerror(L, "invalid key to " LUA_QL("next"));  /* key not found */
184      nx = gnext(n);
185      if (nx == 0)
186        luaG_runerror(L, "invalid key to 'next'");  /* key not found */
187      else n += nx;
164188    }
165189  }
166190}
167191
168192
169193int luaH_next (lua_State *L, Table *t, StkId key) {
170  int i = findindex(L, t, key);  /* find original element */
171  for (i++; i < t->sizearray; i++) {  /* try first array part */
194  unsigned int i = findindex(L, t, key);  /* find original element */
195  for (; i < t->sizearray; i++) {  /* try first array part */
172196    if (!ttisnil(&t->array[i])) {  /* a non-nil value? */
173      setnvalue(key, cast_num(i+1));
197      setivalue(key, i + 1);
174198      setobj2s(L, key+1, &t->array[i]);
175199      return 1;
176200    }
177201  }
178  for (i -= t->sizearray; i < sizenode(t); i++) {  /* then hash part */
202  for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) {  /* hash part */
179203    if (!ttisnil(gval(gnode(t, i)))) {  /* a non-nil value? */
180204      setobj2s(L, key, gkey(gnode(t, i)));
181205      setobj2s(L, key+1, gval(gnode(t, i)));
r242885r242886
192216** ==============================================================
193217*/
194218
195
196static int computesizes (int nums[], int *narray) {
219/*
220** Compute the optimal size for the array part of table 't'. 'nums' is a
221** "count array" where 'nums[i]' is the number of integers in the table
222** between 2^(i - 1) + 1 and 2^i. Put in '*narray' the optimal size, and
223** return the number of elements that will go to that part.
224*/
225static unsigned int computesizes (unsigned int nums[], unsigned int *narray) {
197226  int i;
198  int twotoi;  /* 2^i */
199  int a = 0;  /* number of elements smaller than 2^i */
200  int na = 0;  /* number of elements to go to array part */
201  int n = 0;  /* optimal size for array part */
227  unsigned int twotoi;  /* 2^i */
228  unsigned int a = 0;  /* number of elements smaller than 2^i */
229  unsigned int na = 0;  /* number of elements to go to array part */
230  unsigned int n = 0;  /* optimal size for array part */
202231  for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
203232    if (nums[i] > 0) {
204233      a += nums[i];
205234      if (a > twotoi/2) {  /* more than half elements present? */
206235        n = twotoi;  /* optimal size (till now) */
207        na = a;  /* all elements smaller than n will go to array part */
236        na = a;  /* all elements up to 'n' will go to array part */
208237      }
209238    }
210239    if (a == *narray) break;  /* all elements already counted */
r242885r242886
215244}
216245
217246
218static int countint (const TValue *key, int *nums) {
219  int k = arrayindex(key);
220  if (0 < k && k <= MAXASIZE) {  /* is `key' an appropriate array index? */
247static int countint (const TValue *key, unsigned int *nums) {
248  unsigned int k = arrayindex(key);
249  if (k != 0) {  /* is 'key' an appropriate array index? */
221250    nums[luaO_ceillog2(k)]++;  /* count as such */
222251    return 1;
223252  }
r242885r242886
226255}
227256
228257
229static int numusearray (const Table *t, int *nums) {
258static unsigned int numusearray (const Table *t, unsigned int *nums) {
230259  int lg;
231  int ttlg;  /* 2^lg */
232  int ause = 0;  /* summation of `nums' */
233  int i = 1;  /* count to traverse all array keys */
234  for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) {  /* for each slice */
235    int lc = 0;  /* counter */
236    int lim = ttlg;
260  unsigned int ttlg;  /* 2^lg */
261  unsigned int ause = 0;  /* summation of 'nums' */
262  unsigned int i = 1;  /* count to traverse all array keys */
263  /* traverse each slice */
264  for (lg = 0, ttlg = 1; lg <= MAXABITS; lg++, ttlg *= 2) {
265    unsigned int lc = 0;  /* counter */
266    unsigned int lim = ttlg;
237267    if (lim > t->sizearray) {
238268      lim = t->sizearray;  /* adjust upper limit */
239269      if (i > lim)
240270        break;  /* no more elements to count */
241271    }
242    /* count elements in range (2^(lg-1), 2^lg] */
272    /* count elements in range (2^(lg - 1), 2^lg] */
243273    for (; i <= lim; i++) {
244274      if (!ttisnil(&t->array[i-1]))
245275        lc++;
r242885r242886
251281}
252282
253283
254static int numusehash (const Table *t, int *nums, int *pnasize) {
284static int numusehash (const Table *t, unsigned int *nums,
285                       unsigned int *pnasize) {
255286  int totaluse = 0;  /* total number of elements */
256  int ause = 0;  /* summation of `nums' */
287  int ause = 0;  /* elements added to 'nums' (can go to array part) */
257288  int i = sizenode(t);
258289  while (i--) {
259290    Node *n = &t->node[i];
r242885r242886
267298}
268299
269300
270static void setarrayvector (lua_State *L, Table *t, int size) {
271  int i;
301static void setarrayvector (lua_State *L, Table *t, unsigned int size) {
302  unsigned int i;
272303  luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
273304  for (i=t->sizearray; i<size; i++)
274305     setnilvalue(&t->array[i]);
r242885r242886
276307}
277308
278309
279static void setnodevector (lua_State *L, Table *t, int size) {
310static void setnodevector (lua_State *L, Table *t, unsigned int size) {
280311  int lsize;
281312  if (size == 0) {  /* no elements to hash part? */
282    t->node = cast(Node *, dummynode);  /* use common `dummynode' */
313    t->node = cast(Node *, dummynode);  /* use common 'dummynode' */
283314    lsize = 0;
284315  }
285316  else {
286317    int i;
287318    lsize = luaO_ceillog2(size);
288    if (lsize > MAXBITS)
319    if (lsize > MAXHBITS)
289320      luaG_runerror(L, "table overflow");
290321    size = twoto(lsize);
291322    t->node = luaM_newvector(L, size, Node);
292    for (i=0; i<size; i++) {
323    for (i = 0; i < (int)size; i++) {
293324      Node *n = gnode(t, i);
294      gnext(n) = NULL;
295      setnilvalue(gkey(n));
325      gnext(n) = 0;
326      setnilvalue(wgkey(n));
296327      setnilvalue(gval(n));
297328    }
298329  }
r242885r242886
301332}
302333
303334
304void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
305  int i;
306  int oldasize = t->sizearray;
335void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
336                                          unsigned int nhsize) {
337  unsigned int i;
338  int j;
339  unsigned int oldasize = t->sizearray;
307340  int oldhsize = t->lsizenode;
308341  Node *nold = t->node;  /* save old hash ... */
309342  if (nasize > oldasize)  /* array part must grow? */
r242885r242886
321354    luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
322355  }
323356  /* re-insert elements from hash part */
324  for (i = twoto(oldhsize) - 1; i >= 0; i--) {
325    Node *old = nold+i;
357  for (j = twoto(oldhsize) - 1; j >= 0; j--) {
358    Node *old = nold + j;
326359    if (!ttisnil(gval(old))) {
327360      /* doesn't need barrier/invalidate cache, as entry was
328361         already present in the table */
r242885r242886
334367}
335368
336369
337void luaH_resizearray (lua_State *L, Table *t, int nasize) {
370void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
338371  int nsize = isdummy(t->node) ? 0 : sizenode(t);
339372  luaH_resize(L, t, nasize, nsize);
340373}
341374
342
375/*
376** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
377*/
343378static void rehash (lua_State *L, Table *t, const TValue *ek) {
344  int nasize, na;
345  int nums[MAXBITS+1];  /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */
379  unsigned int nasize, na;
380  unsigned int nums[MAXABITS + 1];
346381  int i;
347382  int totaluse;
348  for (i=0; i<=MAXBITS; i++) nums[i] = 0;  /* reset counts */
383  for (i = 0; i <= MAXABITS; i++) nums[i] = 0;  /* reset counts */
349384  nasize = numusearray(t, nums);  /* count keys in array part */
350385  totaluse = nasize;  /* all those keys are integer keys */
351386  totaluse += numusehash(t, nums, &nasize);  /* count keys in hash part */
r242885r242886
366401
367402
368403Table *luaH_new (lua_State *L) {
369  Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h;
404  GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));
405  Table *t = gco2t(o);
370406  t->metatable = NULL;
371407  t->flags = cast_byte(~0);
372408  t->array = NULL;
r242885r242886
404440*/
405441TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
406442  Node *mp;
443  TValue aux;
407444  if (ttisnil(key)) luaG_runerror(L, "table index is nil");
408  else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))
409    luaG_runerror(L, "table index is NaN");
445  else if (ttisfloat(key)) {
446    lua_Number n = fltvalue(key);
447    lua_Integer k;
448    if (luai_numisnan(n))
449      luaG_runerror(L, "table index is NaN");
450    if (numisinteger(n, &k)) {  /* index is int? */
451      setivalue(&aux, k);
452      key = &aux;  /* insert it as an integer */
453    }
454  }
410455  mp = mainposition(t, key);
411456  if (!ttisnil(gval(mp)) || isdummy(mp)) {  /* main position is taken? */
412457    Node *othern;
413    Node *n = getfreepos(t);  /* get a free place */
414    if (n == NULL) {  /* cannot find a free place? */
458    Node *f = getfreepos(t);  /* get a free place */
459    if (f == NULL) {  /* cannot find a free place? */
415460      rehash(L, t, key);  /* grow table */
416      /* whatever called 'newkey' take care of TM cache and GC barrier */
461      /* whatever called 'newkey' takes care of TM cache and GC barrier */
417462      return luaH_set(L, t, key);  /* insert key into grown table */
418463    }
419    lua_assert(!isdummy(n));
464    lua_assert(!isdummy(f));
420465    othern = mainposition(t, gkey(mp));
421466    if (othern != mp) {  /* is colliding node out of its main position? */
422467      /* yes; move colliding node into free position */
423      while (gnext(othern) != mp) othern = gnext(othern);  /* find previous */
424      gnext(othern) = n;  /* redo the chain with `n' in place of `mp' */
425      *n = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
426      gnext(mp) = NULL;  /* now `mp' is free */
468      while (othern + gnext(othern) != mp)  /* find previous */
469        othern += gnext(othern);
470      gnext(othern) = cast_int(f - othern);  /* rechain to point to 'f' */
471      *f = *mp;  /* copy colliding node into free pos. (mp->next also goes) */
472      if (gnext(mp) != 0) {
473        gnext(f) += cast_int(mp - f);  /* correct 'next' */
474        gnext(mp) = 0;  /* now 'mp' is free */
475      }
427476      setnilvalue(gval(mp));
428477    }
429478    else {  /* colliding node is in its own main position */
430479      /* new node will go into free position */
431      gnext(n) = gnext(mp);  /* chain new position */
432      gnext(mp) = n;
433      mp = n;
480      if (gnext(mp) != 0)
481        gnext(f) = cast_int((mp + gnext(mp)) - f);  /* chain new position */
482      else lua_assert(gnext(f) == 0);
483      gnext(mp) = cast_int(f - mp);
484      mp = f;
434485    }
435486  }
436  setobj2t(L, gkey(mp), key);
437  luaC_barrierback(L, obj2gco(t), key);
487  setnodekey(L, &mp->i_key, key);
488  luaC_barrierback(L, t, key);
438489  lua_assert(ttisnil(gval(mp)));
439490  return gval(mp);
440491}
r242885r242886
443494/*
444495** search function for integers
445496*/
446const TValue *luaH_getint (Table *t, int key) {
497const TValue *luaH_getint (Table *t, lua_Integer key) {
447498  /* (1 <= key && key <= t->sizearray) */
448  if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
449    return &t->array[key-1];
499  if (l_castS2U(key - 1) < t->sizearray)
500    return &t->array[key - 1];
450501  else {
451    lua_Number nk = cast_num(key);
452    Node *n = hashnum(t, nk);
453    do {  /* check whether `key' is somewhere in the chain */
454      if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk))
502    Node *n = hashint(t, key);
503    for (;;) {  /* check whether 'key' is somewhere in the chain */
504      if (ttisinteger(gkey(n)) && ivalue(gkey(n)) == key)
455505        return gval(n);  /* that's it */
456      else n = gnext(n);
457    } while (n);
506      else {
507        int nx = gnext(n);
508        if (nx == 0) break;
509        n += nx;
510      }
511    };
458512    return luaO_nilobject;
459513  }
460514}
r242885r242886
465519*/
466520const TValue *luaH_getstr (Table *t, TString *key) {
467521  Node *n = hashstr(t, key);
468  lua_assert(key->tsv.tt == LUA_TSHRSTR);
469  do {  /* check whether `key' is somewhere in the chain */
470    if (ttisshrstring(gkey(n)) && eqshrstr(rawtsvalue(gkey(n)), key))
522  lua_assert(key->tt == LUA_TSHRSTR);
523  for (;;) {  /* check whether 'key' is somewhere in the chain */
524    const TValue *k = gkey(n);
525    if (ttisshrstring(k) && eqshrstr(tsvalue(k), key))
471526      return gval(n);  /* that's it */
472    else n = gnext(n);
473  } while (n);
527    else {
528      int nx = gnext(n);
529      if (nx == 0) break;
530      n += nx;
531    }
532  };
474533  return luaO_nilobject;
475534}
476535
r242885r242886
480539*/
481540const TValue *luaH_get (Table *t, const TValue *key) {
482541  switch (ttype(key)) {
483    case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key));
542    case LUA_TSHRSTR: return luaH_getstr(t, tsvalue(key));
543    case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
484544    case LUA_TNIL: return luaO_nilobject;
485    case LUA_TNUMBER: {
486      int k;
487      lua_Number n = nvalue(key);
488      lua_number2int(k, n);
489      if (luai_numeq(cast_num(k), n)) /* index is int? */
545    case LUA_TNUMFLT: {
546      lua_Integer k;
547      if (numisinteger(fltvalue(key), &k)) /* index is int? */
490548        return luaH_getint(t, k);  /* use specialized version */
491549      /* else go through */
492550    }
493551    default: {
494552      Node *n = mainposition(t, key);
495      do {  /* check whether `key' is somewhere in the chain */
553      for (;;) {  /* check whether 'key' is somewhere in the chain */
496554        if (luaV_rawequalobj(gkey(n), key))
497555          return gval(n);  /* that's it */
498        else n = gnext(n);
499      } while (n);
556        else {
557          int nx = gnext(n);
558          if (nx == 0) break;
559          n += nx;
560        }
561      };
500562      return luaO_nilobject;
501563    }
502564  }
r242885r242886
515577}
516578
517579
518void luaH_setint (lua_State *L, Table *t, int key, TValue *value) {
580void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
519581  const TValue *p = luaH_getint(t, key);
520582  TValue *cell;
521583  if (p != luaO_nilobject)
522584    cell = cast(TValue *, p);
523585  else {
524586    TValue k;
525    setnvalue(&k, cast_num(key));
587    setivalue(&k, key);
526588    cell = luaH_newkey(L, t, &k);
527589  }
528590  setobj2t(L, cell, value);
r242885r242886
532594static int unbound_search (Table *t, unsigned int j) {
533595  unsigned int i = j;  /* i is zero or a present index */
534596  j++;
535  /* find `i' and `j' such that i is present and j is not */
597  /* find 'i' and 'j' such that i is present and j is not */
536598  while (!ttisnil(luaH_getint(t, j))) {
537599    i = j;
538    j *= 2;
539    if (j > cast(unsigned int, MAX_INT)) {  /* overflow? */
600    if (j > cast(unsigned int, MAX_INT)/2) {  /* overflow? */
540601      /* table was built with bad purposes: resort to linear search */
541602      i = 1;
542603      while (!ttisnil(luaH_getint(t, i))) i++;
543604      return i - 1;
544605    }
606    j *= 2;
545607  }
546608  /* now do a binary search between them */
547609  while (j - i > 1) {
r242885r242886
554616
555617
556618/*
557** Try to find a boundary in table `t'. A `boundary' is an integer index
619** Try to find a boundary in table 't'. A 'boundary' is an integer index
558620** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
559621*/
560622int luaH_getn (Table *t) {
trunk/3rdparty/lua/src/ltable.h
r242885r242886
11/*
2** $Id: ltable.h,v 2.16.1.2 2013/08/30 15:49:41 roberto Exp $
2** $Id: ltable.h,v 2.20 2014/09/04 18:15:29 roberto Exp $
33** Lua tables (hash)
44** See Copyright Notice in lua.h
55*/
r242885r242886
1111
1212
1313#define gnode(t,i)   (&(t)->node[i])
14#define gkey(n)      (&(n)->i_key.tvk)
1514#define gval(n)      (&(n)->i_val)
1615#define gnext(n)   ((n)->i_key.nk.next)
1716
17
18/* 'const' to avoid wrong writings that can mess up field 'next' */
19#define gkey(n)      cast(const TValue*, (&(n)->i_key.tvk))
20
21#define wgkey(n)      (&(n)->i_key.nk)
22
1823#define invalidateTMcache(t)   ((t)->flags = 0)
1924
25
2026/* returns the key, given the value of a table entry */
2127#define keyfromval(v) \
2228  (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val))))
2329
2430
25LUAI_FUNC const TValue *luaH_getint (Table *t, int key);
26LUAI_FUNC void luaH_setint (lua_State *L, Table *t, int key, TValue *value);
31LUAI_FUNC const TValue *luaH_getint (Table *t, lua_Integer key);
32LUAI_FUNC void luaH_setint (lua_State *L, Table *t, lua_Integer key,
33                                                    TValue *value);
2734LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
2835LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
2936LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key);
3037LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
3138LUAI_FUNC Table *luaH_new (lua_State *L);
32LUAI_FUNC void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize);
33LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, int nasize);
39LUAI_FUNC void luaH_resize (lua_State *L, Table *t, unsigned int nasize,
40                                                    unsigned int nhsize);
41LUAI_FUNC void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize);
3442LUAI_FUNC void luaH_free (lua_State *L, Table *t);
3543LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
3644LUAI_FUNC int luaH_getn (Table *t);
trunk/3rdparty/lua/src/ltablib.c
r242885r242886
11/*
2** $Id: ltablib.c,v 1.65.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: ltablib.c,v 1.79 2014/11/02 19:19:04 roberto Exp $
33** Library for Table Manipulation
44** See Copyright Notice in lua.h
55*/
66
7#define ltablib_c
8#define LUA_LIB
79
10#include "lprefix.h"
11
12
13#include <limits.h>
814#include <stddef.h>
915
10#define ltablib_c
11#define LUA_LIB
12
1316#include "lua.h"
1417
1518#include "lauxlib.h"
1619#include "lualib.h"
1720
1821
19#define aux_getn(L,n)   (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n))
2022
23/*
24** Structure with table-access functions
25*/
26typedef struct {
27  int (*geti) (lua_State *L, int idx, lua_Integer n);
28  void (*seti) (lua_State *L, int idx, lua_Integer n);
29} TabA;
2130
2231
32/*
33** Check that 'arg' has a table and set access functions in 'ta' to raw
34** or non-raw according to the presence of corresponding metamethods.
35*/
36static void checktab (lua_State *L, int arg, TabA *ta) {
37  ta->geti = NULL; ta->seti = NULL;
38  if (lua_getmetatable(L, arg)) {
39    lua_pushliteral(L, "__index");  /* 'index' metamethod */
40    if (lua_rawget(L, -2) != LUA_TNIL)
41      ta->geti = lua_geti;
42    lua_pushliteral(L, "__newindex");  /* 'newindex' metamethod */
43    if (lua_rawget(L, -3) != LUA_TNIL)
44      ta->seti = lua_seti;
45    lua_pop(L, 3);  /* pop metatable plus both metamethods */
46  }
47  if (ta->geti == NULL || ta->seti == NULL) {
48    luaL_checktype(L, arg, LUA_TTABLE);  /* must be table for raw methods */
49    if (ta->geti == NULL) ta->geti = lua_rawgeti;
50    if (ta->seti == NULL) ta->seti = lua_rawseti;
51  }
52}
53
54
55#define aux_getn(L,n,ta)   (checktab(L, n, ta), luaL_len(L, n))
56
57
2358#if defined(LUA_COMPAT_MAXN)
2459static int maxn (lua_State *L) {
2560  lua_Number max = 0;
r242885r242886
3974
4075
4176static int tinsert (lua_State *L) {
42  int e = aux_getn(L, 1) + 1;  /* first empty element */
43  int pos;  /* where to insert new element */
77  TabA ta;
78  lua_Integer e = aux_getn(L, 1, &ta) + 1;  /* first empty element */
79  lua_Integer pos;  /* where to insert new element */
4480  switch (lua_gettop(L)) {
4581    case 2: {  /* called with only 2 arguments */
4682      pos = e;  /* insert new element at the end */
4783      break;
4884    }
4985    case 3: {
50      int i;
51      pos = luaL_checkint(L, 2);  /* 2nd argument is the position */
86      lua_Integer i;
87      pos = luaL_checkinteger(L, 2);  /* 2nd argument is the position */
5288      luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds");
5389      for (i = e; i > pos; i--) {  /* move up elements */
54        lua_rawgeti(L, 1, i-1);
55        lua_rawseti(L, 1, i);  /* t[i] = t[i-1] */
90        (*ta.geti)(L, 1, i - 1);
91        (*ta.seti)(L, 1, i);  /* t[i] = t[i - 1] */
5692      }
5793      break;
5894    }
5995    default: {
60      return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
96      return luaL_error(L, "wrong number of arguments to 'insert'");
6197    }
6298  }
63  lua_rawseti(L, 1, pos);  /* t[pos] = v */
99  (*ta.seti)(L, 1, pos);  /* t[pos] = v */
64100  return 0;
65101}
66102
67103
68104static int tremove (lua_State *L) {
69  int size = aux_getn(L, 1);
70  int pos = luaL_optint(L, 2, size);
105  TabA ta;
106  lua_Integer size = aux_getn(L, 1, &ta);
107  lua_Integer pos = luaL_optinteger(L, 2, size);
71108  if (pos != size)  /* validate 'pos' if given */
72109    luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds");
73  lua_rawgeti(L, 1, pos);  /* result = t[pos] */
110  (*ta.geti)(L, 1, pos);  /* result = t[pos] */
74111  for ( ; pos < size; pos++) {
75    lua_rawgeti(L, 1, pos+1);
76    lua_rawseti(L, 1, pos);  /* t[pos] = t[pos+1] */
112    (*ta.geti)(L, 1, pos + 1);
113    (*ta.seti)(L, 1, pos);  /* t[pos] = t[pos + 1] */
77114  }
78115  lua_pushnil(L);
79  lua_rawseti(L, 1, pos);  /* t[pos] = nil */
116  (*ta.seti)(L, 1, pos);  /* t[pos] = nil */
80117  return 1;
81118}
82119
83120
84static void addfield (lua_State *L, luaL_Buffer *b, int i) {
85  lua_rawgeti(L, 1, i);
121static int tmove (lua_State *L) {
122  TabA ta;
123  lua_Integer f = luaL_checkinteger(L, 2);
124  lua_Integer e = luaL_checkinteger(L, 3);
125  lua_Integer t = luaL_checkinteger(L, 4);
126  int tt = !lua_isnoneornil(L, 5) ? 5 : 1;  /* destination table */
127  /* the following restriction avoids several problems with overflows */
128  luaL_argcheck(L, f > 0, 2, "initial position must be positive");
129  if (e >= f) {  /* otherwise, nothing to move */
130    lua_Integer n, i;
131    ta.geti = (luaL_getmetafield(L, 1, "__index") == LUA_TNIL)
132      ? (luaL_checktype(L, 1, LUA_TTABLE), lua_rawgeti)
133      : lua_geti;
134    ta.seti = (luaL_getmetafield(L, tt, "__newindex") == LUA_TNIL)
135      ? (luaL_checktype(L, tt, LUA_TTABLE), lua_rawseti)
136      : lua_seti;
137    n = e - f + 1;  /* number of elements to move */
138    if (t > f) {
139      for (i = n - 1; i >= 0; i--) {
140        (*ta.geti)(L, 1, f + i);
141        (*ta.seti)(L, tt, t + i);
142      }
143    }
144    else {
145      for (i = 0; i < n; i++) {
146        (*ta.geti)(L, 1, f + i);
147        (*ta.seti)(L, tt, t + i);
148      }
149    }
150  }
151  lua_pushvalue(L, tt);  /* return "to table" */
152  return 1;
153}
154
155
156static void addfield (lua_State *L, luaL_Buffer *b, TabA *ta, lua_Integer i) {
157  (*ta->geti)(L, 1, i);
86158  if (!lua_isstring(L, -1))
87    luaL_error(L, "invalid value (%s) at index %d in table for "
88                  LUA_QL("concat"), luaL_typename(L, -1), i);
159    luaL_error(L, "invalid value (%s) at index %d in table for 'concat'",
160                  luaL_typename(L, -1), i);
89161  luaL_addvalue(b);
90162}
91163
92164
93165static int tconcat (lua_State *L) {
166  TabA ta;
94167  luaL_Buffer b;
95168  size_t lsep;
96  int i, last;
169  lua_Integer i, last;
97170  const char *sep = luaL_optlstring(L, 2, "", &lsep);
98  luaL_checktype(L, 1, LUA_TTABLE);
99  i = luaL_optint(L, 3, 1);
100  last = luaL_opt(L, luaL_checkint, 4, luaL_len(L, 1));
171  checktab(L, 1, &ta);
172  i = luaL_optinteger(L, 3, 1);
173  last = luaL_opt(L, luaL_checkinteger, 4, luaL_len(L, 1));
101174  luaL_buffinit(L, &b);
102175  for (; i < last; i++) {
103    addfield(L, &b, i);
176    addfield(L, &b, &ta, i);
104177    luaL_addlstring(&b, sep, lsep);
105178  }
106179  if (i == last)  /* add last value (if interval was not empty) */
107    addfield(L, &b, i);
180    addfield(L, &b, &ta, i);
108181  luaL_pushresult(&b);
109182  return 1;
110183}
r242885r242886
117190*/
118191
119192static int pack (lua_State *L) {
193  int i;
120194  int n = lua_gettop(L);  /* number of elements to pack */
121195  lua_createtable(L, n, 1);  /* create result table */
196  lua_insert(L, 1);  /* put it at index 1 */
197  for (i = n; i >= 1; i--)  /* assign elements */
198    lua_rawseti(L, 1, i);
122199  lua_pushinteger(L, n);
123  lua_setfield(L, -2, "n");  /* t.n = number of elements */
124  if (n > 0) {  /* at least one element? */
125    int i;
126    lua_pushvalue(L, 1);
127    lua_rawseti(L, -2, 1);  /* insert first element */
128    lua_replace(L, 1);  /* move table into index 1 */
129    for (i = n; i >= 2; i--)  /* assign other elements */
130      lua_rawseti(L, 1, i);
131  }
200  lua_setfield(L, 1, "n");  /* t.n = number of elements */
132201  return 1;  /* return table */
133202}
134203
135204
136205static int unpack (lua_State *L) {
137  int i, e, n;
138  luaL_checktype(L, 1, LUA_TTABLE);
139  i = luaL_optint(L, 2, 1);
140  e = luaL_opt(L, luaL_checkint, 3, luaL_len(L, 1));
206  TabA ta;
207  lua_Integer i, e;
208  lua_Unsigned n;
209  checktab(L, 1, &ta);
210  i = luaL_optinteger(L, 2, 1);
211  e = luaL_opt(L, luaL_checkinteger, 3, luaL_len(L, 1));
141212  if (i > e) return 0;  /* empty range */
142  n = e - i + 1;  /* number of elements */
143  if (n <= 0 || !lua_checkstack(L, n))  /* n <= 0 means arith. overflow */
213  n = (lua_Unsigned)e - i;  /* number of elements minus 1 (avoid overflows) */
214  if (n >= (unsigned int)INT_MAX  || !lua_checkstack(L, (int)(++n)))
144215    return luaL_error(L, "too many results to unpack");
145  lua_rawgeti(L, 1, i);  /* push arg[i] (avoiding overflow problems) */
146  while (i++ < e)  /* push arg[i + 1...e] */
147    lua_rawgeti(L, 1, i);
148  return n;
216  do {  /* must have at least one element */
217    (*ta.geti)(L, 1, i);  /* push arg[i..e] */
218  } while (i++ < e);
219
220  return (int)n;
149221}
150222
151223/* }====================================================== */
r242885r242886
155227/*
156228** {======================================================
157229** Quicksort
158** (based on `Algorithms in MODULA-3', Robert Sedgewick;
230** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
159231**  Addison-Wesley, 1993.)
160232** =======================================================
161233*/
162234
163235
164static void set2 (lua_State *L, int i, int j) {
165  lua_rawseti(L, 1, i);
166  lua_rawseti(L, 1, j);
236static void set2 (lua_State *L, TabA *ta, int i, int j) {
237  (*ta->seti)(L, 1, i);
238  (*ta->seti)(L, 1, j);
167239}
168240
169241static int sort_comp (lua_State *L, int a, int b) {
r242885r242886
171243    int res;
172244    lua_pushvalue(L, 2);
173245    lua_pushvalue(L, a-1);  /* -1 to compensate function */
174    lua_pushvalue(L, b-2);  /* -2 to compensate function and `a' */
246    lua_pushvalue(L, b-2);  /* -2 to compensate function and 'a' */
175247    lua_call(L, 2, 1);
176248    res = lua_toboolean(L, -1);
177249    lua_pop(L, 1);
r242885r242886
181253    return lua_compare(L, a, b, LUA_OPLT);
182254}
183255
184static void auxsort (lua_State *L, int l, int u) {
256static void auxsort (lua_State *L, TabA *ta, int l, int u) {
185257  while (l < u) {  /* for tail recursion */
186258    int i, j;
187259    /* sort elements a[l], a[(l+u)/2] and a[u] */
188    lua_rawgeti(L, 1, l);
189    lua_rawgeti(L, 1, u);
260    (*ta->geti)(L, 1, l);
261    (*ta->geti)(L, 1, u);
190262    if (sort_comp(L, -1, -2))  /* a[u] < a[l]? */
191      set2(L, l, u);  /* swap a[l] - a[u] */
263      set2(L, ta, l, u);  /* swap a[l] - a[u] */
192264    else
193265      lua_pop(L, 2);
194266    if (u-l == 1) break;  /* only 2 elements */
195267    i = (l+u)/2;
196    lua_rawgeti(L, 1, i);
197    lua_rawgeti(L, 1, l);
268    (*ta->geti)(L, 1, i);
269    (*ta->geti)(L, 1, l);
198270    if (sort_comp(L, -2, -1))  /* a[i]<a[l]? */
199      set2(L, i, l);
271      set2(L, ta, i, l);
200272    else {
201273      lua_pop(L, 1);  /* remove a[l] */
202      lua_rawgeti(L, 1, u);
274      (*ta->geti)(L, 1, u);
203275      if (sort_comp(L, -1, -2))  /* a[u]<a[i]? */
204        set2(L, i, u);
276        set2(L, ta, i, u);
205277      else
206278        lua_pop(L, 2);
207279    }
208280    if (u-l == 2) break;  /* only 3 elements */
209    lua_rawgeti(L, 1, i);  /* Pivot */
281    (*ta->geti)(L, 1, i);  /* Pivot */
210282    lua_pushvalue(L, -1);
211    lua_rawgeti(L, 1, u-1);
212    set2(L, i, u-1);
283    (*ta->geti)(L, 1, u-1);
284    set2(L, ta, i, u-1);
213285    /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
214286    i = l; j = u-1;
215287    for (;;) {  /* invariant: a[l..i] <= P <= a[j..u] */
216288      /* repeat ++i until a[i] >= P */
217      while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
289      while ((*ta->geti)(L, 1, ++i), sort_comp(L, -1, -2)) {
218290        if (i>=u) luaL_error(L, "invalid order function for sorting");
219291        lua_pop(L, 1);  /* remove a[i] */
220292      }
221293      /* repeat --j until a[j] <= P */
222      while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
294      while ((*ta->geti)(L, 1, --j), sort_comp(L, -3, -1)) {
223295        if (j<=l) luaL_error(L, "invalid order function for sorting");
224296        lua_pop(L, 1);  /* remove a[j] */
225297      }
r242885r242886
227299        lua_pop(L, 3);  /* pop pivot, a[i], a[j] */
228300        break;
229301      }
230      set2(L, i, j);
302      set2(L, ta, i, j);
231303    }
232    lua_rawgeti(L, 1, u-1);
233    lua_rawgeti(L, 1, i);
234    set2(L, u-1, i);  /* swap pivot (a[u-1]) with a[i] */
304    (*ta->geti)(L, 1, u-1);
305    (*ta->geti)(L, 1, i);
306    set2(L, ta, u-1, i);  /* swap pivot (a[u-1]) with a[i] */
235307    /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
236308    /* adjust so that smaller half is in [j..i] and larger one in [l..u] */
237309    if (i-l < u-i) {
r242885r242886
240312    else {
241313      j=i+1; i=u; u=j-2;
242314    }
243    auxsort(L, j, i);  /* call recursively the smaller one */
315    auxsort(L, ta, j, i);  /* call recursively the smaller one */
244316  }  /* repeat the routine for the larger one */
245317}
246318
247319static int sort (lua_State *L) {
248  int n = aux_getn(L, 1);
249  luaL_checkstack(L, 40, "");  /* assume array is smaller than 2^40 */
320  TabA ta;
321  int n = (int)aux_getn(L, 1, &ta);
322  luaL_checkstack(L, 50, "");  /* assume array is smaller than 2^50 */
250323  if (!lua_isnoneornil(L, 2))  /* is there a 2nd argument? */
251324    luaL_checktype(L, 2, LUA_TFUNCTION);
252  lua_settop(L, 2);  /* make sure there is two arguments */
253  auxsort(L, 1, n);
325  lua_settop(L, 2);  /* make sure there are two arguments */
326  auxsort(L, &ta, 1, n);
254327  return 0;
255328}
256329
r242885r242886
266339  {"pack", pack},
267340  {"unpack", unpack},
268341  {"remove", tremove},
342  {"move", tmove},
269343  {"sort", sort},
270344  {NULL, NULL}
271345};
trunk/3rdparty/lua/src/ltm.c
r242885r242886
11/*
2** $Id: ltm.c,v 2.14.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: ltm.c,v 2.33 2014/11/21 12:15:57 roberto Exp $
33** Tag methods
44** See Copyright Notice in lua.h
55*/
66
7#define ltm_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <string.h>
914
10#define ltm_c
11#define LUA_CORE
12
1315#include "lua.h"
1416
17#include "ldebug.h"
18#include "ldo.h"
1519#include "lobject.h"
1620#include "lstate.h"
1721#include "lstring.h"
1822#include "ltable.h"
1923#include "ltm.h"
24#include "lvm.h"
2025
2126
2227static const char udatatypename[] = "userdata";
r242885r242886
2530  "no value",
2631  "nil", "boolean", udatatypename, "number",
2732  "string", "table", "function", udatatypename, "thread",
28  "proto", "upval"  /* these last two cases are used for tests only */
33  "proto" /* this last case is used for tests only */
2934};
3035
3136
r242885r242886
3338  static const char *const luaT_eventname[] = {  /* ORDER TM */
3439    "__index", "__newindex",
3540    "__gc", "__mode", "__len", "__eq",
36    "__add", "__sub", "__mul", "__div", "__mod",
37    "__pow", "__unm", "__lt", "__le",
41    "__add", "__sub", "__mul", "__mod", "__pow",
42    "__div", "__idiv",
43    "__band", "__bor", "__bxor", "__shl", "__shr",
44    "__unm", "__bnot", "__lt", "__le",
3845    "__concat", "__call"
3946  };
4047  int i;
4148  for (i=0; i<TM_N; i++) {
4249    G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
43    luaS_fix(G(L)->tmname[i]);  /* never collect these names */
50    luaC_fix(L, obj2gco(G(L)->tmname[i]));  /* never collect these names */
4451  }
4552}
4653
r242885r242886
6269
6370const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
6471  Table *mt;
65  switch (ttypenv(o)) {
72  switch (ttnov(o)) {
6673    case LUA_TTABLE:
6774      mt = hvalue(o)->metatable;
6875      break;
r242885r242886
7077      mt = uvalue(o)->metatable;
7178      break;
7279    default:
73      mt = G(L)->mt[ttypenv(o)];
80      mt = G(L)->mt[ttnov(o)];
7481  }
7582  return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject);
7683}
7784
85
86void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
87                  const TValue *p2, TValue *p3, int hasres) {
88  ptrdiff_t result = savestack(L, p3);
89  setobj2s(L, L->top++, f);  /* push function (assume EXTRA_STACK) */
90  setobj2s(L, L->top++, p1);  /* 1st argument */
91  setobj2s(L, L->top++, p2);  /* 2nd argument */
92  if (!hasres)  /* no result? 'p3' is third argument */
93    setobj2s(L, L->top++, p3);  /* 3rd argument */
94  /* metamethod may yield only when called from Lua code */
95  luaD_call(L, L->top - (4 - hasres), hasres, isLua(L->ci));
96  if (hasres) {  /* if has result, move it to its place */
97    p3 = restorestack(L, result);
98    setobjs2s(L, p3, --L->top);
99  }
100}
101
102
103int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2,
104                    StkId res, TMS event) {
105  const TValue *tm = luaT_gettmbyobj(L, p1, event);  /* try first operand */
106  if (ttisnil(tm))
107    tm = luaT_gettmbyobj(L, p2, event);  /* try second operand */
108  if (ttisnil(tm)) return 0;
109  luaT_callTM(L, tm, p1, p2, res, 1);
110  return 1;
111}
112
113
114void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
115                    StkId res, TMS event) {
116  if (!luaT_callbinTM(L, p1, p2, res, event)) {
117    switch (event) {
118      case TM_CONCAT:
119        luaG_concaterror(L, p1, p2);
120      case TM_BAND: case TM_BOR: case TM_BXOR:
121      case TM_SHL: case TM_SHR: case TM_BNOT: {
122        lua_Number dummy;
123        if (tonumber(p1, &dummy) && tonumber(p2, &dummy))
124          luaG_tointerror(L, p1, p2);
125        else
126          luaG_opinterror(L, p1, p2, "perform bitwise operation on");
127        /* else go through */
128      }
129      default:
130        luaG_opinterror(L, p1, p2, "perform arithmetic on");
131    }
132  }
133}
134
135
136int luaT_callorderTM (lua_State *L, const TValue *p1, const TValue *p2,
137                      TMS event) {
138  if (!luaT_callbinTM(L, p1, p2, L->top, event))
139    return -1;  /* no metamethod */
140  else
141    return !l_isfalse(L->top);
142}
143
trunk/3rdparty/lua/src/ltm.h
r242885r242886
11/*
2** $Id: ltm.h,v 2.11.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: ltm.h,v 2.21 2014/10/25 11:50:46 roberto Exp $
33** Tag methods
44** See Copyright Notice in lua.h
55*/
r242885r242886
1313
1414/*
1515* WARNING: if you change the order of this enumeration,
16* grep "ORDER TM"
16* grep "ORDER TM" and "ORDER OP"
1717*/
1818typedef enum {
1919  TM_INDEX,
r242885r242886
2121  TM_GC,
2222  TM_MODE,
2323  TM_LEN,
24  TM_EQ,  /* last tag method with `fast' access */
24  TM_EQ,  /* last tag method with fast access */
2525  TM_ADD,
2626  TM_SUB,
2727  TM_MUL,
28  TM_DIV,
2928  TM_MOD,
3029  TM_POW,
30  TM_DIV,
31  TM_IDIV,
32  TM_BAND,
33  TM_BOR,
34  TM_BXOR,
35  TM_SHL,
36  TM_SHR,
3137  TM_UNM,
38  TM_BNOT,
3239  TM_LT,
3340  TM_LE,
3441  TM_CONCAT,
r242885r242886
4451#define fasttm(l,et,e)   gfasttm(G(l), et, e)
4552
4653#define ttypename(x)   luaT_typenames_[(x) + 1]
47#define objtypename(x)   ttypename(ttypenv(x))
54#define objtypename(x)   ttypename(ttnov(x))
4855
4956LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS];
5057
r242885r242886
5461                                                       TMS event);
5562LUAI_FUNC void luaT_init (lua_State *L);
5663
64LUAI_FUNC void luaT_callTM (lua_State *L, const TValue *f, const TValue *p1,
65                            const TValue *p2, TValue *p3, int hasres);
66LUAI_FUNC int luaT_callbinTM (lua_State *L, const TValue *p1, const TValue *p2,
67                              StkId res, TMS event);
68LUAI_FUNC void luaT_trybinTM (lua_State *L, const TValue *p1, const TValue *p2,
69                              StkId res, TMS event);
70LUAI_FUNC int luaT_callorderTM (lua_State *L, const TValue *p1,
71                                const TValue *p2, TMS event);
72
73
74
5775#endif
trunk/3rdparty/lua/src/lua.c
r242885r242886
11/*
2** $Id: lua.c,v 1.206.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lua.c,v 1.222 2014/11/11 19:41:27 roberto Exp $
33** Lua stand-alone interpreter
44** See Copyright Notice in lua.h
55*/
66
7#define lua_c
78
9#include "lprefix.h"
10
11
812#include <signal.h>
913#include <stdio.h>
1014#include <stdlib.h>
1115#include <string.h>
1216
13#define lua_c
14
1517#include "lua.h"
1618
1719#include "lauxlib.h"
r242885r242886
3133#define LUA_MAXINPUT      512
3234#endif
3335
34#if !defined(LUA_INIT)
35#define LUA_INIT      "LUA_INIT"
36#if !defined(LUA_INIT_VAR)
37#define LUA_INIT_VAR      "LUA_INIT"
3638#endif
3739
38#define LUA_INITVERSION  \
39   LUA_INIT "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
40#define LUA_INITVARVERSION  \
41   LUA_INIT_VAR "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
4042
4143
4244/*
4345** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
4446** is, whether we're running lua interactively).
4547*/
46#if defined(LUA_USE_ISATTY)
48#if !defined(lua_stdin_is_tty)   /* { */
49
50#if defined(LUA_USE_POSIX)   /* { */
51
4752#include <unistd.h>
4853#define lua_stdin_is_tty()   isatty(0)
49#elif defined(LUA_WIN)
54
55#elif defined(LUA_USE_WINDOWS)   /* }{ */
56
5057#include <io.h>
51#include <stdio.h>
5258#define lua_stdin_is_tty()   _isatty(_fileno(stdin))
53#else
59
60#else            /* }{ */
61
62/* ISO C definition */
5463#define lua_stdin_is_tty()   1  /* assume stdin is a tty */
55#endif
5664
65#endif            /* } */
5766
67#endif            /* } */
68
69
5870/*
5971** lua_readline defines how to show a prompt and then read a line from
6072** the standard input.
6173** lua_saveline defines how to "save" a read line in a "history".
6274** lua_freeline defines how to free a line read by lua_readline.
6375*/
64#if defined(LUA_USE_READLINE)
76#if !defined(lua_readline)   /* { */
6577
66#include <stdio.h>
78#if defined(LUA_USE_READLINE)   /* { */
79
6780#include <readline/readline.h>
6881#include <readline/history.h>
6982#define lua_readline(L,b,p)   ((void)L, ((b)=readline(p)) != NULL)
r242885r242886
7285          add_history(lua_tostring(L, idx));  /* add it to history */
7386#define lua_freeline(L,b)   ((void)L, free(b))
7487
75#elif !defined(lua_readline)
88#else            /* }{ */
7689
7790#define lua_readline(L,b,p) \
7891        ((void)L, fputs(p, stdout), fflush(stdout),  /* show prompt */ \
r242885r242886
8093#define lua_saveline(L,idx)   { (void)L; (void)idx; }
8194#define lua_freeline(L,b)   { (void)L; (void)b; }
8295
83#endif
96#endif            /* } */
8497
98#endif            /* } */
8599
86100
87101
102
88103static lua_State *globalL = NULL;
89104
90105static const char *progname = LUA_PROGNAME;
91106
92107
93
108/*
109** Hook set by signal function to stop the interpreter.
110*/
94111static void lstop (lua_State *L, lua_Debug *ar) {
95112  (void)ar;  /* unused arg. */
96  lua_sethook(L, NULL, 0, 0);
113  lua_sethook(L, NULL, 0, 0);  /* reset hook */
97114  luaL_error(L, "interrupted!");
98115}
99116
100117
118/*
119** Function to be called at a C signal. Because a C signal cannot
120** just change a Lua state (as there is no proper synchronization),
121** this function only sets a hook that, when called, will stop the
122** interpreter.
123*/
101124static void laction (int i) {
102  signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
103                              terminate process (default action) */
125  signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
104126  lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
105127}
106128
107129
108130static void print_usage (const char *badoption) {
109  luai_writestringerror("%s: ", progname);
131  lua_writestringerror("%s: ", progname);
110132  if (badoption[1] == 'e' || badoption[1] == 'l')
111    luai_writestringerror("'%s' needs argument\n", badoption);
133    lua_writestringerror("'%s' needs argument\n", badoption);
112134  else
113    luai_writestringerror("unrecognized option '%s'\n", badoption);
114  luai_writestringerror(
135    lua_writestringerror("unrecognized option '%s'\n", badoption);
136  lua_writestringerror(
115137  "usage: %s [options] [script [args]]\n"
116138  "Available options are:\n"
117  "  -e stat  execute string " LUA_QL("stat") "\n"
118  "  -i       enter interactive mode after executing " LUA_QL("script") "\n"
119  "  -l name  require library " LUA_QL("name") "\n"
139  "  -e stat  execute string 'stat'\n"
140  "  -i       enter interactive mode after executing 'script'\n"
141  "  -l name  require library 'name'\n"
120142  "  -v       show version information\n"
121143  "  -E       ignore environment variables\n"
122144  "  --       stop handling options\n"
r242885r242886
126148}
127149
128150
151/*
152** Prints an error message, adding the program name in front of it
153** (if present)
154*/
129155static void l_message (const char *pname, const char *msg) {
130  if (pname) luai_writestringerror("%s: ", pname);
131  luai_writestringerror("%s\n", msg);
156  if (pname) lua_writestringerror("%s: ", pname);
157  lua_writestringerror("%s\n", msg);
132158}
133159
134160
161/*
162** Check whether 'status' is not OK and, if so, prints the error
163** message on the top of the stack. It assumes that the error object
164** is a string, as it was either generated by Lua or by 'msghandler'.
165*/
135166static int report (lua_State *L, int status) {
136  if (status != LUA_OK && !lua_isnil(L, -1)) {
167  if (status != LUA_OK) {
137168    const char *msg = lua_tostring(L, -1);
138    if (msg == NULL) msg = "(error object is not a string)";
139169    l_message(progname, msg);
140    lua_pop(L, 1);
141    /* force a complete garbage collection in case of errors */
142    lua_gc(L, LUA_GCCOLLECT, 0);
170    lua_pop(L, 1);  /* remove message */
143171  }
144172  return status;
145173}
146174
147175
148/* the next function is called unprotected, so it must avoid errors */
149static void finalreport (lua_State *L, int status) {
150  if (status != LUA_OK) {
151    const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1)
152                                                       : NULL;
153    if (msg == NULL) msg = "(error object is not a string)";
154    l_message(progname, msg);
155    lua_pop(L, 1);
156  }
157}
158
159
160static int traceback (lua_State *L) {
176/*
177** Message handler used to run all chunks
178*/
179static int msghandler (lua_State *L) {
161180  const char *msg = lua_tostring(L, 1);
162  if (msg)
163    luaL_traceback(L, L, msg, 1);
164  else if (!lua_isnoneornil(L, 1)) {  /* is there an error object? */
165    if (!luaL_callmeta(L, 1, "__tostring"))  /* try its 'tostring' metamethod */
166      lua_pushliteral(L, "(no error message)");
181  if (msg == NULL) {  /* is error object not a string? */
182    if (luaL_callmeta(L, 1, "__tostring") &&  /* does it have a metamethod */
183        lua_type(L, -1) == LUA_TSTRING)  /* that produces a string? */
184      return 1;  /* that is the message */
185    else
186      msg = lua_pushfstring(L, "(error object is a %s value)",
187                               luaL_typename(L, 1));
167188  }
168  return 1;
189  luaL_traceback(L, L, msg, 1);  /* append a standard traceback */
190  return 1;  /* return the traceback */
169191}
170192
171193
194/*
195** Interface to 'lua_pcall', which sets appropriate message function
196** and C-signal handler. Used to run all chunks.
197*/
172198static int docall (lua_State *L, int narg, int nres) {
173199  int status;
174200  int base = lua_gettop(L) - narg;  /* function index */
175  lua_pushcfunction(L, traceback);  /* push traceback function */
176  lua_insert(L, base);  /* put it under chunk and args */
201  lua_pushcfunction(L, msghandler);  /* push message handler */
202  lua_insert(L, base);  /* put it under function and args */
177203  globalL = L;  /* to be available to 'laction' */
178  signal(SIGINT, laction);
204  signal(SIGINT, laction);  /* set C-signal handler */
179205  status = lua_pcall(L, narg, nres, base);
180  signal(SIGINT, SIG_DFL);
181  lua_remove(L, base);  /* remove traceback function */
206  signal(SIGINT, SIG_DFL); /* reset C-signal handler */
207  lua_remove(L, base);  /* remove message handler from the stack */
182208  return status;
183209}
184210
185211
186212static void print_version (void) {
187  luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
188  luai_writeline();
213  lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
214  lua_writeline();
189215}
190216
191217
192static int getargs (lua_State *L, char **argv, int n) {
193  int narg;
194  int i;
195  int argc = 0;
196  while (argv[argc]) argc++;  /* count total number of arguments */
197  narg = argc - (n + 1);  /* number of arguments to the script */
198  luaL_checkstack(L, narg + 3, "too many arguments to script");
199  for (i=n+1; i < argc; i++)
218/*
219** Create the 'arg' table, which stores all arguments from the
220** command line ('argv'). It should be aligned so that, at index 0,
221** it has 'argv[script]', which is the script name. The arguments
222** to the script (everything after 'script') go to positive indices;
223** other arguments (before the script name) go to negative indices.
224** If there is no script name, assume interpreter's name as base.
225*/
226static void createargtable (lua_State *L, char **argv, int argc, int script) {
227  int i, narg;
228  if (script == argc) script = 0;  /* no script name? */
229  narg = argc - (script + 1);  /* number of positive indices */
230  lua_createtable(L, narg, script + 1);
231  for (i = 0; i < argc; i++) {
200232    lua_pushstring(L, argv[i]);
201  lua_createtable(L, narg, n + 1);
202  for (i=0; i < argc; i++) {
203    lua_pushstring(L, argv[i]);
204    lua_rawseti(L, -2, i - n);
233    lua_rawseti(L, -2, i - script);
205234  }
206  return narg;
235  lua_setglobal(L, "arg");
207236}
208237
209238
210static int dofile (lua_State *L, const char *name) {
211  int status = luaL_loadfile(L, name);
239static int dochunk (lua_State *L, int status) {
212240  if (status == LUA_OK) status = docall(L, 0, 0);
213241  return report(L, status);
214242}
215243
216244
245static int dofile (lua_State *L, const char *name) {
246  return dochunk(L, luaL_loadfile(L, name));
247}
248
249
217250static int dostring (lua_State *L, const char *s, const char *name) {
218  int status = luaL_loadbuffer(L, s, strlen(s), name);
219  if (status == LUA_OK) status = docall(L, 0, 0);
220  return report(L, status);
251  return dochunk(L, luaL_loadbuffer(L, s, strlen(s), name));
221252}
222253
223254
255/*
256** Calls 'require(name)' and stores the result in a global variable
257** with the given name.
258*/
224259static int dolibrary (lua_State *L, const char *name) {
225260  int status;
226261  lua_getglobal(L, "require");
r242885r242886
232267}
233268
234269
270/*
271** Returns the string to be used as a prompt by the interpreter.
272*/
235273static const char *get_prompt (lua_State *L, int firstline) {
236274  const char *p;
237275  lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
r242885r242886
244282#define EOFMARK      "<eof>"
245283#define marklen      (sizeof(EOFMARK)/sizeof(char) - 1)
246284
285
286/*
287** Check whether 'status' signals a syntax error and the error
288** message at the top of the stack ends with the above mark for
289** incomplete statements.
290*/
247291static int incomplete (lua_State *L, int status) {
248292  if (status == LUA_ERRSYNTAX) {
249293    size_t lmsg;
r242885r242886
257301}
258302
259303
304/*
305** Prompt the user, read a line, and push it into the Lua stack.
306*/
260307static int pushline (lua_State *L, int firstline) {
261308  char buffer[LUA_MAXINPUT];
262309  char *b = buffer;
263310  size_t l;
264311  const char *prmt = get_prompt(L, firstline);
265312  int readstatus = lua_readline(L, b, prmt);
266  lua_pop(L, 1);  /* remove result from 'get_prompt' */
267313  if (readstatus == 0)
268    return 0;  /* no input */
314    return 0;  /* no input (prompt will be popped by caller) */
315  lua_pop(L, 1);  /* remove prompt */
269316  l = strlen(b);
270317  if (l > 0 && b[l-1] == '\n')  /* line ends with newline? */
271318    b[l-1] = '\0';  /* remove it */
272  if (firstline && b[0] == '=')  /* first line starts with `=' ? */
273    lua_pushfstring(L, "return %s", b+1);  /* change it to `return' */
319  if (firstline && b[0] == '=')  /* for compatibility with 5.2, ... */
320    lua_pushfstring(L, "return %s", b + 1);  /* change '=' to 'return' */
274321  else
275322    lua_pushstring(L, b);
276323  lua_freeline(L, b);
r242885r242886
278325}
279326
280327
328/*
329** Try to compile line on the stack as 'return <line>'; on return, stack
330** has either compiled chunk or original line (if compilation failed).
331*/
332static int addreturn (lua_State *L) {
333  int status;
334  size_t len; const char *line;
335  lua_pushliteral(L, "return ");
336  lua_pushvalue(L, -2);  /* duplicate line */
337  lua_concat(L, 2);  /* new line is "return ..." */
338  line = lua_tolstring(L, -1, &len);
339  if ((status = luaL_loadbuffer(L, line, len, "=stdin")) == LUA_OK)
340    lua_remove(L, -3);  /* remove original line */
341  else
342    lua_pop(L, 2);  /* remove result from 'luaL_loadbuffer' and new line */
343  return status;
344}
345
346
347/*
348** Read multiple lines until a complete Lua statement
349*/
350static int multiline (lua_State *L) {
351  for (;;) {  /* repeat until gets a complete statement */
352    size_t len;
353    const char *line = lua_tolstring(L, 1, &len);  /* get what it has */
354    int status = luaL_loadbuffer(L, line, len, "=stdin");  /* try it */
355    if (!incomplete(L, status) || !pushline(L, 0))
356      return status;  /* cannot or should not try to add continuation line */
357    lua_pushliteral(L, "\n");  /* add newline... */
358    lua_insert(L, -2);  /* ...between the two lines */
359    lua_concat(L, 3);  /* join them */
360  }
361}
362
363
364/*
365** Read a line and try to load (compile) it first as an expression (by
366** adding "return " in front of it) and second as a statement. Return
367** the final status of load/call with the resulting function (if any)
368** in the top of the stack.
369*/
281370static int loadline (lua_State *L) {
282371  int status;
283372  lua_settop(L, 0);
284373  if (!pushline(L, 1))
285374    return -1;  /* no input */
286  for (;;) {  /* repeat until gets a complete line */
287    size_t l;
288    const char *line = lua_tolstring(L, 1, &l);
289    status = luaL_loadbuffer(L, line, l, "=stdin");
290    if (!incomplete(L, status)) break;  /* cannot try to add lines? */
291    if (!pushline(L, 0))  /* no more input? */
292      return -1;
293    lua_pushliteral(L, "\n");  /* add a new line... */
294    lua_insert(L, -2);  /* ...between the two lines */
295    lua_concat(L, 3);  /* join them */
296  }
297  lua_saveline(L, 1);
298  lua_remove(L, 1);  /* remove line */
375  if ((status = addreturn(L)) != LUA_OK)  /* 'return ...' did not work? */
376    status = multiline(L);  /* try as command, maybe with continuation lines */
377  lua_saveline(L, 1);  /* keep history */
378  lua_remove(L, 1);  /* remove line from the stack */
379  lua_assert(lua_gettop(L) == 1);
299380  return status;
300381}
301382
302383
303static void dotty (lua_State *L) {
384/*
385** Prints (calling the Lua 'print' function) any values on the stack
386*/
387static void l_print (lua_State *L) {
388  int n = lua_gettop(L);
389  if (n > 0) {  /* any result to be printed? */
390    luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
391    lua_getglobal(L, "print");
392    lua_insert(L, 1);
393    if (lua_pcall(L, n, 0, 0) != LUA_OK)
394      l_message(progname, lua_pushfstring(L, "error calling 'print' (%s)",
395                                             lua_tostring(L, -1)));
396  }
397}
398
399
400/*
401** Do the REPL: repeatedly read (load) a line, evaluate (call) it, and
402** print any results.
403*/
404static void doREPL (lua_State *L) {
304405  int status;
305406  const char *oldprogname = progname;
306  progname = NULL;
407  progname = NULL;  /* no 'progname' on errors in interactive mode */
307408  while ((status = loadline(L)) != -1) {
308    if (status == LUA_OK) status = docall(L, 0, LUA_MULTRET);
309    report(L, status);
310    if (status == LUA_OK && lua_gettop(L) > 0) {  /* any result to print? */
311      luaL_checkstack(L, LUA_MINSTACK, "too many results to print");
312      lua_getglobal(L, "print");
313      lua_insert(L, 1);
314      if (lua_pcall(L, lua_gettop(L)-1, 0, 0) != LUA_OK)
315        l_message(progname, lua_pushfstring(L,
316                               "error calling " LUA_QL("print") " (%s)",
317                               lua_tostring(L, -1)));
318    }
409    if (status == LUA_OK)
410      status = docall(L, 0, LUA_MULTRET);
411    if (status == LUA_OK) l_print(L);
412    else report(L, status);
319413  }
320414  lua_settop(L, 0);  /* clear stack */
321  luai_writeline();
415  lua_writeline();
322416  progname = oldprogname;
323417}
324418
325419
326static int handle_script (lua_State *L, char **argv, int n) {
420/*
421** Push on the stack the contents of table 'arg' from 1 to #arg
422*/
423static int pushargs (lua_State *L) {
424  int i, n;
425  if (lua_getglobal(L, "arg") != LUA_TTABLE)
426    luaL_error(L, "'arg' is not a table");
427  n = (int)luaL_len(L, -1);
428  luaL_checkstack(L, n + 3, "too many arguments to script");
429  for (i = 1; i <= n; i++)
430    lua_rawgeti(L, -i, i);
431  lua_remove(L, -i);  /* remove table from the stack */
432  return n;
433}
434
435
436static int handle_script (lua_State *L, char **argv) {
327437  int status;
328  const char *fname;
329  int narg = getargs(L, argv, n);  /* collect arguments */
330  lua_setglobal(L, "arg");
331  fname = argv[n];
332  if (strcmp(fname, "-") == 0 && strcmp(argv[n-1], "--") != 0)
438  const char *fname = argv[0];
439  if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
333440    fname = NULL;  /* stdin */
334441  status = luaL_loadfile(L, fname);
335  lua_insert(L, -(narg+1));
336  if (status == LUA_OK)
337    status = docall(L, narg, LUA_MULTRET);
338  else
339    lua_pop(L, narg);
442  if (status == LUA_OK) {
443    int n = pushargs(L);  /* push arguments to script */
444    status = docall(L, n, LUA_MULTRET);
445  }
340446  return report(L, status);
341447}
342448
343449
344/* check that argument has no extra characters at the end */
345#define noextrachars(x)      {if ((x)[2] != '\0') return -1;}
346450
451/* bits of various argument indicators in 'args' */
452#define has_error   1   /* bad option */
453#define has_i      2   /* -i */
454#define has_v      4   /* -v */
455#define has_e      8   /* -e */
456#define has_E      16   /* -E */
347457
348/* indices of various argument indicators in array args */
349#define has_i      0   /* -i */
350#define has_v      1   /* -v */
351#define has_e      2   /* -e */
352#define has_E      3   /* -E */
353
354#define num_has      4   /* number of 'has_*' */
355
356
357static int collectargs (char **argv, int *args) {
458/*
459** Traverses all arguments from 'argv', returning a mask with those
460** needed before running any Lua code (or an error code if it finds
461** any invalid argument). 'first' returns the first not-handled argument
462** (either the script name or a bad argument in case of error).
463*/
464static int collectargs (char **argv, int *first) {
465  int args = 0;
358466  int i;
359467  for (i = 1; argv[i] != NULL; i++) {
468    *first = i;
360469    if (argv[i][0] != '-')  /* not an option? */
361        return i;
362    switch (argv[i][1]) {  /* option */
363      case '-':
364        noextrachars(argv[i]);
365        return (argv[i+1] != NULL ? i+1 : 0);
366      case '\0':
367        return i;
470        return args;  /* stop handling options */
471    switch (argv[i][1]) {  /* else check option */
472      case '-':  /* '--' */
473        if (argv[i][2] != '\0')  /* extra characters after '--'? */
474          return has_error;  /* invalid option */
475        *first = i + 1;
476        return args;
477      case '\0':  /* '-' */
478        return args;  /* script "name" is '-' */
368479      case 'E':
369        args[has_E] = 1;
480        if (argv[i][2] != '\0')  /* extra characters after 1st? */
481          return has_error;  /* invalid option */
482        args |= has_E;
370483        break;
371484      case 'i':
372        noextrachars(argv[i]);
373        args[has_i] = 1;  /* go through */
485        args |= has_i;  /* goes through  (-i implies -v) */
374486      case 'v':
375        noextrachars(argv[i]);
376        args[has_v] = 1;
487        if (argv[i][2] != '\0')  /* extra characters after 1st? */
488          return has_error;  /* invalid option */
489        args |= has_v;
377490        break;
378491      case 'e':
379        args[has_e] = 1;  /* go through */
492        args |= has_e;  /* go through */
380493      case 'l':  /* both options need an argument */
381494        if (argv[i][2] == '\0') {  /* no concatenated argument? */
382495          i++;  /* try next 'argv' */
383496          if (argv[i] == NULL || argv[i][0] == '-')
384            return -(i - 1);  /* no next argument or it is another option */
497            return has_error;  /* no next argument or it is another option */
385498        }
386499        break;
387      default:  /* invalid option; return its index... */
388        return -i;  /* ...as a negative value */
500      default:  /* invalid option */
501        return has_error;
389502    }
390503  }
391  return 0;
504  *first = i;  /* no script name */
505  return args;
392506}
393507
394508
509/*
510** Processes options 'e' and 'l', which involve running Lua code.
511** Returns 0 if some code raises an error.
512*/
395513static int runargs (lua_State *L, char **argv, int n) {
396514  int i;
397515  for (i = 1; i < n; i++) {
398    lua_assert(argv[i][0] == '-');
399    switch (argv[i][1]) {  /* option */
400      case 'e': {
401        const char *chunk = argv[i] + 2;
402        if (*chunk == '\0') chunk = argv[++i];
403        lua_assert(chunk != NULL);
404        if (dostring(L, chunk, "=(command line)") != LUA_OK)
405          return 0;
406        break;
407      }
408      case 'l': {
409        const char *filename = argv[i] + 2;
410        if (*filename == '\0') filename = argv[++i];
411        lua_assert(filename != NULL);
412        if (dolibrary(L, filename) != LUA_OK)
413          return 0;  /* stop if file fails */
414        break;
415      }
416      default: break;
516    int status;
517    int option = argv[i][1];
518    lua_assert(argv[i][0] == '-');  /* already checked */
519    if (option == 'e' || option == 'l') {
520      const char *extra = argv[i] + 2;  /* both options need an argument */
521      if (*extra == '\0') extra = argv[++i];
522      lua_assert(extra != NULL);
523      if (option == 'e')
524        status = dostring(L, extra, "=(command line)");
525      else
526        status = dolibrary(L, extra);
527      if (status != LUA_OK) return 0;
417528    }
418529  }
419530  return 1;
r242885r242886
421532
422533
423534static int handle_luainit (lua_State *L) {
424  const char *name = "=" LUA_INITVERSION;
535  const char *name = "=" LUA_INITVARVERSION;
425536  const char *init = getenv(name + 1);
426537  if (init == NULL) {
427    name = "=" LUA_INIT;
538    name = "=" LUA_INIT_VAR;
428539    init = getenv(name + 1);  /* try alternative name */
429540  }
430541  if (init == NULL) return LUA_OK;
r242885r242886
435546}
436547
437548
549/*
550** Main body of stand-alone interpreter (to be called in protected mode).
551** Reads the options and handles them all.
552*/
438553static int pmain (lua_State *L) {
439554  int argc = (int)lua_tointeger(L, 1);
440555  char **argv = (char **)lua_touserdata(L, 2);
441556  int script;
442  int args[num_has];
443  args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0;
557  int args = collectargs(argv, &script);
558  luaL_checkversion(L);  /* check that interpreter has correct version */
444559  if (argv[0] && argv[0][0]) progname = argv[0];
445  script = collectargs(argv, args);
446  if (script < 0) {  /* invalid arg? */
447    print_usage(argv[-script]);
560  if (args == has_error) {  /* bad arg? */
561    print_usage(argv[script]);  /* 'script' has index of bad arg. */
448562    return 0;
449563  }
450  if (args[has_v]) print_version();
451  if (args[has_E]) {  /* option '-E'? */
564  if (args & has_v)  /* option '-v'? */
565    print_version();
566  if (args & has_E) {  /* option '-E'? */
452567    lua_pushboolean(L, 1);  /* signal for libraries to ignore env. vars. */
453568    lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
454569  }
455  /* open standard libraries */
456  luaL_checkversion(L);
457  lua_gc(L, LUA_GCSTOP, 0);  /* stop collector during initialization */
458  luaL_openlibs(L);  /* open libraries */
459  lua_gc(L, LUA_GCRESTART, 0);
460  if (!args[has_E] && handle_luainit(L) != LUA_OK)
461    return 0;  /* error running LUA_INIT */
462  /* execute arguments -e and -l */
463  if (!runargs(L, argv, (script > 0) ? script : argc)) return 0;
464  /* execute main script (if there is one) */
465  if (script && handle_script(L, argv, script) != LUA_OK) return 0;
466  if (args[has_i])  /* -i option? */
467    dotty(L);
468  else if (script == 0 && !args[has_e] && !args[has_v]) {  /* no arguments? */
469    if (lua_stdin_is_tty()) {
570  luaL_openlibs(L);  /* open standard libraries */
571  createargtable(L, argv, argc, script);  /* create table 'arg' */
572  if (!(args & has_E)) {  /* no option '-E'? */
573    if (handle_luainit(L) != LUA_OK)  /* run LUA_INIT */
574      return 0;  /* error running LUA_INIT */
575  }
576  if (!runargs(L, argv, script))  /* execute arguments -e and -l */
577    return 0;  /* something failed */
578  if (script < argc &&  /* execute main script (if there is one) */
579      handle_script(L, argv + script) != LUA_OK)
580    return 0;
581  if (args & has_i)  /* -i option? */
582    doREPL(L);  /* do read-eval-print loop */
583  else if (script == argc && !(args & (has_e | has_v))) {  /* no arguments? */
584    if (lua_stdin_is_tty()) {  /* running in interactive mode? */
470585      print_version();
471      dotty(L);
586      doREPL(L);  /* do read-eval-print loop */
472587    }
473588    else dofile(L, NULL);  /* executes stdin as a file */
474589  }
r242885r242886
484599    l_message(argv[0], "cannot create state: not enough memory");
485600    return EXIT_FAILURE;
486601  }
487  /* call 'pmain' in protected mode */
488  lua_pushcfunction(L, &pmain);
602  lua_pushcfunction(L, &pmain);  /* to call 'pmain' in protected mode */
489603  lua_pushinteger(L, argc);  /* 1st argument */
490604  lua_pushlightuserdata(L, argv); /* 2nd argument */
491  status = lua_pcall(L, 2, 1, 0);
605  status = lua_pcall(L, 2, 1, 0);  /* do the call */
492606  result = lua_toboolean(L, -1);  /* get result */
493  finalreport(L, status);
607  report(L, status);
494608  lua_close(L);
495609  return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
496610}
trunk/3rdparty/lua/src/lua.h
r242885r242886
11/*
2** $Id: lua.h,v 1.285.1.2 2013/11/11 12:09:16 roberto Exp $
2** $Id: lua.h,v 1.325 2014/12/26 17:24:27 roberto Exp $
33** Lua - A Scripting Language
44** Lua.org, PUC-Rio, Brazil (http://www.lua.org)
55** See Copyright Notice at the end of this file
r242885r242886
1717
1818
1919#define LUA_VERSION_MAJOR   "5"
20#define LUA_VERSION_MINOR   "2"
21#define LUA_VERSION_NUM      502
22#define LUA_VERSION_RELEASE   "3"
20#define LUA_VERSION_MINOR   "3"
21#define LUA_VERSION_NUM      503
22#define LUA_VERSION_RELEASE   "0"
2323
2424#define LUA_VERSION   "Lua " LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
2525#define LUA_RELEASE   LUA_VERSION "." LUA_VERSION_RELEASE
26#define LUA_COPYRIGHT   LUA_RELEASE "  Copyright (C) 1994-2013 Lua.org, PUC-Rio"
26#define LUA_COPYRIGHT   LUA_RELEASE "  Copyright (C) 1994-2015 Lua.org, PUC-Rio"
2727#define LUA_AUTHORS   "R. Ierusalimschy, L. H. de Figueiredo, W. Celes"
2828
2929
3030/* mark for precompiled code ('<esc>Lua') */
31#define LUA_SIGNATURE   "\033Lua"
31#define LUA_SIGNATURE   "\x1bLua"
3232
3333/* option for multiple returns in 'lua_pcall' and 'lua_call' */
3434#define LUA_MULTRET   (-1)
r242885r242886
5353
5454typedef struct lua_State lua_State;
5555
56typedef int (*lua_CFunction) (lua_State *L);
5756
58
5957/*
60** functions that read/write blocks when loading/dumping Lua chunks
61*/
62typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
63
64typedef int (*lua_Writer) (lua_State *L, const void* p, size_t sz, void* ud);
65
66
67/*
68** prototype for memory-allocation functions
69*/
70typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
71
72
73/*
7458** basic types
7559*/
7660#define LUA_TNONE      (-1)
r242885r242886
10993/* unsigned integer type */
11094typedef LUA_UNSIGNED lua_Unsigned;
11195
96/* type for continuation-function contexts */
97typedef LUA_KCONTEXT lua_KContext;
11298
11399
114100/*
101** Type for C functions registered with Lua
102*/
103typedef int (*lua_CFunction) (lua_State *L);
104
105/*
106** Type for continuation functions
107*/
108typedef int (*lua_KFunction) (lua_State *L, int status, lua_KContext ctx);
109
110
111/*
112** Type for functions that read/write blocks when loading/dumping Lua chunks
113*/
114typedef const char * (*lua_Reader) (lua_State *L, void *ud, size_t *sz);
115
116typedef int (*lua_Writer) (lua_State *L, const void *p, size_t sz, void *ud);
117
118
119/*
120** Type for memory-allocation functions
121*/
122typedef void * (*lua_Alloc) (void *ud, void *ptr, size_t osize, size_t nsize);
123
124
125
126/*
115127** generic extra include file
116128*/
117129#if defined(LUA_USER_H)
r242885r242886
145157LUA_API int   (lua_gettop) (lua_State *L);
146158LUA_API void  (lua_settop) (lua_State *L, int idx);
147159LUA_API void  (lua_pushvalue) (lua_State *L, int idx);
148LUA_API void  (lua_remove) (lua_State *L, int idx);
149LUA_API void  (lua_insert) (lua_State *L, int idx);
150LUA_API void  (lua_replace) (lua_State *L, int idx);
160LUA_API void  (lua_rotate) (lua_State *L, int idx, int n);
151161LUA_API void  (lua_copy) (lua_State *L, int fromidx, int toidx);
152LUA_API int   (lua_checkstack) (lua_State *L, int sz);
162LUA_API int   (lua_checkstack) (lua_State *L, int n);
153163
154164LUA_API void  (lua_xmove) (lua_State *from, lua_State *to, int n);
155165
r242885r242886
161171LUA_API int             (lua_isnumber) (lua_State *L, int idx);
162172LUA_API int             (lua_isstring) (lua_State *L, int idx);
163173LUA_API int             (lua_iscfunction) (lua_State *L, int idx);
174LUA_API int             (lua_isinteger) (lua_State *L, int idx);
164175LUA_API int             (lua_isuserdata) (lua_State *L, int idx);
165176LUA_API int             (lua_type) (lua_State *L, int idx);
166177LUA_API const char     *(lua_typename) (lua_State *L, int tp);
167178
168179LUA_API lua_Number      (lua_tonumberx) (lua_State *L, int idx, int *isnum);
169180LUA_API lua_Integer     (lua_tointegerx) (lua_State *L, int idx, int *isnum);
170LUA_API lua_Unsigned    (lua_tounsignedx) (lua_State *L, int idx, int *isnum);
171181LUA_API int             (lua_toboolean) (lua_State *L, int idx);
172182LUA_API const char     *(lua_tolstring) (lua_State *L, int idx, size_t *len);
173183LUA_API size_t          (lua_rawlen) (lua_State *L, int idx);
r242885r242886
181191** Comparison and arithmetic functions
182192*/
183193
184#define LUA_OPADD   0   /* ORDER TM */
194#define LUA_OPADD   0   /* ORDER TM, ORDER OP */
185195#define LUA_OPSUB   1
186196#define LUA_OPMUL   2
187#define LUA_OPDIV   3
188#define LUA_OPMOD   4
189#define LUA_OPPOW   5
190#define LUA_OPUNM   6
197#define LUA_OPMOD   3
198#define LUA_OPPOW   4
199#define LUA_OPDIV   5
200#define LUA_OPIDIV   6
201#define LUA_OPBAND   7
202#define LUA_OPBOR   8
203#define LUA_OPBXOR   9
204#define LUA_OPSHL   10
205#define LUA_OPSHR   11
206#define LUA_OPUNM   12
207#define LUA_OPBNOT   13
191208
192209LUA_API void  (lua_arith) (lua_State *L, int op);
193210
r242885r242886
205222LUA_API void        (lua_pushnil) (lua_State *L);
206223LUA_API void        (lua_pushnumber) (lua_State *L, lua_Number n);
207224LUA_API void        (lua_pushinteger) (lua_State *L, lua_Integer n);
208LUA_API void        (lua_pushunsigned) (lua_State *L, lua_Unsigned n);
209LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t l);
225LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len);
210226LUA_API const char *(lua_pushstring) (lua_State *L, const char *s);
211227LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,
212228                                                      va_list argp);
r242885r242886
220236/*
221237** get functions (Lua -> stack)
222238*/
223LUA_API void  (lua_getglobal) (lua_State *L, const char *var);
224LUA_API void  (lua_gettable) (lua_State *L, int idx);
225LUA_API void  (lua_getfield) (lua_State *L, int idx, const char *k);
226LUA_API void  (lua_rawget) (lua_State *L, int idx);
227LUA_API void  (lua_rawgeti) (lua_State *L, int idx, int n);
228LUA_API void  (lua_rawgetp) (lua_State *L, int idx, const void *p);
239LUA_API int (lua_getglobal) (lua_State *L, const char *name);
240LUA_API int (lua_gettable) (lua_State *L, int idx);
241LUA_API int (lua_getfield) (lua_State *L, int idx, const char *k);
242LUA_API int (lua_geti) (lua_State *L, int idx, lua_Integer n);
243LUA_API int (lua_rawget) (lua_State *L, int idx);
244LUA_API int (lua_rawgeti) (lua_State *L, int idx, lua_Integer n);
245LUA_API int (lua_rawgetp) (lua_State *L, int idx, const void *p);
246
229247LUA_API void  (lua_createtable) (lua_State *L, int narr, int nrec);
230248LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);
231249LUA_API int   (lua_getmetatable) (lua_State *L, int objindex);
232LUA_API void  (lua_getuservalue) (lua_State *L, int idx);
250LUA_API int  (lua_getuservalue) (lua_State *L, int idx);
233251
234252
235253/*
236254** set functions (stack -> Lua)
237255*/
238LUA_API void  (lua_setglobal) (lua_State *L, const char *var);
256LUA_API void  (lua_setglobal) (lua_State *L, const char *name);
239257LUA_API void  (lua_settable) (lua_State *L, int idx);
240258LUA_API void  (lua_setfield) (lua_State *L, int idx, const char *k);
259LUA_API void  (lua_seti) (lua_State *L, int idx, lua_Integer n);
241260LUA_API void  (lua_rawset) (lua_State *L, int idx);
242LUA_API void  (lua_rawseti) (lua_State *L, int idx, int n);
261LUA_API void  (lua_rawseti) (lua_State *L, int idx, lua_Integer n);
243262LUA_API void  (lua_rawsetp) (lua_State *L, int idx, const void *p);
244263LUA_API int   (lua_setmetatable) (lua_State *L, int objindex);
245264LUA_API void  (lua_setuservalue) (lua_State *L, int idx);
r242885r242886
248267/*
249268** 'load' and 'call' functions (load and run Lua code)
250269*/
251LUA_API void  (lua_callk) (lua_State *L, int nargs, int nresults, int ctx,
252                           lua_CFunction k);
270LUA_API void  (lua_callk) (lua_State *L, int nargs, int nresults,
271                           lua_KContext ctx, lua_KFunction k);
253272#define lua_call(L,n,r)      lua_callk(L, (n), (r), 0, NULL)
254273
255LUA_API int   (lua_getctx) (lua_State *L, int *ctx);
256
257274LUA_API int   (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
258                            int ctx, lua_CFunction k);
275                            lua_KContext ctx, lua_KFunction k);
259276#define lua_pcall(L,n,r,f)   lua_pcallk(L, (n), (r), (f), 0, NULL)
260277
261278LUA_API int   (lua_load) (lua_State *L, lua_Reader reader, void *dt,
262                                        const char *chunkname,
263                                        const char *mode);
279                          const char *chunkname, const char *mode);
264280
265LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data);
281LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);
266282
267283
268284/*
269285** coroutine functions
270286*/
271LUA_API int  (lua_yieldk) (lua_State *L, int nresults, int ctx,
272                           lua_CFunction k);
287LUA_API int  (lua_yieldk)     (lua_State *L, int nresults, lua_KContext ctx,
288                               lua_KFunction k);
289LUA_API int  (lua_resume)     (lua_State *L, lua_State *from, int narg);
290LUA_API int  (lua_status)     (lua_State *L);
291LUA_API int (lua_isyieldable) (lua_State *L);
292
273293#define lua_yield(L,n)      lua_yieldk(L, (n), 0, NULL)
274LUA_API int  (lua_resume) (lua_State *L, lua_State *from, int narg);
275LUA_API int  (lua_status) (lua_State *L);
276294
295
277296/*
278297** garbage-collection function and options
279298*/
r242885r242886
286305#define LUA_GCSTEP      5
287306#define LUA_GCSETPAUSE      6
288307#define LUA_GCSETSTEPMUL   7
289#define LUA_GCSETMAJORINC   8
290308#define LUA_GCISRUNNING      9
291#define LUA_GCGEN      10
292#define LUA_GCINC      11
293309
294310LUA_API int (lua_gc) (lua_State *L, int what, int data);
295311
r242885r242886
305321LUA_API void  (lua_concat) (lua_State *L, int n);
306322LUA_API void  (lua_len)    (lua_State *L, int idx);
307323
324LUA_API size_t   (lua_stringtonumber) (lua_State *L, const char *s);
325
308326LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
309327LUA_API void      (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
310328
311329
312330
313331/*
314** ===============================================================
332** {==============================================================
315333** some useful macros
316334** ===============================================================
317335*/
318336
319#define lua_tonumber(L,i)   lua_tonumberx(L,i,NULL)
320#define lua_tointeger(L,i)   lua_tointegerx(L,i,NULL)
321#define lua_tounsigned(L,i)   lua_tounsignedx(L,i,NULL)
337#define lua_getextraspace(L)   ((void *)((char *)(L) - LUA_EXTRASPACE))
322338
339#define lua_tonumber(L,i)   lua_tonumberx(L,(i),NULL)
340#define lua_tointeger(L,i)   lua_tointegerx(L,(i),NULL)
341
323342#define lua_pop(L,n)      lua_settop(L, -(n)-1)
324343
325344#define lua_newtable(L)      lua_createtable(L, 0, 0)
r242885r242886
346365#define lua_tostring(L,i)   lua_tolstring(L, (i), NULL)
347366
348367
368#define lua_insert(L,idx)   lua_rotate(L, (idx), 1)
349369
370#define lua_remove(L,idx)   (lua_rotate(L, (idx), -1), lua_pop(L, 1))
371
372#define lua_replace(L,idx)   (lua_copy(L, -1, (idx)), lua_pop(L, 1))
373
374/* }============================================================== */
375
376
350377/*
378** {==============================================================
379** compatibility macros for unsigned conversions
380** ===============================================================
381*/
382#if defined(LUA_COMPAT_APIINTCASTS)
383
384#define lua_pushunsigned(L,n)   lua_pushinteger(L, (lua_Integer)(n))
385#define lua_tounsignedx(L,i,is)   ((lua_Unsigned)lua_tointegerx(L,i,is))
386#define lua_tounsigned(L,i)   lua_tounsignedx(L,(i),NULL)
387
388#endif
389/* }============================================================== */
390
391/*
351392** {======================================================================
352393** Debug API
353394** =======================================================================
r242885r242886
390431LUA_API void  (lua_upvaluejoin) (lua_State *L, int fidx1, int n1,
391432                                               int fidx2, int n2);
392433
393LUA_API int (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);
434LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);
394435LUA_API lua_Hook (lua_gethook) (lua_State *L);
395436LUA_API int (lua_gethookmask) (lua_State *L);
396437LUA_API int (lua_gethookcount) (lua_State *L);
r242885r242886
418459
419460
420461/******************************************************************************
421* Copyright (C) 1994-2013 Lua.org, PUC-Rio.
462* Copyright (C) 1994-2015 Lua.org, PUC-Rio.
422463*
423464* Permission is hereby granted, free of charge, to any person obtaining
424465* a copy of this software and associated documentation files (the
trunk/3rdparty/lua/src/luac.c
r242885r242886
11/*
2** $Id: luac.c,v 1.69 2011/11/29 17:46:33 lhf Exp $
3** Lua compiler (saves bytecodes to files; also list bytecodes)
2** $Id: luac.c,v 1.72 2015/01/06 03:09:13 lhf Exp $
3** Lua compiler (saves bytecodes to files; also lists bytecodes)
44** See Copyright Notice in lua.h
55*/
66
7#define luac_c
8#define LUA_CORE
9
10#include "lprefix.h"
11
12#include <ctype.h>
713#include <errno.h>
814#include <stdio.h>
915#include <stdlib.h>
1016#include <string.h>
1117
12#define luac_c
13#define LUA_CORE
14
1518#include "lua.h"
1619#include "lauxlib.h"
1720
r242885r242886
4750static void usage(const char* message)
4851{
4952 if (*message=='-')
50  fprintf(stderr,"%s: unrecognized option " LUA_QS "\n",progname,message);
53  fprintf(stderr,"%s: unrecognized option '%s'\n",progname,message);
5154 else
5255  fprintf(stderr,"%s: %s\n",progname,message);
5356 fprintf(stderr,
5457  "usage: %s [options] [filenames]\n"
5558  "Available options are:\n"
5659  "  -l       list (use -l -l for full listing)\n"
57  "  -o name  output to file " LUA_QL("name") " (default is \"%s\")\n"
60  "  -o name  output to file 'name' (default is \"%s\")\n"
5861  "  -p       parse only\n"
5962  "  -s       strip debug information\n"
6063  "  -v       show version information\n"
r242885r242886
8992  {
9093   output=argv[++i];
9194   if (output==NULL || *output==0 || (*output=='-' && output[1]!=0))
92    usage(LUA_QL("-o") " needs argument");
95    usage("'-o' needs argument");
9396   if (IS("-")) output=NULL;
9497  }
9598  else if (IS("-p"))         /* parse only */
r242885r242886
203206}
204207
205208/*
206** $Id: print.c,v 1.69 2013/07/04 01:03:46 lhf Exp $
209** $Id: print.c,v 1.76 2015/01/05 16:12:50 lhf Exp $
207210** print bytecodes
208211** See Copyright Notice in lua.h
209212*/
r242885r242886
223226static void PrintString(const TString* ts)
224227{
225228 const char* s=getstr(ts);
226 size_t i,n=ts->tsv.len;
229 size_t i,n=ts->len;
227230 printf("%c",'"');
228231 for (i=0; i<n; i++)
229232 {
r242885r242886
251254static void PrintConstant(const Proto* f, int i)
252255{
253256 const TValue* o=&f->k[i];
254 switch (ttypenv(o))
257 switch (ttype(o))
255258 {
256259  case LUA_TNIL:
257260   printf("nil");
r242885r242886
259262  case LUA_TBOOLEAN:
260263   printf(bvalue(o) ? "true" : "false");
261264   break;
262  case LUA_TNUMBER:
263   printf(LUA_NUMBER_FMT,nvalue(o));
265  case LUA_TNUMFLT:
266   {
267   char buff[100];
268   sprintf(buff,LUA_NUMBER_FMT,fltvalue(o));
269   printf("%s",buff);
270   if (buff[strspn(buff,"-0123456789")]=='\0') printf(".0");
264271   break;
265  case LUA_TSTRING:
266   PrintString(rawtsvalue(o));
272   }
273  case LUA_TNUMINT:
274   printf(LUA_INTEGER_FMT,ivalue(o));
267275   break;
276  case LUA_TSHRSTR: case LUA_TLNGSTR:
277   PrintString(tsvalue(o));
278   break;
268279  default:            /* cannot happen */
269280   printf("? type=%d",ttype(o));
270281   break;
r242885r242886
337348   case OP_ADD:
338349   case OP_SUB:
339350   case OP_MUL:
351   case OP_POW:
340352   case OP_DIV:
341   case OP_POW:
353   case OP_IDIV:
354   case OP_BAND:
355   case OP_BOR:
356   case OP_BXOR:
357   case OP_SHL:
358   case OP_SHR:
342359   case OP_EQ:
343360   case OP_LT:
344361   case OP_LE:
trunk/3rdparty/lua/src/luaconf.h
r242885r242886
11/*
2** $Id: luaconf.h,v 1.176.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: luaconf.h,v 1.238 2014/12/29 13:27:55 roberto Exp $
33** Configuration file for Lua
44** See Copyright Notice in lua.h
55*/
66
77
8#ifndef lconfig_h
9#define lconfig_h
8#ifndef luaconf_h
9#define luaconf_h
1010
1111#include <limits.h>
1212#include <stddef.h>
1313
1414
1515/*
16** ==================================================================
16** ===================================================================
1717** Search for "@@" to find all configurable definitions.
1818** ===================================================================
1919*/
2020
2121
2222/*
23@@ LUA_ANSI controls the use of non-ansi features.
24** CHANGE it (define it) if you want Lua to avoid the use of any
25** non-ansi feature or library.
23** {====================================================================
24** System Configuration: macros to adapt (if needed) Lua to some
25** particular platform, for instance compiling it with 32-bit numbers or
26** restricting it to C89.
27** =====================================================================
2628*/
27#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__)
28#define LUA_ANSI
29#endif
3029
30/*
31@@ LUA_32BITS enables Lua with 32-bit integers and 32-bit floats. You
32** can also define LUA_32BITS in the make file, but changing here you
33** ensure that all software connected to Lua will be compiled with the
34** same configuration.
35*/
36/* #define LUA_32BITS */
3137
32#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE)
33#define LUA_WIN      /* enable goodies for regular Windows platforms */
38
39/*
40@@ LUA_USE_C89 controls the use of non-ISO-C89 features.
41** Define it if you want Lua to avoid the use of a few C99 features
42** or Windows-specific features on Windows.
43*/
44/* #define LUA_USE_C89 */
45
46
47/*
48** By default, Lua on Windows use (some) specific Windows features
49*/
50#if !defined(LUA_USE_C89) && defined(_WIN32) && !defined(_WIN32_WCE)
51#define LUA_USE_WINDOWS  /* enable goodies for regular Windows */
3452#endif
3553
36#if defined(LUA_WIN)
37#define LUA_DL_DLL
38#define LUA_USE_AFORMAT      /* assume 'printf' handles 'aA' specifiers */
54
55#if defined(LUA_USE_WINDOWS)
56#define LUA_DL_DLL   /* enable support for DLL */
57#define LUA_USE_C89   /* broadly, Windows is C89 */
3958#endif
4059
4160
42
4361#if defined(LUA_USE_LINUX)
4462#define LUA_USE_POSIX
4563#define LUA_USE_DLOPEN      /* needs an extra library: -ldl */
4664#define LUA_USE_READLINE   /* needs some extra libraries */
47#define LUA_USE_STRTODHEX   /* assume 'strtod' handles hex formats */
48#define LUA_USE_AFORMAT      /* assume 'printf' handles 'aA' specifiers */
49#define LUA_USE_LONGLONG   /* assume support for long long */
5065#endif
5166
67
5268#if defined(LUA_USE_MACOSX)
5369#define LUA_USE_POSIX
54#define LUA_USE_DLOPEN      /* does not need -ldl */
70#define LUA_USE_DLOPEN      /* MacOS does not need -ldl */
5571#define LUA_USE_READLINE   /* needs an extra library: -lreadline */
56#define LUA_USE_STRTODHEX   /* assume 'strtod' handles hex formats */
57#define LUA_USE_AFORMAT      /* assume 'printf' handles 'aA' specifiers */
58#define LUA_USE_LONGLONG   /* assume support for long long */
5972#endif
6073
6174
75/*
76@@ LUA_C89_NUMBERS ensures that Lua uses the largest types available for
77** C89 ('long' and 'double'); Windows always has '__int64', so it does
78** not need to use this case.
79*/
80#if defined(LUA_USE_C89) && !defined(LUA_USE_WINDOWS)
81#define LUA_C89_NUMBERS
82#endif
6283
84
85
6386/*
64@@ LUA_USE_POSIX includes all functionality listed as X/Open System
65@* Interfaces Extension (XSI).
66** CHANGE it (define it) if your system is XSI compatible.
87@@ LUAI_BITSINT defines the (minimum) number of bits in an 'int'.
6788*/
68#if defined(LUA_USE_POSIX)
69#define LUA_USE_MKSTEMP
70#define LUA_USE_ISATTY
71#define LUA_USE_POPEN
72#define LUA_USE_ULONGJMP
73#define LUA_USE_GMTIME_R
89/* avoid undefined shifts */
90#if ((INT_MAX >> 15) >> 15) >= 1
91#define LUAI_BITSINT   32
92#else
93/* 'int' always must have at least 16 bits */
94#define LUAI_BITSINT   16
7495#endif
7596
7697
98/*
99@@ LUA_INT_INT / LUA_INT_LONG / LUA_INT_LONGLONG defines the type for
100** Lua integers.
101@@ LUA_REAL_FLOAT / LUA_REAL_DOUBLE / LUA_REAL_LONGDOUBLE defines
102** the type for Lua floats.
103** Lua should work fine with any mix of these options (if supported
104** by your C compiler). The usual configurations are 64-bit integers
105** and 'double' (the default), 32-bit integers and 'float' (for
106** restricted platforms), and 'long'/'double' (for C compilers not
107** compliant with C99, which may not have support for 'long long').
108*/
77109
110#if defined(LUA_32BITS)      /* { */
78111/*
112** 32-bit integers and 'float'
113*/
114#if LUAI_BITSINT >= 32  /* use 'int' if big enough */
115#define LUA_INT_INT
116#else  /* otherwise use 'long' */
117#define LUA_INT_LONG
118#endif
119#define LUA_REAL_FLOAT
120
121#elif defined(LUA_C89_NUMBERS)   /* }{ */
122/*
123** largest types available for C89 ('long' and 'double')
124*/
125#define LUA_INT_LONG
126#define LUA_REAL_DOUBLE
127
128#else            /* }{ */
129/*
130** default configuration for 64-bit Lua ('long long' and 'double')
131*/
132#define LUA_INT_LONGLONG
133#define LUA_REAL_DOUBLE
134
135#endif                        /* } */
136
137/* }================================================================== */
138
139
140
141
142/*
143** {==================================================================
144** Configuration for Paths.
145** ===================================================================
146*/
147
148/*
79149@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
80@* Lua libraries.
150** Lua libraries.
81151@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
82@* C libraries.
152** C libraries.
83153** CHANGE them if your machine has a non-conventional directory
84154** hierarchy or if you want to install your libraries in
85155** non-conventional directories.
86156*/
87#if defined(_WIN32)   /* { */
157#define LUA_VDIR   LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
158#if defined(_WIN32)    /* { */
88159/*
89160** In Windows, any exclamation mark ('!') in the path is replaced by the
90161** path of the directory of the executable file of the current process.
91162*/
92163#define LUA_LDIR   "!\\lua\\"
93164#define LUA_CDIR   "!\\"
165#define LUA_SHRDIR   "!\\..\\share\\lua\\" LUA_VDIR "\\"
94166#define LUA_PATH_DEFAULT  \
95167      LUA_LDIR"?.lua;"  LUA_LDIR"?\\init.lua;" \
96      LUA_CDIR"?.lua;"  LUA_CDIR"?\\init.lua;" ".\\?.lua"
168      LUA_CDIR"?.lua;"  LUA_CDIR"?\\init.lua;" \
169      LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \
170      ".\\?.lua;" ".\\?\\init.lua"
97171#define LUA_CPATH_DEFAULT \
98      LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll"
172      LUA_CDIR"?.dll;" \
173      LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \
174      LUA_CDIR"loadall.dll;" ".\\?.dll"
99175
100176#else         /* }{ */
101177
102#define LUA_VDIR   LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/"
103178#define LUA_ROOT   "/usr/local/"
104#define LUA_LDIR   LUA_ROOT "share/lua/" LUA_VDIR
105#define LUA_CDIR   LUA_ROOT "lib/lua/" LUA_VDIR
179#define LUA_LDIR   LUA_ROOT "share/lua/" LUA_VDIR "/"
180#define LUA_CDIR   LUA_ROOT "lib/lua/" LUA_VDIR "/"
106181#define LUA_PATH_DEFAULT  \
107182      LUA_LDIR"?.lua;"  LUA_LDIR"?/init.lua;" \
108      LUA_CDIR"?.lua;"  LUA_CDIR"?/init.lua;" "./?.lua"
183      LUA_CDIR"?.lua;"  LUA_CDIR"?/init.lua;" \
184      "./?.lua;" "./?/init.lua"
109185#define LUA_CPATH_DEFAULT \
110186      LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so"
111187#endif         /* } */
r242885r242886
122198#define LUA_DIRSEP   "/"
123199#endif
124200
201/* }================================================================== */
125202
203
126204/*
127@@ LUA_ENV is the name of the variable that holds the current
128@@ environment, used to access global names.
129** CHANGE it if you do not like this name.
205** {==================================================================
206** Marks for exported symbols in the C code
207** ===================================================================
130208*/
131#define LUA_ENV      "_ENV"
132209
133
134210/*
135211@@ LUA_API is a mark for all core API functions.
136212@@ LUALIB_API is a mark for all auxiliary library functions.
r242885r242886
162238
163239/*
164240@@ LUAI_FUNC is a mark for all extern functions that are not to be
165@* exported to outside modules.
241** exported to outside modules.
166242@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables
167@* that are not to be exported to outside modules (LUAI_DDEF for
168@* definitions and LUAI_DDEC for declarations).
243** that are not to be exported to outside modules (LUAI_DDEF for
244** definitions and LUAI_DDEC for declarations).
169245** CHANGE them if you need to mark them in some special way. Elf/gcc
170246** (versions 3.2 and later) mark them as "hidden" to optimize access
171247** when Lua is compiled as a shared library. Not all elf targets support
r242885r242886
177253#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
178254    defined(__ELF__)      /* { */
179255#define LUAI_FUNC   __attribute__((visibility("hidden"))) extern
180#define LUAI_DDEC   LUAI_FUNC
181#define LUAI_DDEF   /* empty */
182
183256#else            /* }{ */
184257#define LUAI_FUNC   extern
185#define LUAI_DDEC   extern
186#define LUAI_DDEF   /* empty */
187258#endif            /* } */
188259
260#define LUAI_DDEC   LUAI_FUNC
261#define LUAI_DDEF   /* empty */
189262
263/* }================================================================== */
190264
265
191266/*
192@@ LUA_QL describes how error messages quote program elements.
193** CHANGE it if you want a different appearance.
267** {==================================================================
268** Compatibility with previous versions
269** ===================================================================
194270*/
195#define LUA_QL(x)   "'" x "'"
196#define LUA_QS      LUA_QL("%s")
197271
272/*
273@@ LUA_COMPAT_5_2 controls other macros for compatibility with Lua 5.2.
274@@ LUA_COMPAT_5_1 controls other macros for compatibility with Lua 5.1.
275** You can define it to get all options, or change specific options
276** to fit your specific needs.
277*/
278#if defined(LUA_COMPAT_5_2)   /* { */
198279
199280/*
200@@ LUA_IDSIZE gives the maximum size for the description of the source
201@* of a function in debug information.
202** CHANGE it if you want a different size.
281@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated
282** functions in the mathematical library.
203283*/
204#define LUA_IDSIZE   60
284#define LUA_COMPAT_MATHLIB
205285
286/*
287@@ LUA_COMPAT_BITLIB controls the presence of library 'bit32'.
288*/
289#define LUA_COMPAT_BITLIB
206290
207291/*
208@@ luai_writestring/luai_writeline define how 'print' prints its results.
209** They are only used in libraries and the stand-alone program. (The #if
210** avoids including 'stdio.h' everywhere.)
292@@ LUA_COMPAT_IPAIRS controls the effectiveness of the __ipairs metamethod.
211293*/
212#if defined(LUA_LIB) || defined(lua_c)
213#include <stdio.h>
214#define luai_writestring(s,l)   fwrite((s), sizeof(char), (l), stdout)
215#define luai_writeline()   (luai_writestring("\n", 1), fflush(stdout))
216#endif
294#define LUA_COMPAT_IPAIRS
217295
218296/*
219@@ luai_writestringerror defines how to print error messages.
220** (A format string with one argument is enough for Lua...)
297@@ LUA_COMPAT_APIINTCASTS controls the presence of macros for
298** manipulating other integer types (lua_pushunsigned, lua_tounsigned,
299** luaL_checkint, luaL_checklong, etc.)
221300*/
222#define luai_writestringerror(s,p) \
223   (fprintf(stderr, (s), (p)), fflush(stderr))
301#define LUA_COMPAT_APIINTCASTS
224302
225303
226304/*
227@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is,
228** strings that are internalized. (Cannot be smaller than reserved words
229** or tags for metamethods, as these strings must be internalized;
230** #("function") = 8, #("__newindex") = 10.)
305@@ LUA_COMPAT_FLOATSTRING makes Lua format integral floats without a
306@@ a float mark ('.0').
307** This macro is not on by default even in compatibility mode,
308** because this is not really an incompatibility.
231309*/
232#define LUAI_MAXSHORTLEN        40
310/* #define LUA_COMPAT_FLOATSTRING */
233311
312#endif            /* } */
234313
235314
236/*
237** {==================================================================
238** Compatibility with previous versions
239** ===================================================================
240*/
315#if defined(LUA_COMPAT_5_1)   /* { */
241316
242317/*
243@@ LUA_COMPAT_ALL controls all compatibility options.
244** You can define it to get all options, or change specific options
245** to fit your specific needs.
246*/
247#if defined(LUA_COMPAT_ALL)   /* { */
248
249/*
250318@@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'.
251319** You can replace it with 'table.unpack'.
252320*/
r242885r242886
310378
311379
312380/*
313@@ LUAI_BITSINT defines the number of bits in an int.
314** CHANGE here if Lua cannot automatically detect the number of bits of
315** your machine. Probably you do not need to change this.
381** {==================================================================
382** Configuration for Numbers.
383** Change these definitions if no predefined LUA_REAL_* / LUA_INT_*
384** satisfy your needs.
385** ===================================================================
316386*/
317/* avoid overflows in comparison */
318#if INT_MAX-20 < 32760      /* { */
319#define LUAI_BITSINT   16
320#elif INT_MAX > 2147483640L   /* }{ */
321/* int has at least 32 bits */
322#define LUAI_BITSINT   32
323#else            /* }{ */
324#error "you must define LUA_BITSINT with number of bits in an integer"
325#endif            /* } */
326387
327
328388/*
329@@ LUA_INT32 is an signed integer with exactly 32 bits.
330@@ LUAI_UMEM is an unsigned integer big enough to count the total
331@* memory used by Lua.
332@@ LUAI_MEM is a signed integer big enough to count the total memory
333@* used by Lua.
334** CHANGE here if for some weird reason the default definitions are not
335** good enough for your machine. Probably you do not need to change
336** this.
389@@ LUA_NUMBER is the floating-point type used by Lua.
390**
391@@ LUAI_UACNUMBER is the result of an 'usual argument conversion'
392@@ over a floating number.
393**
394@@ LUA_NUMBER_FRMLEN is the length modifier for writing floats.
395@@ LUA_NUMBER_FMT is the format for writing floats.
396@@ lua_number2str converts a float to a string.
397**
398@@ l_mathop allows the addition of an 'l' or 'f' to all math operations.
399**
400@@ lua_str2number converts a decimal numeric string to a number.
337401*/
338#if LUAI_BITSINT >= 32      /* { */
339#define LUA_INT32   int
340#define LUAI_UMEM   size_t
341#define LUAI_MEM   ptrdiff_t
342#else            /* }{ */
343/* 16-bit ints */
344#define LUA_INT32   long
345#define LUAI_UMEM   unsigned long
346#define LUAI_MEM   long
347#endif            /* } */
348402
403#if defined(LUA_REAL_FLOAT)      /* { single float */
349404
350/*
351@@ LUAI_MAXSTACK limits the size of the Lua stack.
352** CHANGE it if you need a different limit. This limit is arbitrary;
353** its only purpose is to stop Lua to consume unlimited stack
354** space (and to reserve some numbers for pseudo-indices).
355*/
356#if LUAI_BITSINT >= 32
357#define LUAI_MAXSTACK      1000000
358#else
359#define LUAI_MAXSTACK      15000
360#endif
405#define LUA_NUMBER   float
361406
362/* reserve some space for error handling */
363#define LUAI_FIRSTPSEUDOIDX   (-LUAI_MAXSTACK - 1000)
407#define LUAI_UACNUMBER   double
364408
409#define LUA_NUMBER_FRMLEN   ""
410#define LUA_NUMBER_FMT      "%.7g"
365411
412#define l_mathop(op)      op##f
366413
414#define lua_str2number(s,p)   strtof((s), (p))
367415
368/*
369@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
370** CHANGE it if it uses too much C-stack space.
371*/
372#define LUAL_BUFFERSIZE      BUFSIZ
373416
417#elif defined(LUA_REAL_LONGDOUBLE)   /* }{ long double */
374418
419#define LUA_NUMBER   long double
375420
421#define LUAI_UACNUMBER   long double
376422
377/*
378** {==================================================================
379@@ LUA_NUMBER is the type of numbers in Lua.
380** CHANGE the following definitions only if you want to build Lua
381** with a number type different from double. You may also need to
382** change lua_number2int & lua_number2integer.
383** ===================================================================
384*/
423#define LUA_NUMBER_FRMLEN   "L"
424#define LUA_NUMBER_FMT      "%.19Lg"
385425
386#define LUA_NUMBER_DOUBLE
426#define l_mathop(op)      op##l
427
428#define lua_str2number(s,p)   strtold((s), (p))
429
430#elif defined(LUA_REAL_DOUBLE)      /* }{ double */
431
387432#define LUA_NUMBER   double
388433
389/*
390@@ LUAI_UACNUMBER is the result of an 'usual argument conversion'
391@* over a number.
392*/
393434#define LUAI_UACNUMBER   double
394435
436#define LUA_NUMBER_FRMLEN   ""
437#define LUA_NUMBER_FMT      "%.14g"
395438
396/*
397@@ LUA_NUMBER_SCAN is the format for reading numbers.
398@@ LUA_NUMBER_FMT is the format for writing numbers.
399@@ lua_number2str converts a number to a string.
400@@ LUAI_MAXNUMBER2STR is maximum size of previous conversion.
401*/
402#define LUA_NUMBER_SCAN      "%lf"
403#define LUA_NUMBER_FMT      "%.14g"
439#define l_mathop(op)      op
440
441#define lua_str2number(s,p)   strtod((s), (p))
442
443#else               /* }{ */
444
445#error "numeric real type not defined"
446
447#endif               /* } */
448
449
450#define l_floor(x)      (l_mathop(floor)(x))
451
404452#define lua_number2str(s,n)   sprintf((s), LUA_NUMBER_FMT, (n))
405#define LUAI_MAXNUMBER2STR   32 /* 16 digits, sign, point, and \0 */
406453
407454
408455/*
409@@ l_mathop allows the addition of an 'l' or 'f' to all math operations
456@@ lua_numbertointeger converts a float number to an integer, or
457** returns 0 if float is not within the range of a lua_Integer.
458** (The range comparisons are tricky because of rounding. The tests
459** here assume a two-complement representation, where MININTEGER always
460** has an exact representation as a float; MAXINTEGER may not have one,
461** and therefore its conversion to float may have an ill-defined value.)
410462*/
411#define l_mathop(x)      (x)
463#define lua_numbertointeger(n,p) \
464  ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \
465   (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \
466      (*(p) = (LUA_INTEGER)(n), 1))
412467
413468
414469/*
415@@ lua_str2number converts a decimal numeric string to a number.
416@@ lua_strx2number converts an hexadecimal numeric string to a number.
417** In C99, 'strtod' does both conversions. C89, however, has no function
418** to convert floating hexadecimal strings to numbers. For these
419** systems, you can leave 'lua_strx2number' undefined and Lua will
420** provide its own implementation.
470@@ The luai_num* macros define the primitive operations over numbers.
471** They should work for any size of floating numbers.
421472*/
422#define lua_str2number(s,p)   strtod((s), (p))
423473
424#if defined(LUA_USE_STRTODHEX)
425#define lua_strx2number(s,p)   strtod((s), (p))
426#endif
474/* the following operations need the math library */
475#if defined(lobject_c) || defined(lvm_c)
476#include <math.h>
427477
478/* floor division (defined as 'floor(a/b)') */
479#define luai_numidiv(L,a,b)   ((void)L, l_mathop(floor)(luai_numdiv(L,a,b)))
428480
429481/*
430@@ The luai_num* macros define the primitive operations over numbers.
482** module: defined as 'a - floor(a/b)*b'; the previous definition gives
483** NaN when 'b' is huge, but the result should be 'a'. 'fmod' gives the
484** result of 'a - trunc(a/b)*b', and therefore must be corrected when
485** 'trunc(a/b) ~= floor(a/b)'. That happens when the division has a
486** non-integer negative result, which is equivalent to the test below
431487*/
488#define luai_nummod(L,a,b,m)  \
489  { (m) = l_mathop(fmod)(a,b); if ((m)*(b) < 0) (m) += (b); }
432490
433/* the following operations need the math library */
434#if defined(lobject_c) || defined(lvm_c)
435#include <math.h>
436#define luai_nummod(L,a,b)   ((a) - l_mathop(floor)((a)/(b))*(b))
437#define luai_numpow(L,a,b)   (l_mathop(pow)(a,b))
491/* exponentiation */
492#define luai_numpow(L,a,b)   ((void)L, l_mathop(pow)(a,b))
493
438494#endif
439495
440496/* these are quite standard operations */
r242885r242886
445501#define luai_numdiv(L,a,b)   ((a)/(b))
446502#define luai_numunm(L,a)   (-(a))
447503#define luai_numeq(a,b)      ((a)==(b))
448#define luai_numlt(L,a,b)   ((a)<(b))
449#define luai_numle(L,a,b)   ((a)<=(b))
450#define luai_numisnan(L,a)   (!luai_numeq((a), (a)))
504#define luai_numlt(a,b)      ((a)<(b))
505#define luai_numle(a,b)      ((a)<=(b))
506#define luai_numisnan(a)   (!luai_numeq((a), (a)))
451507#endif
452508
453509
510/*
511@@ LUA_INTEGER is the integer type used by Lua.
512**
513@@ LUA_UNSIGNED is the unsigned version of LUA_INTEGER.
514**
515@@ LUAI_UACINT is the result of an 'usual argument conversion'
516@@ over a lUA_INTEGER.
517@@ LUA_INTEGER_FRMLEN is the length modifier for reading/writing integers.
518@@ LUA_INTEGER_FMT is the format for writing integers.
519@@ LUA_MAXINTEGER is the maximum value for a LUA_INTEGER.
520@@ LUA_MININTEGER is the minimum value for a LUA_INTEGER.
521@@ lua_integer2str converts an integer to a string.
522*/
454523
524
525/* The following definitions are good for most cases here */
526
527#define LUA_INTEGER_FMT      "%" LUA_INTEGER_FRMLEN "d"
528#define lua_integer2str(s,n)   sprintf((s), LUA_INTEGER_FMT, (n))
529
530#define LUAI_UACINT      LUA_INTEGER
531
455532/*
456@@ LUA_INTEGER is the integral type used by lua_pushinteger/lua_tointeger.
457** CHANGE that if ptrdiff_t is not adequate on your machine. (On most
458** machines, ptrdiff_t gives a good choice between int or long.)
533** use LUAI_UACINT here to avoid problems with promotions (which
534** can turn a comparison between unsigneds into a signed comparison)
459535*/
460#define LUA_INTEGER   ptrdiff_t
536#define LUA_UNSIGNED      unsigned LUAI_UACINT
461537
538
539/* now the variable definitions */
540
541#if defined(LUA_INT_INT)      /* { int */
542
543#define LUA_INTEGER      int
544#define LUA_INTEGER_FRMLEN   ""
545
546#define LUA_MAXINTEGER      INT_MAX
547#define LUA_MININTEGER      INT_MIN
548
549#elif defined(LUA_INT_LONG)   /* }{ long */
550
551#define LUA_INTEGER      long
552#define LUA_INTEGER_FRMLEN   "l"
553
554#define LUA_MAXINTEGER      LONG_MAX
555#define LUA_MININTEGER      LONG_MIN
556
557#elif defined(LUA_INT_LONGLONG)   /* }{ long long */
558
559#if defined(LLONG_MAX)      /* { */
560/* use ISO C99 stuff */
561
562#define LUA_INTEGER      long long
563#define LUA_INTEGER_FRMLEN   "ll"
564
565#define LUA_MAXINTEGER      LLONG_MAX
566#define LUA_MININTEGER      LLONG_MIN
567
568#elif defined(LUA_USE_WINDOWS) /* }{ */
569/* in Windows, can use specific Windows types */
570
571#define LUA_INTEGER      __int64
572#define LUA_INTEGER_FRMLEN   "I64"
573
574#define LUA_MAXINTEGER      _I64_MAX
575#define LUA_MININTEGER      _I64_MIN
576
577#else            /* }{ */
578
579#error "Compiler does not support 'long long'. Use option '-DLUA_32BITS' \
580  or '-DLUA_C89_NUMBERS' (see file 'luaconf.h' for details)"
581
582#endif            /* } */
583
584#else            /* }{ */
585
586#error "numeric integer type not defined"
587
588#endif            /* } */
589
590/* }================================================================== */
591
592
462593/*
463@@ LUA_UNSIGNED is the integral type used by lua_pushunsigned/lua_tounsigned.
464** It must have at least 32 bits.
594** {==================================================================
595** Dependencies with C99
596** ===================================================================
465597*/
466#define LUA_UNSIGNED   unsigned LUA_INT32
467598
599/*
600@@ lua_strx2number converts an hexadecimal numeric string to a number.
601** In C99, 'strtod' does both conversions. Otherwise, you can
602** leave 'lua_strx2number' undefined and Lua will provide its own
603** implementation.
604*/
605#if !defined(LUA_USE_C89)
606#define lua_strx2number(s,p)   lua_str2number(s,p)
607#endif
468608
469609
470610/*
471** Some tricks with doubles
611@@ LUA_USE_AFORMAT allows '%a'/'%A' specifiers in 'string.format'
612** Enable it if the C function 'printf' supports these specifiers.
613** (C99 demands it and Windows also supports it.)
472614*/
615#if !defined(LUA_USE_C89) || defined(LUA_USE_WINDOWS)
616#define LUA_USE_AFORMAT
617#endif
473618
474#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI)   /* { */
619
475620/*
476** The next definitions activate some tricks to speed up the
477** conversion from doubles to integer types, mainly to LUA_UNSIGNED.
478**
479@@ LUA_MSASMTRICK uses Microsoft assembler to avoid clashes with a
480** DirectX idiosyncrasy.
481**
482@@ LUA_IEEE754TRICK uses a trick that should work on any machine
483** using IEEE754 with a 32-bit integer type.
484**
485@@ LUA_IEEELL extends the trick to LUA_INTEGER; should only be
486** defined when LUA_INTEGER is a 32-bit integer.
487**
488@@ LUA_IEEEENDIAN is the endianness of doubles in your machine
489** (0 for little endian, 1 for big endian); if not defined, Lua will
490** check it dynamically for LUA_IEEE754TRICK (but not for LUA_NANTRICK).
491**
492@@ LUA_NANTRICK controls the use of a trick to pack all types into
493** a single double value, using NaN values to represent non-number
494** values. The trick only works on 32-bit machines (ints and pointers
495** are 32-bit values) with numbers represented as IEEE 754-2008 doubles
496** with conventional endianess (12345678 or 87654321), in CPUs that do
497** not produce signaling NaN values (all NaNs are quiet).
621** 'strtof' and 'opf' variants for math functions are not valid in
622** C89. Otherwise, the macro 'HUGE_VALF' is a good proxy for testing the
623** availability of these variants. ('math.h' is already included in
624** all files that use these macros.)
498625*/
626#if defined(LUA_USE_C89) || (defined(HUGE_VAL) && !defined(HUGE_VALF))
627#undef l_mathop  /* variants not available */
628#undef lua_str2number
629#define l_mathop(op)      (lua_Number)op  /* no variant */
630#define lua_str2number(s,p)   ((lua_Number)strtod((s), (p)))
631#endif
499632
500/* Microsoft compiler on a Pentium (32 bit) ? */
501#if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86)   /* { */
502633
503#define LUA_MSASMTRICK
504#define LUA_IEEEENDIAN      0
505#define LUA_NANTRICK
634/*
635@@ LUA_KCONTEXT is the type of the context ('ctx') for continuation
636** functions.  It must be a numerical type; Lua will use 'intptr_t' if
637** available, otherwise it will use 'ptrdiff_t' (the nearest thing to
638** 'intptr_t' in C89)
639*/
640#define LUA_KCONTEXT   ptrdiff_t
506641
642#if !defined(LUA_USE_C89) && defined(__STDC_VERSION__) && \
643    __STDC_VERSION__ >= 199901L
644#include <stdint.h>
645#if defined (INTPTR_MAX)  /* even in C99 this type is optional */
646#undef LUA_KCONTEXT
647#define LUA_KCONTEXT   intptr_t
648#endif
649#endif
507650
508/* pentium 32 bits? */
509#elif defined(__i386__) || defined(__i386) || defined(__X86__) /* }{ */
651/* }================================================================== */
510652
511#define LUA_IEEE754TRICK
512#define LUA_IEEELL
513#define LUA_IEEEENDIAN      0
514#define LUA_NANTRICK
515653
516/* pentium 64 bits? */
517#elif defined(__x86_64)                  /* }{ */
654/*
655** {==================================================================
656** Macros that affect the API and must be stable (that is, must be the
657** same when you compile Lua and when you compile code that links to
658** Lua). You probably do not want/need to change them.
659** =====================================================================
660*/
518661
519#define LUA_IEEE754TRICK
520#define LUA_IEEEENDIAN      0
662/*
663@@ LUAI_MAXSTACK limits the size of the Lua stack.
664** CHANGE it if you need a different limit. This limit is arbitrary;
665** its only purpose is to stop Lua from consuming unlimited stack
666** space (and to reserve some numbers for pseudo-indices).
667*/
668#if LUAI_BITSINT >= 32
669#define LUAI_MAXSTACK      1000000
670#else
671#define LUAI_MAXSTACK      15000
672#endif
521673
522#elif defined(__POWERPC__) || defined(__ppc__)         /* }{ */
674/* reserve some space for error handling */
675#define LUAI_FIRSTPSEUDOIDX   (-LUAI_MAXSTACK - 1000)
523676
524#define LUA_IEEE754TRICK
525#define LUA_IEEEENDIAN      1
526677
527#else                        /* }{ */
678/*
679@@ LUA_EXTRASPACE defines the size of a raw memory area associated with
680** a Lua state with very fast access.
681** CHANGE it if you need a different size.
682*/
683#define LUA_EXTRASPACE      (sizeof(void *))
528684
529/* assume IEEE754 and a 32-bit integer type */
530#define LUA_IEEE754TRICK
531685
532#endif                        /* } */
686/*
687@@ LUA_IDSIZE gives the maximum size for the description of the source
688@@ of a function in debug information.
689** CHANGE it if you want a different size.
690*/
691#define LUA_IDSIZE   60
533692
534#endif                     /* } */
535693
694/*
695@@ LUAI_MAXSHORTLEN is the maximum length for short strings, that is,
696** strings that are internalized. (Cannot be smaller than reserved words
697** or tags for metamethods, as these strings must be internalized;
698** #("function") = 8, #("__newindex") = 10.)
699*/
700#define LUAI_MAXSHORTLEN        40
701
702
703/*
704@@ LUAL_BUFFERSIZE is the buffer size used by the lauxlib buffer system.
705** CHANGE it if it uses too much C-stack space.
706*/
707#define LUAL_BUFFERSIZE   ((int)(0x80 * sizeof(void*) * sizeof(lua_Integer)))
708
536709/* }================================================================== */
537710
538711
712/*
713@@ LUA_QL describes how error messages quote program elements.
714** Lua does not use these macros anymore; they are here for
715** compatibility only.
716*/
717#define LUA_QL(x)   "'" x "'"
718#define LUA_QS      LUA_QL("%s")
539719
540720
721
722
541723/* =================================================================== */
542724
543725/*
r242885r242886
547729
548730
549731
732
733
550734#endif
551735
trunk/3rdparty/lua/src/lualib.h
r242885r242886
11/*
2** $Id: lualib.h,v 1.43.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lualib.h,v 1.44 2014/02/06 17:32:33 roberto Exp $
33** Lua standard libraries
44** See Copyright Notice in lua.h
55*/
r242885r242886
2929#define LUA_STRLIBNAME   "string"
3030LUAMOD_API int (luaopen_string) (lua_State *L);
3131
32#define LUA_UTF8LIBNAME   "utf8"
33LUAMOD_API int (luaopen_utf8) (lua_State *L);
34
3235#define LUA_BITLIBNAME   "bit32"
3336LUAMOD_API int (luaopen_bit32) (lua_State *L);
3437
trunk/3rdparty/lua/src/lundump.c
r242885r242886
11/*
2** $Id: lundump.c,v 2.22.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lundump.c,v 2.41 2014/11/02 19:19:04 roberto Exp $
33** load precompiled Lua chunks
44** See Copyright Notice in lua.h
55*/
66
7#include <string.h>
8
97#define lundump_c
108#define LUA_CORE
119
10#include "lprefix.h"
11
12
13#include <string.h>
14
1215#include "lua.h"
1316
1417#include "ldebug.h"
r242885r242886
2023#include "lundump.h"
2124#include "lzio.h"
2225
26
27#if !defined(luai_verifycode)
28#define luai_verifycode(L,b,f)  /* empty */
29#endif
30
31
2332typedef struct {
24 lua_State* L;
25 ZIO* Z;
26 Mbuffer* b;
27 const char* name;
33  lua_State *L;
34  ZIO *Z;
35  Mbuffer *b;
36  const char *name;
2837} LoadState;
2938
30static l_noret error(LoadState* S, const char* why)
31{
32 luaO_pushfstring(S->L,"%s: %s precompiled chunk",S->name,why);
33 luaD_throw(S->L,LUA_ERRSYNTAX);
39
40static l_noret error(LoadState *S, const char *why) {
41  luaO_pushfstring(S->L, "%s: %s precompiled chunk", S->name, why);
42  luaD_throw(S->L, LUA_ERRSYNTAX);
3443}
3544
36#define LoadMem(S,b,n,size)   LoadBlock(S,b,(n)*(size))
37#define LoadByte(S)      (lu_byte)LoadChar(S)
38#define LoadVar(S,x)      LoadMem(S,&x,1,sizeof(x))
39#define LoadVector(S,b,n,size)   LoadMem(S,b,n,size)
4045
41#if !defined(luai_verifycode)
42#define luai_verifycode(L,b,f)   /* empty */
43#endif
46/*
47** All high-level loads go through LoadVector; you can change it to
48** adapt to the endianness of the input
49*/
50#define LoadVector(S,b,n)   LoadBlock(S,b,(n)*sizeof((b)[0]))
4451
45static void LoadBlock(LoadState* S, void* b, size_t size)
46{
47 if (luaZ_read(S->Z,b,size)!=0) error(S,"truncated");
52static void LoadBlock (LoadState *S, void *b, size_t size) {
53  if (luaZ_read(S->Z, b, size) != 0)
54    error(S, "truncated");
4855}
4956
50static int LoadChar(LoadState* S)
51{
52 char x;
53 LoadVar(S,x);
54 return x;
57
58#define LoadVar(S,x)      LoadVector(S,&x,1)
59
60
61static lu_byte LoadByte (LoadState *S) {
62  lu_byte x;
63  LoadVar(S, x);
64  return x;
5565}
5666
57static int LoadInt(LoadState* S)
58{
59 int x;
60 LoadVar(S,x);
61 if (x<0) error(S,"corrupted");
62 return x;
67
68static int LoadInt (LoadState *S) {
69  int x;
70  LoadVar(S, x);
71  return x;
6372}
6473
65static lua_Number LoadNumber(LoadState* S)
66{
67 lua_Number x;
68 LoadVar(S,x);
69 return x;
74
75static lua_Number LoadNumber (LoadState *S) {
76  lua_Number x;
77  LoadVar(S, x);
78  return x;
7079}
7180
72static TString* LoadString(LoadState* S)
73{
74 size_t size;
75 LoadVar(S,size);
76 if (size==0)
77  return NULL;
78 else
79 {
80  char* s=luaZ_openspace(S->L,S->b,size);
81  LoadBlock(S,s,size*sizeof(char));
82  return luaS_newlstr(S->L,s,size-1);      /* remove trailing '\0' */
83 }
81
82static lua_Integer LoadInteger (LoadState *S) {
83  lua_Integer x;
84  LoadVar(S, x);
85  return x;
8486}
8587
86static void LoadCode(LoadState* S, Proto* f)
87{
88 int n=LoadInt(S);
89 f->code=luaM_newvector(S->L,n,Instruction);
90 f->sizecode=n;
91 LoadVector(S,f->code,n,sizeof(Instruction));
88
89static TString *LoadString (LoadState *S) {
90  size_t size = LoadByte(S);
91  if (size == 0xFF)
92    LoadVar(S, size);
93  if (size == 0)
94    return NULL;
95  else {
96    char *s = luaZ_openspace(S->L, S->b, --size);
97    LoadVector(S, s, size);
98    return luaS_newlstr(S->L, s, size);
99  }
92100}
93101
94static void LoadFunction(LoadState* S, Proto* f);
95102
96static void LoadConstants(LoadState* S, Proto* f)
97{
98 int i,n;
99 n=LoadInt(S);
100 f->k=luaM_newvector(S->L,n,TValue);
101 f->sizek=n;
102 for (i=0; i<n; i++) setnilvalue(&f->k[i]);
103 for (i=0; i<n; i++)
104 {
105  TValue* o=&f->k[i];
106  int t=LoadChar(S);
107  switch (t)
108  {
109   case LUA_TNIL:
110   setnilvalue(o);
111   break;
112   case LUA_TBOOLEAN:
113   setbvalue(o,LoadChar(S));
114   break;
115   case LUA_TNUMBER:
116   setnvalue(o,LoadNumber(S));
117   break;
118   case LUA_TSTRING:
119   setsvalue2n(S->L,o,LoadString(S));
120   break;
121    default: lua_assert(0);
103static void LoadCode (LoadState *S, Proto *f) {
104  int n = LoadInt(S);
105  f->code = luaM_newvector(S->L, n, Instruction);
106  f->sizecode = n;
107  LoadVector(S, f->code, n);
108}
109
110
111static void LoadFunction(LoadState *S, Proto *f, TString *psource);
112
113
114static void LoadConstants (LoadState *S, Proto *f) {
115  int i;
116  int n = LoadInt(S);
117  f->k = luaM_newvector(S->L, n, TValue);
118  f->sizek = n;
119  for (i = 0; i < n; i++)
120    setnilvalue(&f->k[i]);
121  for (i = 0; i < n; i++) {
122    TValue *o = &f->k[i];
123    int t = LoadByte(S);
124    switch (t) {
125    case LUA_TNIL:
126      setnilvalue(o);
127      break;
128    case LUA_TBOOLEAN:
129      setbvalue(o, LoadByte(S));
130      break;
131    case LUA_TNUMFLT:
132      setfltvalue(o, LoadNumber(S));
133      break;
134    case LUA_TNUMINT:
135      setivalue(o, LoadInteger(S));
136      break;
137    case LUA_TSHRSTR:
138    case LUA_TLNGSTR:
139      setsvalue2n(S->L, o, LoadString(S));
140      break;
141    default:
142      lua_assert(0);
143    }
122144  }
123 }
124 n=LoadInt(S);
125 f->p=luaM_newvector(S->L,n,Proto*);
126 f->sizep=n;
127 for (i=0; i<n; i++) f->p[i]=NULL;
128 for (i=0; i<n; i++)
129 {
130  f->p[i]=luaF_newproto(S->L);
131  LoadFunction(S,f->p[i]);
132 }
133145}
134146
135static void LoadUpvalues(LoadState* S, Proto* f)
136{
137 int i,n;
138 n=LoadInt(S);
139 f->upvalues=luaM_newvector(S->L,n,Upvaldesc);
140 f->sizeupvalues=n;
141 for (i=0; i<n; i++) f->upvalues[i].name=NULL;
142 for (i=0; i<n; i++)
143 {
144  f->upvalues[i].instack=LoadByte(S);
145  f->upvalues[i].idx=LoadByte(S);
146 }
147
148static void LoadProtos (LoadState *S, Proto *f) {
149  int i;
150  int n = LoadInt(S);
151  f->p = luaM_newvector(S->L, n, Proto *);
152  f->sizep = n;
153  for (i = 0; i < n; i++)
154    f->p[i] = NULL;
155  for (i = 0; i < n; i++) {
156    f->p[i] = luaF_newproto(S->L);
157    LoadFunction(S, f->p[i], f->source);
158  }
147159}
148160
149static void LoadDebug(LoadState* S, Proto* f)
150{
151 int i,n;
152 f->source=LoadString(S);
153 n=LoadInt(S);
154 f->lineinfo=luaM_newvector(S->L,n,int);
155 f->sizelineinfo=n;
156 LoadVector(S,f->lineinfo,n,sizeof(int));
157 n=LoadInt(S);
158 f->locvars=luaM_newvector(S->L,n,LocVar);
159 f->sizelocvars=n;
160 for (i=0; i<n; i++) f->locvars[i].varname=NULL;
161 for (i=0; i<n; i++)
162 {
163  f->locvars[i].varname=LoadString(S);
164  f->locvars[i].startpc=LoadInt(S);
165  f->locvars[i].endpc=LoadInt(S);
166 }
167 n=LoadInt(S);
168 for (i=0; i<n; i++) f->upvalues[i].name=LoadString(S);
161
162static void LoadUpvalues (LoadState *S, Proto *f) {
163  int i, n;
164  n = LoadInt(S);
165  f->upvalues = luaM_newvector(S->L, n, Upvaldesc);
166  f->sizeupvalues = n;
167  for (i = 0; i < n; i++)
168    f->upvalues[i].name = NULL;
169  for (i = 0; i < n; i++) {
170    f->upvalues[i].instack = LoadByte(S);
171    f->upvalues[i].idx = LoadByte(S);
172  }
169173}
170174
171static void LoadFunction(LoadState* S, Proto* f)
172{
173 f->linedefined=LoadInt(S);
174 f->lastlinedefined=LoadInt(S);
175 f->numparams=LoadByte(S);
176 f->is_vararg=LoadByte(S);
177 f->maxstacksize=LoadByte(S);
178 LoadCode(S,f);
179 LoadConstants(S,f);
180 LoadUpvalues(S,f);
181 LoadDebug(S,f);
175
176static void LoadDebug (LoadState *S, Proto *f) {
177  int i, n;
178  n = LoadInt(S);
179  f->lineinfo = luaM_newvector(S->L, n, int);
180  f->sizelineinfo = n;
181  LoadVector(S, f->lineinfo, n);
182  n = LoadInt(S);
183  f->locvars = luaM_newvector(S->L, n, LocVar);
184  f->sizelocvars = n;
185  for (i = 0; i < n; i++)
186    f->locvars[i].varname = NULL;
187  for (i = 0; i < n; i++) {
188    f->locvars[i].varname = LoadString(S);
189    f->locvars[i].startpc = LoadInt(S);
190    f->locvars[i].endpc = LoadInt(S);
191  }
192  n = LoadInt(S);
193  for (i = 0; i < n; i++)
194    f->upvalues[i].name = LoadString(S);
182195}
183196
184/* the code below must be consistent with the code in luaU_header */
185#define N0   LUAC_HEADERSIZE
186#define N1   (sizeof(LUA_SIGNATURE)-sizeof(char))
187#define N2   N1+2
188#define N3   N2+6
189197
190static void LoadHeader(LoadState* S)
191{
192 lu_byte h[LUAC_HEADERSIZE];
193 lu_byte s[LUAC_HEADERSIZE];
194 luaU_header(h);
195 memcpy(s,h,sizeof(char));         /* first char already read */
196 LoadBlock(S,s+sizeof(char),LUAC_HEADERSIZE-sizeof(char));
197 if (memcmp(h,s,N0)==0) return;
198 if (memcmp(h,s,N1)!=0) error(S,"not a");
199 if (memcmp(h,s,N2)!=0) error(S,"version mismatch in");
200 if (memcmp(h,s,N3)!=0) error(S,"incompatible"); else error(S,"corrupted");
198static void LoadFunction (LoadState *S, Proto *f, TString *psource) {
199  f->source = LoadString(S);
200  if (f->source == NULL)  /* no source in dump? */
201    f->source = psource;  /* reuse parent's source */
202  f->linedefined = LoadInt(S);
203  f->lastlinedefined = LoadInt(S);
204  f->numparams = LoadByte(S);
205  f->is_vararg = LoadByte(S);
206  f->maxstacksize = LoadByte(S);
207  LoadCode(S, f);
208  LoadConstants(S, f);
209  LoadUpvalues(S, f);
210  LoadProtos(S, f);
211  LoadDebug(S, f);
201212}
202213
203/*
204** load precompiled chunk
205*/
206Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name)
207{
208 LoadState S;
209 Closure* cl;
210 if (*name=='@' || *name=='=')
211  S.name=name+1;
212 else if (*name==LUA_SIGNATURE[0])
213  S.name="binary string";
214 else
215  S.name=name;
216 S.L=L;
217 S.Z=Z;
218 S.b=buff;
219 LoadHeader(&S);
220 cl=luaF_newLclosure(L,1);
221 setclLvalue(L,L->top,cl); incr_top(L);
222 cl->l.p=luaF_newproto(L);
223 LoadFunction(&S,cl->l.p);
224 if (cl->l.p->sizeupvalues != 1)
225 {
226  Proto* p=cl->l.p;
227  cl=luaF_newLclosure(L,cl->l.p->sizeupvalues);
228  cl->l.p=p;
229  setclLvalue(L,L->top-1,cl);
230 }
231 luai_verifycode(L,buff,cl->l.p);
232 return cl;
214
215static void checkliteral (LoadState *S, const char *s, const char *msg) {
216  char buff[sizeof(LUA_SIGNATURE) + sizeof(LUAC_DATA)]; /* larger than both */
217  size_t len = strlen(s);
218  LoadVector(S, buff, len);
219  if (memcmp(s, buff, len) != 0)
220    error(S, msg);
233221}
234222
235#define MYINT(s)   (s[0]-'0')
236#define VERSION      MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR)
237#define FORMAT      0      /* this is the official format */
238223
224static void fchecksize (LoadState *S, size_t size, const char *tname) {
225  if (LoadByte(S) != size)
226    error(S, luaO_pushfstring(S->L, "%s size mismatch in", tname));
227}
228
229
230#define checksize(S,t)   fchecksize(S,sizeof(t),#t)
231
232static void checkHeader (LoadState *S) {
233  checkliteral(S, LUA_SIGNATURE + 1, "not a");  /* 1st char already checked */
234  if (LoadByte(S) != LUAC_VERSION)
235    error(S, "version mismatch in");
236  if (LoadByte(S) != LUAC_FORMAT)
237    error(S, "format mismatch in");
238  checkliteral(S, LUAC_DATA, "corrupted");
239  checksize(S, int);
240  checksize(S, size_t);
241  checksize(S, Instruction);
242  checksize(S, lua_Integer);
243  checksize(S, lua_Number);
244  if (LoadInteger(S) != LUAC_INT)
245    error(S, "endianness mismatch in");
246  if (LoadNumber(S) != LUAC_NUM)
247    error(S, "float format mismatch in");
248}
249
250
239251/*
240* make header for precompiled chunks
241* if you change the code below be sure to update LoadHeader and FORMAT above
242* and LUAC_HEADERSIZE in lundump.h
252** load precompiled chunk
243253*/
244void luaU_header (lu_byte* h)
245{
246 int x=1;
247 memcpy(h,LUA_SIGNATURE,sizeof(LUA_SIGNATURE)-sizeof(char));
248 h+=sizeof(LUA_SIGNATURE)-sizeof(char);
249 *h++=cast_byte(VERSION);
250 *h++=cast_byte(FORMAT);
251 *h++=cast_byte(*(char*)&x);         /* endianness */
252 *h++=cast_byte(sizeof(int));
253 *h++=cast_byte(sizeof(size_t));
254 *h++=cast_byte(sizeof(Instruction));
255 *h++=cast_byte(sizeof(lua_Number));
256 *h++=cast_byte(((lua_Number)0.5)==0);      /* is lua_Number integral? */
257 memcpy(h,LUAC_TAIL,sizeof(LUAC_TAIL)-sizeof(char));
254LClosure *luaU_undump(lua_State *L, ZIO *Z, Mbuffer *buff,
255                      const char *name) {
256  LoadState S;
257  LClosure *cl;
258  if (*name == '@' || *name == '=')
259    S.name = name + 1;
260  else if (*name == LUA_SIGNATURE[0])
261    S.name = "binary string";
262  else
263    S.name = name;
264  S.L = L;
265  S.Z = Z;
266  S.b = buff;
267  checkHeader(&S);
268  cl = luaF_newLclosure(L, LoadByte(&S));
269  setclLvalue(L, L->top, cl);
270  incr_top(L);
271  cl->p = luaF_newproto(L);
272  LoadFunction(&S, cl->p, NULL);
273  lua_assert(cl->nupvalues == cl->p->sizeupvalues);
274  luai_verifycode(L, buff, cl->p);
275  return cl;
258276}
277
trunk/3rdparty/lua/src/lundump.h
r242885r242886
11/*
2** $Id: lundump.h,v 1.39.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lundump.h,v 1.44 2014/06/19 18:27:20 roberto Exp $
33** load precompiled Lua chunks
44** See Copyright Notice in lua.h
55*/
r242885r242886
77#ifndef lundump_h
88#define lundump_h
99
10#include "llimits.h"
1011#include "lobject.h"
1112#include "lzio.h"
1213
13/* load one chunk; from lundump.c */
14LUAI_FUNC Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);
1514
16/* make header; from lundump.c */
17LUAI_FUNC void luaU_header (lu_byte* h);
15/* data to catch conversion errors */
16#define LUAC_DATA   "\x19\x93\r\n\x1a\n"
1817
19/* dump one chunk; from ldump.c */
20LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w, void* data, int strip);
18#define LUAC_INT   0x5678
19#define LUAC_NUM   cast_num(370.5)
2120
22/* data to catch conversion errors */
23#define LUAC_TAIL      "\x19\x93\r\n\x1a\n"
21#define MYINT(s)   (s[0]-'0')
22#define LUAC_VERSION   (MYINT(LUA_VERSION_MAJOR)*16+MYINT(LUA_VERSION_MINOR))
23#define LUAC_FORMAT   0   /* this is the official format */
2424
25/* size in bytes of header of binary files */
26#define LUAC_HEADERSIZE      (sizeof(LUA_SIGNATURE)-sizeof(char)+2+6+sizeof(LUAC_TAIL)-sizeof(char))
25/* load one chunk; from lundump.c */
26LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff,
27                                 const char* name);
2728
29/* dump one chunk; from ldump.c */
30LUAI_FUNC int luaU_dump (lua_State* L, const Proto* f, lua_Writer w,
31                         void* data, int strip);
32
2833#endif
trunk/3rdparty/lua/src/lutf8lib.c
r0r242886
1/*
2** $Id: lutf8lib.c,v 1.13 2014/11/02 19:19:04 roberto Exp $
3** Standard library for UTF-8 manipulation
4** See Copyright Notice in lua.h
5*/
6
7#define lutf8lib_c
8#define LUA_LIB
9
10#include "lprefix.h"
11
12
13#include <assert.h>
14#include <stdlib.h>
15#include <string.h>
16
17#include "lua.h"
18
19#include "lauxlib.h"
20#include "lualib.h"
21
22#define MAXUNICODE   0x10FFFF
23
24#define iscont(p)   ((*(p) & 0xC0) == 0x80)
25
26
27/* from strlib */
28/* translate a relative string position: negative means back from end */
29static lua_Integer u_posrelat (lua_Integer pos, size_t len) {
30  if (pos >= 0) return pos;
31  else if (0u - (size_t)pos > len) return 0;
32  else return (lua_Integer)len + pos + 1;
33}
34
35
36/*
37** Decode one UTF-8 sequence, returning NULL if byte sequence is invalid.
38*/
39static const char *utf8_decode (const char *o, int *val) {
40  static unsigned int limits[] = {0xFF, 0x7F, 0x7FF, 0xFFFF};
41  const unsigned char *s = (const unsigned char *)o;
42  unsigned int c = s[0];
43  unsigned int res = 0;  /* final result */
44  if (c < 0x80)  /* ascii? */
45    res = c;
46  else {
47    int count = 0;  /* to count number of continuation bytes */
48    while (c & 0x40) {  /* still have continuation bytes? */
49      int cc = s[++count];  /* read next byte */
50      if ((cc & 0xC0) != 0x80)  /* not a continuation byte? */
51        return NULL;  /* invalid byte sequence */
52      res = (res << 6) | (cc & 0x3F);  /* add lower 6 bits from cont. byte */
53      c <<= 1;  /* to test next bit */
54    }
55    res |= ((c & 0x7F) << (count * 5));  /* add first byte */
56    if (count > 3 || res > MAXUNICODE || res <= limits[count])
57      return NULL;  /* invalid byte sequence */
58    s += count;  /* skip continuation bytes read */
59  }
60  if (val) *val = res;
61  return (const char *)s + 1;  /* +1 to include first byte */
62}
63
64
65/*
66** utf8len(s [, i [, j]]) --> number of characters that start in the
67** range [i,j], or nil + current position if 's' is not well formed in
68** that interval
69*/
70static int utflen (lua_State *L) {
71  int n = 0;
72  size_t len;
73  const char *s = luaL_checklstring(L, 1, &len);
74  lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
75  lua_Integer posj = u_posrelat(luaL_optinteger(L, 3, -1), len);
76  luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
77                   "initial position out of string");
78  luaL_argcheck(L, --posj < (lua_Integer)len, 3,
79                   "final position out of string");
80  while (posi <= posj) {
81    const char *s1 = utf8_decode(s + posi, NULL);
82    if (s1 == NULL) {  /* conversion error? */
83      lua_pushnil(L);  /* return nil ... */
84      lua_pushinteger(L, posi + 1);  /* ... and current position */
85      return 2;
86    }
87    posi = s1 - s;
88    n++;
89  }
90  lua_pushinteger(L, n);
91  return 1;
92}
93
94
95/*
96** codepoint(s, [i, [j]])  -> returns codepoints for all characters
97** that start in the range [i,j]
98*/
99static int codepoint (lua_State *L) {
100  size_t len;
101  const char *s = luaL_checklstring(L, 1, &len);
102  lua_Integer posi = u_posrelat(luaL_optinteger(L, 2, 1), len);
103  lua_Integer pose = u_posrelat(luaL_optinteger(L, 3, posi), len);
104  int n;
105  const char *se;
106  luaL_argcheck(L, posi >= 1, 2, "out of range");
107  luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of range");
108  if (posi > pose) return 0;  /* empty interval; return no values */
109  n = (int)(pose -  posi + 1);
110  if (posi + n <= pose)  /* (lua_Integer -> int) overflow? */
111    return luaL_error(L, "string slice too long");
112  luaL_checkstack(L, n, "string slice too long");
113  n = 0;
114  se = s + pose;
115  for (s += posi - 1; s < se;) {
116    int code;
117    s = utf8_decode(s, &code);
118    if (s == NULL)
119      return luaL_error(L, "invalid UTF-8 code");
120    lua_pushinteger(L, code);
121    n++;
122  }
123  return n;
124}
125
126
127static void pushutfchar (lua_State *L, int arg) {
128  lua_Integer code = luaL_checkinteger(L, arg);
129  luaL_argcheck(L, 0 <= code && code <= MAXUNICODE, arg, "value out of range");
130  lua_pushfstring(L, "%U", (long)code);
131}
132
133
134/*
135** utfchar(n1, n2, ...)  -> char(n1)..char(n2)...
136*/
137static int utfchar (lua_State *L) {
138  int n = lua_gettop(L);  /* number of arguments */
139  if (n == 1)  /* optimize common case of single char */
140    pushutfchar(L, 1);
141  else {
142    int i;
143    luaL_Buffer b;
144    luaL_buffinit(L, &b);
145    for (i = 1; i <= n; i++) {
146      pushutfchar(L, i);
147      luaL_addvalue(&b);
148    }
149    luaL_pushresult(&b);
150  }
151  return 1;
152}
153
154
155/*
156** offset(s, n, [i])  -> index where n-th character counting from
157**   position 'i' starts; 0 means character at 'i'.
158*/
159static int byteoffset (lua_State *L) {
160  size_t len;
161  const char *s = luaL_checklstring(L, 1, &len);
162  lua_Integer n  = luaL_checkinteger(L, 2);
163  lua_Integer posi = (n >= 0) ? 1 : len + 1;
164  posi = u_posrelat(luaL_optinteger(L, 3, posi), len);
165  luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 3,
166                   "position out of range");
167  if (n == 0) {
168    /* find beginning of current byte sequence */
169    while (posi > 0 && iscont(s + posi)) posi--;
170  }
171  else {
172    if (iscont(s + posi))
173      luaL_error(L, "initial position is a continuation byte");
174    if (n < 0) {
175       while (n < 0 && posi > 0) {  /* move back */
176         do {  /* find beginning of previous character */
177           posi--;
178         } while (posi > 0 && iscont(s + posi));
179         n++;
180       }
181     }
182     else {
183       n--;  /* do not move for 1st character */
184       while (n > 0 && posi < (lua_Integer)len) {
185         do {  /* find beginning of next character */
186           posi++;
187         } while (iscont(s + posi));  /* (cannot pass final '\0') */
188         n--;
189       }
190     }
191  }
192  if (n == 0)  /* did it find given character? */
193    lua_pushinteger(L, posi + 1);
194  else  /* no such character */
195    lua_pushnil(L);
196  return 1; 
197}
198
199
200static int iter_aux (lua_State *L) {
201  size_t len;
202  const char *s = luaL_checklstring(L, 1, &len);
203  lua_Integer n = lua_tointeger(L, 2) - 1;
204  if (n < 0)  /* first iteration? */
205    n = 0;  /* start from here */
206  else if (n < (lua_Integer)len) {
207    n++;  /* skip current byte */
208    while (iscont(s + n)) n++;  /* and its continuations */
209  }
210  if (n >= (lua_Integer)len)
211    return 0;  /* no more codepoints */
212  else {
213    int code;
214    const char *next = utf8_decode(s + n, &code);
215    if (next == NULL || iscont(next))
216      return luaL_error(L, "invalid UTF-8 code");
217    lua_pushinteger(L, n + 1);
218    lua_pushinteger(L, code);
219    return 2;
220  }
221}
222
223
224static int iter_codes (lua_State *L) {
225  luaL_checkstring(L, 1);
226  lua_pushcfunction(L, iter_aux);
227  lua_pushvalue(L, 1);
228  lua_pushinteger(L, 0);
229  return 3;
230}
231
232
233/* pattern to match a single UTF-8 character */
234#define UTF8PATT   "[\0-\x7F\xC2-\xF4][\x80-\xBF]*"
235
236
237static struct luaL_Reg funcs[] = {
238  {"offset", byteoffset},
239  {"codepoint", codepoint},
240  {"char", utfchar},
241  {"len", utflen},
242  {"codes", iter_codes},
243  /* placeholders */
244  {"charpattern", NULL},
245  {NULL, NULL}
246};
247
248
249LUAMOD_API int luaopen_utf8 (lua_State *L) {
250  luaL_newlib(L, funcs);
251  lua_pushliteral(L, UTF8PATT);
252  lua_setfield(L, -2, "charpattern");
253  return 1;
254}
255
trunk/3rdparty/lua/src/lvm.c
r242885r242886
11/*
2** $Id: lvm.c,v 2.155.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lvm.c,v 2.232 2014/12/27 20:30:38 roberto Exp $
33** Lua virtual machine
44** See Copyright Notice in lua.h
55*/
66
7#define lvm_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
13#include <limits.h>
814#include <stdio.h>
915#include <stdlib.h>
1016#include <string.h>
1117
12#define lvm_c
13#define LUA_CORE
14
1518#include "lua.h"
1619
1720#include "ldebug.h"
r242885r242886
2730#include "lvm.h"
2831
2932
33/*
34** You can define LUA_FLOORN2I if you want to convert floats to integers
35** by flooring them (instead of raising an error if they are not
36** integral values)
37*/
38#if !defined(LUA_FLOORN2I)
39#define LUA_FLOORN2I      0
40#endif
3041
42
3143/* limit for table tag-method chains (to avoid loops) */
32#define MAXTAGLOOP   100
44#define MAXTAGLOOP   2000
3345
3446
35const TValue *luaV_tonumber (const TValue *obj, TValue *n) {
36  lua_Number num;
37  if (ttisnumber(obj)) return obj;
38  if (ttisstring(obj) && luaO_str2d(svalue(obj), tsvalue(obj)->len, &num)) {
39    setnvalue(n, num);
40    return n;
47/*
48** Similar to 'tonumber', but does not attempt to convert strings and
49** ensure correct precision (no extra bits). Used in comparisons.
50*/
51static int tofloat (const TValue *obj, lua_Number *n) {
52  if (ttisfloat(obj)) *n = fltvalue(obj);
53  else if (ttisinteger(obj)) {
54    volatile lua_Number x = cast_num(ivalue(obj));  /* avoid extra precision */
55    *n = x;
4156  }
42  else
43    return NULL;
57  else {
58    *n = 0;  /* to avoid warnings */
59    return 0;
60  }
61  return 1;
4462}
4563
4664
47int luaV_tostring (lua_State *L, StkId obj) {
48  if (!ttisnumber(obj))
49    return 0;
50  else {
51    char s[LUAI_MAXNUMBER2STR];
52    lua_Number n = nvalue(obj);
53    int l = lua_number2str(s, n);
54    setsvalue2s(L, obj, luaS_newlstr(L, s, l));
65/*
66** Try to convert a value to a float. The float case is already handled
67** by the macro 'tonumber'.
68*/
69int luaV_tonumber_ (const TValue *obj, lua_Number *n) {
70  TValue v;
71  if (ttisinteger(obj)) {
72    *n = cast_num(ivalue(obj));
5573    return 1;
5674  }
75  else if (cvt2num(obj) &&  /* string convertible to number? */
76            luaO_str2num(svalue(obj), &v) == tsvalue(obj)->len + 1) {
77    *n = nvalue(&v);  /* convert result of 'luaO_str2num' to a float */
78    return 1;
79  }
80  else
81    return 0;  /* conversion failed */
5782}
5883
5984
60static void traceexec (lua_State *L) {
61  CallInfo *ci = L->ci;
62  lu_byte mask = L->hookmask;
63  int counthook = ((mask & LUA_MASKCOUNT) && L->hookcount == 0);
64  if (counthook)
65    resethookcount(L);  /* reset count */
66  if (ci->callstatus & CIST_HOOKYIELD) {  /* called hook last time? */
67    ci->callstatus &= ~CIST_HOOKYIELD;  /* erase mark */
68    return;  /* do not call hook again (VM yielded, so it did not move) */
85/*
86** try to convert a value to an integer, rounding according to 'mode':
87** mode == 0: accepts only integral values
88** mode == 1: takes the floor of the number
89** mode == 2: takes the ceil of the number
90*/
91static int tointeger_aux (const TValue *obj, lua_Integer *p, int mode) {
92  TValue v;
93 again:
94  if (ttisfloat(obj)) {
95    lua_Number n = fltvalue(obj);
96    lua_Number f = l_floor(n);
97    if (n != f) {  /* not an integral value? */
98      if (mode == 0) return 0;  /* fails if mode demands integral value */
99      else if (mode > 1)  /* needs ceil? */
100        f += 1;  /* convert floor to ceil (remember: n != f) */
101    }
102    return lua_numbertointeger(f, p);
69103  }
70  if (counthook)
71    luaD_hook(L, LUA_HOOKCOUNT, -1);  /* call count hook */
72  if (mask & LUA_MASKLINE) {
73    Proto *p = ci_func(ci)->p;
74    int npc = pcRel(ci->u.l.savedpc, p);
75    int newline = getfuncline(p, npc);
76    if (npc == 0 ||  /* call linehook when enter a new function, */
77        ci->u.l.savedpc <= L->oldpc ||  /* when jump back (loop), or when */
78        newline != getfuncline(p, pcRel(L->oldpc, p)))  /* enter a new line */
79      luaD_hook(L, LUA_HOOKLINE, newline);  /* call line hook */
104  else if (ttisinteger(obj)) {
105    *p = ivalue(obj);
106    return 1;
80107  }
81  L->oldpc = ci->u.l.savedpc;
82  if (L->status == LUA_YIELD) {  /* did hook yield? */
83    if (counthook)
84      L->hookcount = 1;  /* undo decrement to zero */
85    ci->u.l.savedpc--;  /* undo increment (resume will increment it again) */
86    ci->callstatus |= CIST_HOOKYIELD;  /* mark that it yielded */
87    ci->func = L->top - 1;  /* protect stack below results */
88    luaD_throw(L, LUA_YIELD);
108  else if (cvt2num(obj) &&
109            luaO_str2num(svalue(obj), &v) == tsvalue(obj)->len + 1) {
110    obj = &v;
111    goto again;  /* convert result from 'luaO_str2num' to an integer */
89112  }
113  return 0;  /* conversion failed */
90114}
91115
92116
93static void callTM (lua_State *L, const TValue *f, const TValue *p1,
94                    const TValue *p2, TValue *p3, int hasres) {
95  ptrdiff_t result = savestack(L, p3);
96  setobj2s(L, L->top++, f);  /* push function */
97  setobj2s(L, L->top++, p1);  /* 1st argument */
98  setobj2s(L, L->top++, p2);  /* 2nd argument */
99  if (!hasres)  /* no result? 'p3' is third argument */
100    setobj2s(L, L->top++, p3);  /* 3rd argument */
101  /* metamethod may yield only when called from Lua code */
102  luaD_call(L, L->top - (4 - hasres), hasres, isLua(L->ci));
103  if (hasres) {  /* if has result, move it to its place */
104    p3 = restorestack(L, result);
105    setobjs2s(L, p3, --L->top);
117/*
118** try to convert a value to an integer
119*/
120int luaV_tointeger_ (const TValue *obj, lua_Integer *p) {
121  return tointeger_aux(obj, p, LUA_FLOORN2I);
122}
123
124
125/*
126** Try to convert a 'for' limit to an integer, preserving the
127** semantics of the loop.
128** (The following explanation assumes a non-negative step; it is valid
129** for negative steps mutatis mutandis.)
130** If the limit can be converted to an integer, rounding down, that is
131** it.
132** Otherwise, check whether the limit can be converted to a number.  If
133** the number is too large, it is OK to set the limit as LUA_MAXINTEGER,
134** which means no limit.  If the number is too negative, the loop
135** should not run, because any initial integer value is larger than the
136** limit. So, it sets the limit to LUA_MININTEGER. 'stopnow' corrects
137** the extreme case when the initial value is LUA_MININTEGER, in which
138** case the LUA_MININTEGER limit would still run the loop once.
139*/
140static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step,
141                     int *stopnow) {
142  *stopnow = 0;  /* usually, let loops run */
143  if (!tointeger_aux(obj, p, (step < 0 ? 2 : 1))) {  /* not fit in integer? */
144    lua_Number n;  /* try to convert to float */
145    if (!tonumber(obj, &n)) /* cannot convert to float? */
146      return 0;  /* not a number */
147    if (n > 0) {  /* if true, float is larger than max integer */
148      *p = LUA_MAXINTEGER;
149      if (step < 0) *stopnow = 1;
150    }
151    else {  /* float is smaller than min integer */
152      *p = LUA_MININTEGER;
153      if (step >= 0) *stopnow = 1;
154    }
106155  }
156  return 1;
107157}
108158
109159
160/*
161** Main function for table access (invoking metamethods if needed).
162** Compute 'val = t[key]'
163*/
110164void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
111  int loop;
165  int loop;  /* counter to avoid infinite loops */
112166  for (loop = 0; loop < MAXTAGLOOP; loop++) {
113167    const TValue *tm;
114    if (ttistable(t)) {  /* `t' is a table? */
168    if (ttistable(t)) {  /* 't' is a table? */
115169      Table *h = hvalue(t);
116170      const TValue *res = luaH_get(h, key); /* do a primitive get */
117171      if (!ttisnil(res) ||  /* result is not nil? */
118172          (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */
119        setobj2s(L, val, res);
173        setobj2s(L, val, res);  /* result is the raw get */
120174        return;
121175      }
122      /* else will try the tag method */
176      /* else will try metamethod */
123177    }
124178    else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX)))
125      luaG_typeerror(L, t, "index");
126    if (ttisfunction(tm)) {
127      callTM(L, tm, t, key, val, 1);
179      luaG_typeerror(L, t, "index");  /* no metamethod */
180    if (ttisfunction(tm)) {  /* metamethod is a function */
181      luaT_callTM(L, tm, t, key, val, 1);
128182      return;
129183    }
130    t = tm;  /* else repeat with 'tm' */
184    t = tm;  /* else repeat access over 'tm' */
131185  }
132  luaG_runerror(L, "loop in gettable");
186  luaG_runerror(L, "gettable chain too long; possible loop");
133187}
134188
135189
190/*
191** Main function for table assignment (invoking metamethods if needed).
192** Compute 't[key] = val'
193*/
136194void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
137  int loop;
195  int loop;  /* counter to avoid infinite loops */
138196  for (loop = 0; loop < MAXTAGLOOP; loop++) {
139197    const TValue *tm;
140    if (ttistable(t)) {  /* `t' is a table? */
198    if (ttistable(t)) {  /* 't' is a table? */
141199      Table *h = hvalue(t);
142200      TValue *oldval = cast(TValue *, luaH_get(h, key));
143201      /* if previous value is not nil, there must be a previous entry
144         in the table; moreover, a metamethod has no relevance */
202         in the table; a metamethod has no relevance */
145203      if (!ttisnil(oldval) ||
146204         /* previous value is nil; must check the metamethod */
147205         ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL &&
r242885r242886
153211        /* no metamethod and (now) there is an entry with given key */
154212        setobj2t(L, oldval, val);  /* assign new value to that entry */
155213        invalidateTMcache(h);
156        luaC_barrierback(L, obj2gco(h), val);
214        luaC_barrierback(L, h, val);
157215        return;
158216      }
159217      /* else will try the metamethod */
r242885r242886
161219    else  /* not a table; check metamethod */
162220      if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
163221        luaG_typeerror(L, t, "index");
164    /* there is a metamethod */
222    /* try the metamethod */
165223    if (ttisfunction(tm)) {
166      callTM(L, tm, t, key, val, 0);
224      luaT_callTM(L, tm, t, key, val, 0);
167225      return;
168226    }
169    t = tm;  /* else repeat with 'tm' */
227    t = tm;  /* else repeat assignment over 'tm' */
170228  }
171  luaG_runerror(L, "loop in settable");
229  luaG_runerror(L, "settable chain too long; possible loop");
172230}
173231
174232
175static int call_binTM (lua_State *L, const TValue *p1, const TValue *p2,
176                       StkId res, TMS event) {
177  const TValue *tm = luaT_gettmbyobj(L, p1, event);  /* try first operand */
178  if (ttisnil(tm))
179    tm = luaT_gettmbyobj(L, p2, event);  /* try second operand */
180  if (ttisnil(tm)) return 0;
181  callTM(L, tm, p1, p2, res, 1);
182  return 1;
183}
184
185
186static const TValue *get_equalTM (lua_State *L, Table *mt1, Table *mt2,
187                                  TMS event) {
188  const TValue *tm1 = fasttm(L, mt1, event);
189  const TValue *tm2;
190  if (tm1 == NULL) return NULL;  /* no metamethod */
191  if (mt1 == mt2) return tm1;  /* same metatables => same metamethods */
192  tm2 = fasttm(L, mt2, event);
193  if (tm2 == NULL) return NULL;  /* no metamethod */
194  if (luaV_rawequalobj(tm1, tm2))  /* same metamethods? */
195    return tm1;
196  return NULL;
197}
198
199
200static int call_orderTM (lua_State *L, const TValue *p1, const TValue *p2,
201                         TMS event) {
202  if (!call_binTM(L, p1, p2, L->top, event))
203    return -1;  /* no metamethod */
204  else
205    return !l_isfalse(L->top);
206}
207
208
233/*
234** Compare two strings 'ls' x 'rs', returning an integer smaller-equal-
235** -larger than zero if 'ls' is smaller-equal-larger than 'rs'.
236** The code is a little tricky because it allows '\0' in the strings
237** and it uses 'strcoll' (to respect locales) for each segments
238** of the strings.
239*/
209240static int l_strcmp (const TString *ls, const TString *rs) {
210241  const char *l = getstr(ls);
211  size_t ll = ls->tsv.len;
242  size_t ll = ls->len;
212243  const char *r = getstr(rs);
213  size_t lr = rs->tsv.len;
214  for (;;) {
244  size_t lr = rs->len;
245  for (;;) {  /* for each segment */
215246    int temp = strcoll(l, r);
216    if (temp != 0) return temp;
217    else {  /* strings are equal up to a `\0' */
218      size_t len = strlen(l);  /* index of first `\0' in both strings */
219      if (len == lr)  /* r is finished? */
220        return (len == ll) ? 0 : 1;
221      else if (len == ll)  /* l is finished? */
222        return -1;  /* l is smaller than r (because r is not finished) */
223      /* both strings longer than `len'; go on comparing (after the `\0') */
247    if (temp != 0)  /* not equal? */
248      return temp;  /* done */
249    else {  /* strings are equal up to a '\0' */
250      size_t len = strlen(l);  /* index of first '\0' in both strings */
251      if (len == lr)  /* 'rs' is finished? */
252        return (len == ll) ? 0 : 1;  /* check 'ls' */
253      else if (len == ll)  /* 'ls' is finished? */
254        return -1;  /* 'ls' is smaller than 'rs' ('rs' is not finished) */
255      /* both strings longer than 'len'; go on comparing after the '\0' */
224256      len++;
225257      l += len; ll -= len; r += len; lr -= len;
226258    }
r242885r242886
228260}
229261
230262
263/*
264** Main operation less than; return 'l < r'.
265*/
231266int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
232267  int res;
233  if (ttisnumber(l) && ttisnumber(r))
234    return luai_numlt(L, nvalue(l), nvalue(r));
235  else if (ttisstring(l) && ttisstring(r))
236    return l_strcmp(rawtsvalue(l), rawtsvalue(r)) < 0;
237  else if ((res = call_orderTM(L, l, r, TM_LT)) < 0)
238    luaG_ordererror(L, l, r);
268  lua_Number nl, nr;
269  if (ttisinteger(l) && ttisinteger(r))  /* both operands are integers? */
270    return (ivalue(l) < ivalue(r));
271  else if (tofloat(l, &nl) && tofloat(r, &nr))  /* both are numbers? */
272    return luai_numlt(nl, nr);
273  else if (ttisstring(l) && ttisstring(r))  /* both are strings? */
274    return l_strcmp(tsvalue(l), tsvalue(r)) < 0;
275  else if ((res = luaT_callorderTM(L, l, r, TM_LT)) < 0)  /* no metamethod? */
276    luaG_ordererror(L, l, r);  /* error */
239277  return res;
240278}
241279
242280
281/*
282** Main operation less than or equal to; return 'l <= r'.
283*/
243284int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
244285  int res;
245  if (ttisnumber(l) && ttisnumber(r))
246    return luai_numle(L, nvalue(l), nvalue(r));
247  else if (ttisstring(l) && ttisstring(r))
248    return l_strcmp(rawtsvalue(l), rawtsvalue(r)) <= 0;
249  else if ((res = call_orderTM(L, l, r, TM_LE)) >= 0)  /* first try `le' */
286  lua_Number nl, nr;
287  if (ttisinteger(l) && ttisinteger(r))  /* both operands are integers? */
288    return (ivalue(l) <= ivalue(r));
289  else if (tofloat(l, &nl) && tofloat(r, &nr))  /* both are numbers? */
290    return luai_numle(nl, nr);
291  else if (ttisstring(l) && ttisstring(r))  /* both are strings? */
292    return l_strcmp(tsvalue(l), tsvalue(r)) <= 0;
293  else if ((res = luaT_callorderTM(L, l, r, TM_LE)) >= 0)  /* first try 'le' */
250294    return res;
251  else if ((res = call_orderTM(L, r, l, TM_LT)) < 0)  /* else try `lt' */
295  else if ((res = luaT_callorderTM(L, r, l, TM_LT)) < 0)  /* else try 'lt' */
252296    luaG_ordererror(L, l, r);
253297  return !res;
254298}
255299
256300
257301/*
258** equality of Lua values. L == NULL means raw equality (no metamethods)
302** Main operation for equality of Lua values; return 't1 == t2'.
303** L == NULL means raw equality (no metamethods)
259304*/
260int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2) {
305int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
261306  const TValue *tm;
262  lua_assert(ttisequal(t1, t2));
307  if (ttype(t1) != ttype(t2)) {  /* not the same variant? */
308    if (ttnov(t1) != ttnov(t2) || ttnov(t1) != LUA_TNUMBER)
309      return 0;  /* only numbers can be equal with different variants */
310    else {  /* two numbers with different variants */
311      lua_Number n1, n2;  /* compare them as floats */
312      lua_assert(ttisnumber(t1) && ttisnumber(t2));
313      cast_void(tofloat(t1, &n1)); cast_void(tofloat(t2, &n2));
314      return luai_numeq(n1, n2);
315    }
316  }
317  /* values have same type and same variant */
263318  switch (ttype(t1)) {
264319    case LUA_TNIL: return 1;
265    case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
320    case LUA_TNUMINT: return (ivalue(t1) == ivalue(t2));
321    case LUA_TNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2));
266322    case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2);  /* true must be 1 !! */
267323    case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
268324    case LUA_TLCF: return fvalue(t1) == fvalue(t2);
269    case LUA_TSHRSTR: return eqshrstr(rawtsvalue(t1), rawtsvalue(t2));
270    case LUA_TLNGSTR: return luaS_eqlngstr(rawtsvalue(t1), rawtsvalue(t2));
325    case LUA_TSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2));
326    case LUA_TLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2));
271327    case LUA_TUSERDATA: {
272328      if (uvalue(t1) == uvalue(t2)) return 1;
273329      else if (L == NULL) return 0;
274      tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);
330      tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);
331      if (tm == NULL)
332        tm = fasttm(L, uvalue(t2)->metatable, TM_EQ);
275333      break;  /* will try TM */
276334    }
277335    case LUA_TTABLE: {
278336      if (hvalue(t1) == hvalue(t2)) return 1;
279337      else if (L == NULL) return 0;
280      tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
338      tm = fasttm(L, hvalue(t1)->metatable, TM_EQ);
339      if (tm == NULL)
340        tm = fasttm(L, hvalue(t2)->metatable, TM_EQ);
281341      break;  /* will try TM */
282342    }
283343    default:
284      lua_assert(iscollectable(t1));
285344      return gcvalue(t1) == gcvalue(t2);
286345  }
287  if (tm == NULL) return 0;  /* no TM? */
288  callTM(L, tm, t1, t2, L->top, 1);  /* call TM */
346  if (tm == NULL)  /* no TM? */
347    return 0;  /* objects are different */
348  luaT_callTM(L, tm, t1, t2, L->top, 1);  /* call TM */
289349  return !l_isfalse(L->top);
290350}
291351
292352
353/* macro used by 'luaV_concat' to ensure that element at 'o' is a string */
354#define tostring(L,o)  \
355   (ttisstring(o) || (cvt2str(o) && (luaO_tostring(L, o), 1)))
356
357/*
358** Main operation for concatenation: concat 'total' values in the stack,
359** from 'L->top - total' up to 'L->top - 1'.
360*/
293361void luaV_concat (lua_State *L, int total) {
294362  lua_assert(total >= 2);
295363  do {
296364    StkId top = L->top;
297365    int n = 2;  /* number of elements handled in this pass (at least 2) */
298    if (!(ttisstring(top-2) || ttisnumber(top-2)) || !tostring(L, top-1)) {
299      if (!call_binTM(L, top-2, top-1, top-2, TM_CONCAT))
300        luaG_concaterror(L, top-2, top-1);
301    }
366    if (!(ttisstring(top-2) || cvt2str(top-2)) || !tostring(L, top-1))
367      luaT_trybinTM(L, top-2, top-1, top-2, TM_CONCAT);
302368    else if (tsvalue(top-1)->len == 0)  /* second operand is empty? */
303      (void)tostring(L, top - 2);  /* result is first operand */
369      cast_void(tostring(L, top - 2));  /* result is first operand */
304370    else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) {
305371      setobjs2s(L, top - 2, top - 1);  /* result is second op. */
306372    }
r242885r242886
312378      /* collect total length */
313379      for (i = 1; i < total && tostring(L, top-i-1); i++) {
314380        size_t l = tsvalue(top-i-1)->len;
315        if (l >= (MAX_SIZET/sizeof(char)) - tl)
381        if (l >= (MAX_SIZE/sizeof(char)) - tl)
316382          luaG_runerror(L, "string length overflow");
317383        tl += l;
318384      }
319385      buffer = luaZ_openspace(L, &G(L)->buff, tl);
320386      tl = 0;
321387      n = i;
322      do {  /* concat all strings */
388      do {  /* copy all strings to buffer */
323389        size_t l = tsvalue(top-i)->len;
324390        memcpy(buffer+tl, svalue(top-i), l * sizeof(char));
325391        tl += l;
326392      } while (--i > 0);
327      setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
393      setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));  /* create result */
328394    }
329395    total -= n-1;  /* got 'n' strings to create 1 new */
330396    L->top -= n-1;  /* popped 'n' strings and pushed one */
r242885r242886
332398}
333399
334400
401/*
402** Main operation 'ra' = #rb'.
403*/
335404void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
336405  const TValue *tm;
337  switch (ttypenv(rb)) {
406  switch (ttnov(rb)) {
338407    case LUA_TTABLE: {
339408      Table *h = hvalue(rb);
340409      tm = fasttm(L, h->metatable, TM_LEN);
341410      if (tm) break;  /* metamethod? break switch to call it */
342      setnvalue(ra, cast_num(1.0*luaH_getn(h)));  /* else primitive len */
411      setivalue(ra, luaH_getn(h));  /* else primitive len */
343412      return;
344413    }
345414    case LUA_TSTRING: {
346      setnvalue(ra, cast_num(tsvalue(rb)->len));
415      setivalue(ra, tsvalue(rb)->len);
347416      return;
348417    }
349418    default: {  /* try metamethod */
r242885r242886
353422      break;
354423    }
355424  }
356  callTM(L, tm, rb, rb, ra, 1);
425  luaT_callTM(L, tm, rb, rb, ra, 1);
357426}
358427
359428
360void luaV_arith (lua_State *L, StkId ra, const TValue *rb,
361                 const TValue *rc, TMS op) {
362  TValue tempb, tempc;
363  const TValue *b, *c;
364  if ((b = luaV_tonumber(rb, &tempb)) != NULL &&
365      (c = luaV_tonumber(rc, &tempc)) != NULL) {
366    lua_Number res = luaO_arith(op - TM_ADD + LUA_OPADD, nvalue(b), nvalue(c));
367    setnvalue(ra, res);
429/*
430** Integer division; return 'm // n', that is, floor(m/n).
431** C division truncates its result (rounds towards zero).
432** 'floor(q) == trunc(q)' when 'q >= 0' or when 'q' is integer,
433** otherwise 'floor(q) == trunc(q) - 1'.
434*/
435lua_Integer luaV_div (lua_State *L, lua_Integer m, lua_Integer n) {
436  if (l_castS2U(n) + 1u <= 1u) {  /* special cases: -1 or 0 */
437    if (n == 0)
438      luaG_runerror(L, "attempt to divide by zero");
439    return intop(-, 0, m);   /* n==-1; avoid overflow with 0x80000...//-1 */
368440  }
369  else if (!call_binTM(L, rb, rc, ra, op))
370    luaG_aritherror(L, rb, rc);
441  else {
442    lua_Integer q = m / n;  /* perform C division */
443    if ((m ^ n) < 0 && m % n != 0)  /* 'm/n' would be negative non-integer? */
444      q -= 1;  /* correct result for different rounding */
445    return q;
446  }
371447}
372448
373449
374450/*
451** Integer modulus; return 'm % n'. (Assume that C '%' with
452** negative operands follows C99 behavior. See previous comment
453** about luaV_div.)
454*/
455lua_Integer luaV_mod (lua_State *L, lua_Integer m, lua_Integer n) {
456  if (l_castS2U(n) + 1u <= 1u) {  /* special cases: -1 or 0 */
457    if (n == 0)
458      luaG_runerror(L, "attempt to perform 'n%%0'");
459    return 0;   /* m % -1 == 0; avoid overflow with 0x80000...%-1 */
460  }
461  else {
462    lua_Integer r = m % n;
463    if (r != 0 && (m ^ n) < 0)  /* 'm/n' would be non-integer negative? */
464      r += n;  /* correct result for different rounding */
465    return r;
466  }
467}
468
469
470/* number of bits in an integer */
471#define NBITS   cast_int(sizeof(lua_Integer) * CHAR_BIT)
472
473/*
474** Shift left operation. (Shift right just negates 'y'.)
475*/
476lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y) {
477  if (y < 0) {  /* shift right? */
478    if (y <= -NBITS) return 0;
479    else return intop(>>, x, -y);
480  }
481  else {  /* shift left */
482    if (y >= NBITS) return 0;
483    else return intop(<<, x, y);
484  }
485}
486
487
488/*
375489** check whether cached closure in prototype 'p' may be reused, that is,
376490** whether there is a cached closure with the same upvalues needed by
377491** new closure to be created.
378492*/
379static Closure *getcached (Proto *p, UpVal **encup, StkId base) {
380  Closure *c = p->cache;
493static LClosure *getcached (Proto *p, UpVal **encup, StkId base) {
494  LClosure *c = p->cache;
381495  if (c != NULL) {  /* is there a cached closure? */
382496    int nup = p->sizeupvalues;
383497    Upvaldesc *uv = p->upvalues;
384498    int i;
385499    for (i = 0; i < nup; i++) {  /* check whether it has right upvalues */
386500      TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v;
387      if (c->l.upvals[i]->v != v)
501      if (c->upvals[i]->v != v)
388502        return NULL;  /* wrong upvalue; cannot reuse closure */
389503    }
390504  }
r242885r242886
394508
395509/*
396510** create a new Lua closure, push it in the stack, and initialize
397** its upvalues. Note that the call to 'luaC_barrierproto' must come
398** before the assignment to 'p->cache', as the function needs the
399** original value of that field.
511** its upvalues. Note that the closure is not cached if prototype is
512** already black (which means that 'cache' was already cleared by the
513** GC).
400514*/
401515static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
402516                         StkId ra) {
403517  int nup = p->sizeupvalues;
404518  Upvaldesc *uv = p->upvalues;
405519  int i;
406  Closure *ncl = luaF_newLclosure(L, nup);
407  ncl->l.p = p;
520  LClosure *ncl = luaF_newLclosure(L, nup);
521  ncl->p = p;
408522  setclLvalue(L, ra, ncl);  /* anchor new closure in stack */
409523  for (i = 0; i < nup; i++) {  /* fill in its upvalues */
410524    if (uv[i].instack)  /* upvalue refers to local variable? */
411      ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx);
525      ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx);
412526    else  /* get upvalue from enclosing function */
413      ncl->l.upvals[i] = encup[uv[i].idx];
527      ncl->upvals[i] = encup[uv[i].idx];
528    ncl->upvals[i]->refcount++;
529    /* new closure is white, so we do not need a barrier here */
414530  }
415  luaC_barrierproto(L, p, ncl);
416  p->cache = ncl;  /* save it on cache for reuse */
531  if (!isblack(p))  /* cache will not break GC invariant? */
532    p->cache = ncl;  /* save it on cache for reuse */
417533}
418534
419535
r242885r242886
426542  Instruction inst = *(ci->u.l.savedpc - 1);  /* interrupted instruction */
427543  OpCode op = GET_OPCODE(inst);
428544  switch (op) {  /* finish its execution */
429    case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV:
430    case OP_MOD: case OP_POW: case OP_UNM: case OP_LEN:
545    case OP_ADD: case OP_SUB: case OP_MUL: case OP_DIV: case OP_IDIV:
546    case OP_BAND: case OP_BOR: case OP_BXOR: case OP_SHL: case OP_SHR:
547    case OP_MOD: case OP_POW:
548    case OP_UNM: case OP_BNOT: case OP_LEN:
431549    case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: {
432550      setobjs2s(L, base + GETARG_A(inst), --L->top);
433551      break;
r242885r242886
446564      break;
447565    }
448566    case OP_CONCAT: {
449      StkId top = L->top - 1;  /* top when 'call_binTM' was called */
567      StkId top = L->top - 1;  /* top when 'luaT_trybinTM' was called */
450568      int b = GETARG_B(inst);      /* first element to concatenate */
451569      int total = cast_int(top - 1 - (base + b));  /* yet to concatenate */
452570      setobj2s(L, top - 2, top);  /* put TM result in proper position */
r242885r242886
477595
478596
479597
598
480599/*
481** some macros for common tasks in `luaV_execute'
600** {==================================================================
601** Function 'luaV_execute': main interpreter loop
602** ===================================================================
482603*/
483604
605
606/*
607** some macros for common tasks in 'luaV_execute'
608*/
609
484610#if !defined luai_runtimecheck
485611#define luai_runtimecheck(L, c)      /* void */
486612#endif
r242885r242886
517643           luai_threadyield(L); )
518644
519645
520#define arith_op(op,tm) { \
521        TValue *rb = RKB(i); \
522        TValue *rc = RKC(i); \
523        if (ttisnumber(rb) && ttisnumber(rc)) { \
524          lua_Number nb = nvalue(rb), nc = nvalue(rc); \
525          setnvalue(ra, op(L, nb, nc)); \
526        } \
527        else { Protect(luaV_arith(L, ra, rb, rc, tm)); } }
528
529
530646#define vmdispatch(o)   switch(o)
531#define vmcase(l,b)   case l: {b}  break;
532#define vmcasenb(l,b)   case l: {b}      /* nb = no break */
647#define vmcase(l)   case l:
648#define vmbreak      break
533649
534650void luaV_execute (lua_State *L) {
535651  CallInfo *ci = L->ci;
r242885r242886
547663    StkId ra;
548664    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
549665        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
550      Protect(traceexec(L));
666      Protect(luaG_traceexec(L));
551667    }
552    /* WARNING: several calls may realloc the stack and invalidate `ra' */
668    /* WARNING: several calls may realloc the stack and invalidate 'ra' */
553669    ra = RA(i);
554670    lua_assert(base == ci->u.l.base);
555671    lua_assert(base <= L->top && L->top < L->stack + L->stacksize);
556672    vmdispatch (GET_OPCODE(i)) {
557      vmcase(OP_MOVE,
673      vmcase(OP_MOVE) {
558674        setobjs2s(L, ra, RB(i));
559      )
560      vmcase(OP_LOADK,
675        vmbreak;
676      }
677      vmcase(OP_LOADK) {
561678        TValue *rb = k + GETARG_Bx(i);
562679        setobj2s(L, ra, rb);
563      )
564      vmcase(OP_LOADKX,
680        vmbreak;
681      }
682      vmcase(OP_LOADKX) {
565683        TValue *rb;
566684        lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
567685        rb = k + GETARG_Ax(*ci->u.l.savedpc++);
568686        setobj2s(L, ra, rb);
569      )
570      vmcase(OP_LOADBOOL,
687        vmbreak;
688      }
689      vmcase(OP_LOADBOOL) {
571690        setbvalue(ra, GETARG_B(i));
572691        if (GETARG_C(i)) ci->u.l.savedpc++;  /* skip next instruction (if C) */
573      )
574      vmcase(OP_LOADNIL,
692        vmbreak;
693      }
694      vmcase(OP_LOADNIL) {
575695        int b = GETARG_B(i);
576696        do {
577697          setnilvalue(ra++);
578698        } while (b--);
579      )
580      vmcase(OP_GETUPVAL,
699        vmbreak;
700      }
701      vmcase(OP_GETUPVAL) {
581702        int b = GETARG_B(i);
582703        setobj2s(L, ra, cl->upvals[b]->v);
583      )
584      vmcase(OP_GETTABUP,
704        vmbreak;
705      }
706      vmcase(OP_GETTABUP) {
585707        int b = GETARG_B(i);
586708        Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra));
587      )
588      vmcase(OP_GETTABLE,
709        vmbreak;
710      }
711      vmcase(OP_GETTABLE) {
589712        Protect(luaV_gettable(L, RB(i), RKC(i), ra));
590      )
591      vmcase(OP_SETTABUP,
713        vmbreak;
714      }
715      vmcase(OP_SETTABUP) {
592716        int a = GETARG_A(i);
593717        Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i)));
594      )
595      vmcase(OP_SETUPVAL,
718        vmbreak;
719      }
720      vmcase(OP_SETUPVAL) {
596721        UpVal *uv = cl->upvals[GETARG_B(i)];
597722        setobj(L, uv->v, ra);
598        luaC_barrier(L, uv, ra);
599      )
600      vmcase(OP_SETTABLE,
723        luaC_upvalbarrier(L, uv);
724        vmbreak;
725      }
726      vmcase(OP_SETTABLE) {
601727        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
602      )
603      vmcase(OP_NEWTABLE,
728        vmbreak;
729      }
730      vmcase(OP_NEWTABLE) {
604731        int b = GETARG_B(i);
605732        int c = GETARG_C(i);
606733        Table *t = luaH_new(L);
r242885r242886
608735        if (b != 0 || c != 0)
609736          luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));
610737        checkGC(L, ra + 1);
611      )
612      vmcase(OP_SELF,
738        vmbreak;
739      }
740      vmcase(OP_SELF) {
613741        StkId rb = RB(i);
614742        setobjs2s(L, ra+1, rb);
615743        Protect(luaV_gettable(L, rb, RKC(i), ra));
616      )
617      vmcase(OP_ADD,
618        arith_op(luai_numadd, TM_ADD);
619      )
620      vmcase(OP_SUB,
621        arith_op(luai_numsub, TM_SUB);
622      )
623      vmcase(OP_MUL,
624        arith_op(luai_nummul, TM_MUL);
625      )
626      vmcase(OP_DIV,
627        arith_op(luai_numdiv, TM_DIV);
628      )
629      vmcase(OP_MOD,
630        arith_op(luai_nummod, TM_MOD);
631      )
632      vmcase(OP_POW,
633        arith_op(luai_numpow, TM_POW);
634      )
635      vmcase(OP_UNM,
744        vmbreak;
745      }
746      vmcase(OP_ADD) {
747        TValue *rb = RKB(i);
748        TValue *rc = RKC(i);
749        lua_Number nb; lua_Number nc;
750        if (ttisinteger(rb) && ttisinteger(rc)) {
751          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
752          setivalue(ra, intop(+, ib, ic));
753        }
754        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
755          setfltvalue(ra, luai_numadd(L, nb, nc));
756        }
757        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_ADD)); }
758        vmbreak;
759      }
760      vmcase(OP_SUB) {
761        TValue *rb = RKB(i);
762        TValue *rc = RKC(i);
763        lua_Number nb; lua_Number nc;
764        if (ttisinteger(rb) && ttisinteger(rc)) {
765          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
766          setivalue(ra, intop(-, ib, ic));
767        }
768        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
769          setfltvalue(ra, luai_numsub(L, nb, nc));
770        }
771        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SUB)); }
772        vmbreak;
773      }
774      vmcase(OP_MUL) {
775        TValue *rb = RKB(i);
776        TValue *rc = RKC(i);
777        lua_Number nb; lua_Number nc;
778        if (ttisinteger(rb) && ttisinteger(rc)) {
779          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
780          setivalue(ra, intop(*, ib, ic));
781        }
782        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
783          setfltvalue(ra, luai_nummul(L, nb, nc));
784        }
785        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MUL)); }
786        vmbreak;
787      }
788      vmcase(OP_DIV) {  /* float division (always with floats) */
789        TValue *rb = RKB(i);
790        TValue *rc = RKC(i);
791        lua_Number nb; lua_Number nc;
792        if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
793          setfltvalue(ra, luai_numdiv(L, nb, nc));
794        }
795        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_DIV)); }
796        vmbreak;
797      }
798      vmcase(OP_BAND) {
799        TValue *rb = RKB(i);
800        TValue *rc = RKC(i);
801        lua_Integer ib; lua_Integer ic;
802        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
803          setivalue(ra, intop(&, ib, ic));
804        }
805        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BAND)); }
806        vmbreak;
807      }
808      vmcase(OP_BOR) {
809        TValue *rb = RKB(i);
810        TValue *rc = RKC(i);
811        lua_Integer ib; lua_Integer ic;
812        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
813          setivalue(ra, intop(|, ib, ic));
814        }
815        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BOR)); }
816        vmbreak;
817      }
818      vmcase(OP_BXOR) {
819        TValue *rb = RKB(i);
820        TValue *rc = RKC(i);
821        lua_Integer ib; lua_Integer ic;
822        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
823          setivalue(ra, intop(^, ib, ic));
824        }
825        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_BXOR)); }
826        vmbreak;
827      }
828      vmcase(OP_SHL) {
829        TValue *rb = RKB(i);
830        TValue *rc = RKC(i);
831        lua_Integer ib; lua_Integer ic;
832        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
833          setivalue(ra, luaV_shiftl(ib, ic));
834        }
835        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHL)); }
836        vmbreak;
837      }
838      vmcase(OP_SHR) {
839        TValue *rb = RKB(i);
840        TValue *rc = RKC(i);
841        lua_Integer ib; lua_Integer ic;
842        if (tointeger(rb, &ib) && tointeger(rc, &ic)) {
843          setivalue(ra, luaV_shiftl(ib, -ic));
844        }
845        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_SHR)); }
846        vmbreak;
847      }
848      vmcase(OP_MOD) {
849        TValue *rb = RKB(i);
850        TValue *rc = RKC(i);
851        lua_Number nb; lua_Number nc;
852        if (ttisinteger(rb) && ttisinteger(rc)) {
853          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
854          setivalue(ra, luaV_mod(L, ib, ic));
855        }
856        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
857          lua_Number m;
858          luai_nummod(L, nb, nc, m);
859          setfltvalue(ra, m);
860        }
861        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_MOD)); }
862        vmbreak;
863      }
864      vmcase(OP_IDIV) {  /* floor division */
865        TValue *rb = RKB(i);
866        TValue *rc = RKC(i);
867        lua_Number nb; lua_Number nc;
868        if (ttisinteger(rb) && ttisinteger(rc)) {
869          lua_Integer ib = ivalue(rb); lua_Integer ic = ivalue(rc);
870          setivalue(ra, luaV_div(L, ib, ic));
871        }
872        else if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
873          setfltvalue(ra, luai_numidiv(L, nb, nc));
874        }
875        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_IDIV)); }
876        vmbreak;
877      }
878      vmcase(OP_POW) {
879        TValue *rb = RKB(i);
880        TValue *rc = RKC(i);
881        lua_Number nb; lua_Number nc;
882        if (tonumber(rb, &nb) && tonumber(rc, &nc)) {
883          setfltvalue(ra, luai_numpow(L, nb, nc));
884        }
885        else { Protect(luaT_trybinTM(L, rb, rc, ra, TM_POW)); }
886        vmbreak;
887      }
888      vmcase(OP_UNM) {
636889        TValue *rb = RB(i);
637        if (ttisnumber(rb)) {
638          lua_Number nb = nvalue(rb);
639          setnvalue(ra, luai_numunm(L, nb));
890        lua_Number nb;
891        if (ttisinteger(rb)) {
892          lua_Integer ib = ivalue(rb);
893          setivalue(ra, intop(-, 0, ib));
640894        }
895        else if (tonumber(rb, &nb)) {
896          setfltvalue(ra, luai_numunm(L, nb));
897        }
641898        else {
642          Protect(luaV_arith(L, ra, rb, rb, TM_UNM));
899          Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
643900        }
644      )
645      vmcase(OP_NOT,
901        vmbreak;
902      }
903      vmcase(OP_BNOT) {
646904        TValue *rb = RB(i);
905        lua_Integer ib;
906        if (tointeger(rb, &ib)) {
907          setivalue(ra, intop(^, ~l_castS2U(0), ib));
908        }
909        else {
910          Protect(luaT_trybinTM(L, rb, rb, ra, TM_BNOT));
911        }
912        vmbreak;
913      }
914      vmcase(OP_NOT) {
915        TValue *rb = RB(i);
647916        int res = l_isfalse(rb);  /* next assignment may change this value */
648917        setbvalue(ra, res);
649      )
650      vmcase(OP_LEN,
918        vmbreak;
919      }
920      vmcase(OP_LEN) {
651921        Protect(luaV_objlen(L, ra, RB(i)));
652      )
653      vmcase(OP_CONCAT,
922        vmbreak;
923      }
924      vmcase(OP_CONCAT) {
654925        int b = GETARG_B(i);
655926        int c = GETARG_C(i);
656927        StkId rb;
r242885r242886
661932        setobjs2s(L, ra, rb);
662933        checkGC(L, (ra >= rb ? ra + 1 : rb));
663934        L->top = ci->top;  /* restore top */
664      )
665      vmcase(OP_JMP,
935        vmbreak;
936      }
937      vmcase(OP_JMP) {
666938        dojump(ci, i, 0);
667      )
668      vmcase(OP_EQ,
939        vmbreak;
940      }
941      vmcase(OP_EQ) {
669942        TValue *rb = RKB(i);
670943        TValue *rc = RKC(i);
671944        Protect(
672          if (cast_int(equalobj(L, rb, rc)) != GETARG_A(i))
945          if (cast_int(luaV_equalobj(L, rb, rc)) != GETARG_A(i))
673946            ci->u.l.savedpc++;
674947          else
675948            donextjump(ci);
676949        )
677      )
678      vmcase(OP_LT,
950        vmbreak;
951      }
952      vmcase(OP_LT) {
679953        Protect(
680954          if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))
681955            ci->u.l.savedpc++;
682956          else
683957            donextjump(ci);
684958        )
685      )
686      vmcase(OP_LE,
959        vmbreak;
960      }
961      vmcase(OP_LE) {
687962        Protect(
688963          if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))
689964            ci->u.l.savedpc++;
690965          else
691966            donextjump(ci);
692967        )
693      )
694      vmcase(OP_TEST,
968        vmbreak;
969      }
970      vmcase(OP_TEST) {
695971        if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))
696972            ci->u.l.savedpc++;
697973          else
698974          donextjump(ci);
699      )
700      vmcase(OP_TESTSET,
975        vmbreak;
976      }
977      vmcase(OP_TESTSET) {
701978        TValue *rb = RB(i);
702979        if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))
703980          ci->u.l.savedpc++;
r242885r242886
705982          setobjs2s(L, ra, rb);
706983          donextjump(ci);
707984        }
708      )
709      vmcase(OP_CALL,
985        vmbreak;
986      }
987      vmcase(OP_CALL) {
710988        int b = GETARG_B(i);
711989        int nresults = GETARG_C(i) - 1;
712990        if (b != 0) L->top = ra+b;  /* else previous instruction set top */
r242885r242886
719997          ci->callstatus |= CIST_REENTRY;
720998          goto newframe;  /* restart luaV_execute over new Lua function */
721999        }
722      )
723      vmcase(OP_TAILCALL,
1000        vmbreak;
1001      }
1002      vmcase(OP_TAILCALL) {
7241003        int b = GETARG_B(i);
7251004        if (b != 0) L->top = ra+b;  /* else previous instruction set top */
7261005        lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
r242885r242886
7481027          lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize);
7491028          goto newframe;  /* restart luaV_execute over new Lua function */
7501029        }
751      )
752      vmcasenb(OP_RETURN,
1030        vmbreak;
1031      }
1032      vmcase(OP_RETURN) {
7531033        int b = GETARG_B(i);
7541034        if (b != 0) L->top = ra+b-1;
7551035        if (cl->p->sizep > 0) luaF_close(L, base);
r242885r242886
7631043          lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL);
7641044          goto newframe;  /* restart luaV_execute over new Lua function */
7651045        }
766      )
767      vmcase(OP_FORLOOP,
768        lua_Number step = nvalue(ra+2);
769        lua_Number idx = luai_numadd(L, nvalue(ra), step); /* increment index */
770        lua_Number limit = nvalue(ra+1);
771        if (luai_numlt(L, 0, step) ? luai_numle(L, idx, limit)
772                                   : luai_numle(L, limit, idx)) {
773          ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */
774          setnvalue(ra, idx);  /* update internal index... */
775          setnvalue(ra+3, idx);  /* ...and external index */
1046      }
1047      vmcase(OP_FORLOOP) {
1048        if (ttisinteger(ra)) {  /* integer loop? */
1049          lua_Integer step = ivalue(ra + 2);
1050          lua_Integer idx = ivalue(ra) + step; /* increment index */
1051          lua_Integer limit = ivalue(ra + 1);
1052          if ((0 < step) ? (idx <= limit) : (limit <= idx)) {
1053            ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */
1054            setivalue(ra, idx);  /* update internal index... */
1055            setivalue(ra + 3, idx);  /* ...and external index */
1056          }
7761057        }
777      )
778      vmcase(OP_FORPREP,
779        const TValue *init = ra;
780        const TValue *plimit = ra+1;
781        const TValue *pstep = ra+2;
782        if (!tonumber(init, ra))
783          luaG_runerror(L, LUA_QL("for") " initial value must be a number");
784        else if (!tonumber(plimit, ra+1))
785          luaG_runerror(L, LUA_QL("for") " limit must be a number");
786        else if (!tonumber(pstep, ra+2))
787          luaG_runerror(L, LUA_QL("for") " step must be a number");
788        setnvalue(ra, luai_numsub(L, nvalue(ra), nvalue(pstep)));
1058        else {  /* floating loop */
1059          lua_Number step = fltvalue(ra + 2);
1060          lua_Number idx = luai_numadd(L, fltvalue(ra), step); /* inc. index */
1061          lua_Number limit = fltvalue(ra + 1);
1062          if (luai_numlt(0, step) ? luai_numle(idx, limit)
1063                                  : luai_numle(limit, idx)) {
1064            ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */
1065            setfltvalue(ra, idx);  /* update internal index... */
1066            setfltvalue(ra + 3, idx);  /* ...and external index */
1067          }
1068        }
1069        vmbreak;
1070      }
1071      vmcase(OP_FORPREP) {
1072        TValue *init = ra;
1073        TValue *plimit = ra + 1;
1074        TValue *pstep = ra + 2;
1075        lua_Integer ilimit;
1076        int stopnow;
1077        if (ttisinteger(init) && ttisinteger(pstep) &&
1078            forlimit(plimit, &ilimit, ivalue(pstep), &stopnow)) {
1079          /* all values are integer */
1080          lua_Integer initv = (stopnow ? 0 : ivalue(init));
1081          setivalue(plimit, ilimit);
1082          setivalue(init, initv - ivalue(pstep));
1083        }
1084        else {  /* try making all values floats */
1085          lua_Number ninit; lua_Number nlimit; lua_Number nstep;
1086          if (!tonumber(plimit, &nlimit))
1087            luaG_runerror(L, "'for' limit must be a number");
1088          setfltvalue(plimit, nlimit);
1089          if (!tonumber(pstep, &nstep))
1090            luaG_runerror(L, "'for' step must be a number");
1091          setfltvalue(pstep, nstep);
1092          if (!tonumber(init, &ninit))
1093            luaG_runerror(L, "'for' initial value must be a number");
1094          setfltvalue(init, luai_numsub(L, ninit, nstep));
1095        }
7891096        ci->u.l.savedpc += GETARG_sBx(i);
790      )
791      vmcasenb(OP_TFORCALL,
1097        vmbreak;
1098      }
1099      vmcase(OP_TFORCALL) {
7921100        StkId cb = ra + 3;  /* call base */
7931101        setobjs2s(L, cb+2, ra+2);
7941102        setobjs2s(L, cb+1, ra+1);
r242885r242886
8001108        ra = RA(i);
8011109        lua_assert(GET_OPCODE(i) == OP_TFORLOOP);
8021110        goto l_tforloop;
803      )
804      vmcase(OP_TFORLOOP,
1111      }
1112      vmcase(OP_TFORLOOP) {
8051113        l_tforloop:
8061114        if (!ttisnil(ra + 1)) {  /* continue loop? */
8071115          setobjs2s(L, ra, ra + 1);  /* save control variable */
8081116           ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */
8091117        }
810      )
811      vmcase(OP_SETLIST,
1118        vmbreak;
1119      }
1120      vmcase(OP_SETLIST) {
8121121        int n = GETARG_B(i);
8131122        int c = GETARG_C(i);
814        int last;
1123        unsigned int last;
8151124        Table *h;
8161125        if (n == 0) n = cast_int(L->top - ra) - 1;
8171126        if (c == 0) {
r242885r242886
8261135        for (; n > 0; n--) {
8271136          TValue *val = ra+n;
8281137          luaH_setint(L, h, last--, val);
829          luaC_barrierback(L, obj2gco(h), val);
1138          luaC_barrierback(L, h, val);
8301139        }
8311140        L->top = ci->top;  /* correct top (in case of previous open call) */
832      )
833      vmcase(OP_CLOSURE,
1141        vmbreak;
1142      }
1143      vmcase(OP_CLOSURE) {
8341144        Proto *p = cl->p->p[GETARG_Bx(i)];
835        Closure *ncl = getcached(p, cl->upvals, base);  /* cached closure */
1145        LClosure *ncl = getcached(p, cl->upvals, base);  /* cached closure */
8361146        if (ncl == NULL)  /* no match? */
8371147          pushclosure(L, p, cl->upvals, base, ra);  /* create a new one */
8381148        else
8391149          setclLvalue(L, ra, ncl);  /* push cashed closure */
8401150        checkGC(L, ra + 1);
841      )
842      vmcase(OP_VARARG,
1151        vmbreak;
1152      }
1153      vmcase(OP_VARARG) {
8431154        int b = GETARG_B(i) - 1;
8441155        int j;
8451156        int n = cast_int(base - ci->func) - cl->p->numparams - 1;
r242885r242886
8571168            setnilvalue(ra + j);
8581169          }
8591170        }
860      )
861      vmcase(OP_EXTRAARG,
1171        vmbreak;
1172      }
1173      vmcase(OP_EXTRAARG) {
8621174        lua_assert(0);
863      )
1175        vmbreak;
1176      }
8641177    }
8651178  }
8661179}
8671180
1181/* }================================================================== */
1182
trunk/3rdparty/lua/src/lvm.h
r242885r242886
11/*
2** $Id: lvm.h,v 2.18.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lvm.h,v 2.34 2014/08/01 17:24:02 roberto Exp $
33** Lua virtual machine
44** See Copyright Notice in lua.h
55*/
r242885r242886
1313#include "ltm.h"
1414
1515
16#define tostring(L,o) (ttisstring(o) || (luaV_tostring(L, o)))
16#if !defined(LUA_NOCVTN2S)
17#define cvt2str(o)   ttisnumber(o)
18#else
19#define cvt2str(o)   0   /* no conversion from numbers to strings */
20#endif
1721
18#define tonumber(o,n)   (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL))
1922
20#define equalobj(L,o1,o2)  (ttisequal(o1, o2) && luaV_equalobj_(L, o1, o2))
23#if !defined(LUA_NOCVTS2N)
24#define cvt2num(o)   ttisstring(o)
25#else
26#define cvt2num(o)   0   /* no conversion from strings to numbers */
27#endif
2128
22#define luaV_rawequalobj(o1,o2)      equalobj(NULL,o1,o2)
2329
30#define tonumber(o,n) \
31   (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))
2432
25/* not to called directly */
26LUAI_FUNC int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2);
33#define tointeger(o,i) \
34   (ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger_(o,i))
2735
36#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2))
2837
38#define luaV_rawequalobj(t1,t2)      luaV_equalobj(NULL,t1,t2)
39
40
41LUAI_FUNC int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2);
2942LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
3043LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
31LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n);
32LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj);
44LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n);
45LUAI_FUNC int luaV_tointeger_ (const TValue *obj, lua_Integer *p);
3346LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,
3447                                            StkId val);
3548LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,
r242885r242886
3750LUAI_FUNC void luaV_finishOp (lua_State *L);
3851LUAI_FUNC void luaV_execute (lua_State *L);
3952LUAI_FUNC void luaV_concat (lua_State *L, int total);
40LUAI_FUNC void luaV_arith (lua_State *L, StkId ra, const TValue *rb,
41                           const TValue *rc, TMS op);
53LUAI_FUNC lua_Integer luaV_div (lua_State *L, lua_Integer x, lua_Integer y);
54LUAI_FUNC lua_Integer luaV_mod (lua_State *L, lua_Integer x, lua_Integer y);
55LUAI_FUNC lua_Integer luaV_shiftl (lua_Integer x, lua_Integer y);
4256LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);
4357
4458#endif
trunk/3rdparty/lua/src/lzio.c
r242885r242886
11/*
2** $Id: lzio.c,v 1.35.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lzio.c,v 1.36 2014/11/02 19:19:04 roberto Exp $
33** Buffered streams
44** See Copyright Notice in lua.h
55*/
66
7#define lzio_c
8#define LUA_CORE
79
10#include "lprefix.h"
11
12
813#include <string.h>
914
10#define lzio_c
11#define LUA_CORE
12
1315#include "lua.h"
1416
1517#include "llimits.h"
trunk/3rdparty/lua/src/lzio.h
r242885r242886
11/*
2** $Id: lzio.h,v 1.26.1.1 2013/04/12 18:48:47 roberto Exp $
2** $Id: lzio.h,v 1.30 2014/12/19 17:26:14 roberto Exp $
33** Buffered streams
44** See Copyright Notice in lua.h
55*/
r242885r242886
3232#define luaZ_sizebuffer(buff)   ((buff)->buffsize)
3333#define luaZ_bufflen(buff)   ((buff)->n)
3434
35#define luaZ_buffremove(buff,i)   ((buff)->n -= (i))
3536#define luaZ_resetbuffer(buff) ((buff)->n = 0)
3637
3738
3839#define luaZ_resizebuffer(L, buff, size) \
39   (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \
40   ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \
41            (buff)->buffsize, size), \
4042   (buff)->buffsize = size)
4143
4244#define luaZ_freebuffer(L, buff)   luaZ_resizebuffer(L, buff, 0)
r242885r242886
4547LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);
4648LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
4749                                        void *data);
48LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n);   /* read next n bytes */
50LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n);   /* read next n bytes */
4951
5052
5153
r242885r242886
5557  size_t n;         /* bytes still unread */
5658  const char *p;      /* current position in buffer */
5759  lua_Reader reader;      /* reader function */
58  void* data;         /* additional data */
60  void *data;         /* additional data */
5961  lua_State *L;         /* Lua state (for reader) */
6062};
6163


Previous 199869 Revisions Next


© 1997-2024 The MAME Team