Previous 199869 Revisions Next

r34448 Sunday 11th January, 2015 at 20:44:52 UTC by MetalliC
naomi.c: redumped vstrik3c, both existing and new dumps were BAD, made one good-looking from them [ANY, MetalliC]

removed "Rev C" label from name, vstrik3c set is original release
[/trunk]makefile
[3rdparty/lsqlite3]lsqlite3.c
[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
[hash]apple3.xml gjmovie.xml ibm5170.xml
[src/emu]clifront.c clifront.h cliopts.c cliopts.h devfind.c devfind.h emu.mak emucore.c emucore.h emuopts.c emuopts.h image.c ioport.c luaengine.c machine.c machine.h mame.c mame.h render.h rendfont.c rendfont.h rendutil.h video.c webengine.c
[src/emu/bus/nes]ggenie.c ggenie.h nes_slot.h pt554.c
[src/emu/bus/vcs]dpc.c
[src/emu/cpu/tms0980]tms0980.c tms0980.h
[src/emu/imagedev]floppy.c
[src/emu/machine]atahle.c idehd.c
[src/emu/netlist]netlist.mak nl_base.c nl_base.h nl_config.h nl_dice_compat.h nl_factory.c nl_factory.h nl_lists.h nl_setup.c nl_setup.h plists.h pstate.c pstate.h pstring.c
[src/emu/netlist/analog]nld_bjt.c nld_ms_direct.h nld_solver.c nld_solver.h
[src/emu/netlist/devices]net_lib.c net_lib.h nld_4020.c nld_74107.c nld_74123.c nld_74153.c nld_7448.c nld_7474.c nld_7483.c nld_7490.c nld_7493.c nld_74ls629.c nld_9316.c nld_ne555.c nld_signal.h nld_system.h nld_truthtable.h
[src/emu/sound]qs1000.c tiaintf.c tiasound.c tiasound.h
[src/emu/ui]barcode.c devopt.c devopt.h filemngr.c filemngr.h imginfo.c imginfo.h inputmap.c inputmap.h mainmenu.c miscmenu.c miscmenu.h selgame.c slotopt.c slotopt.h tapectrl.c
[src/lib]lib.mak
[src/lib/util]chd.c corefile.h options.h
[src/mame]mame.lst
[src/mame/audio]mario.c
[src/mame/drivers]20pacgal.c aleck64.c chihiro.c dec0.c eolith.c eolith16.c eolithsp.c hyhoo.c naomi.c pastelg.c peplus.c psychic5.c segajw.c sprint2.c stadhero.c stfight.c stlforce.c strnskil.c tourtabl.c vegaeo.c xyonix.c
[src/mame/includes]dec0.h eolith.h eolithsp.h* hyhoo.h mario.h nb1413m3.h pastelg.h stadhero.h stfight.h stlforce.h strnskil.h vaportra.h xyonix.h
[src/mame/machine]dec0.c nb1413m3.c stfight.c
[src/mame/video]dec0.c decbac06.c eolith.c hyhoo.c pastelg.c stadhero.c strnskil.c tia.c tia.h xyonix.c
[src/mess]mess.lst mess.mak
[src/mess/drivers]a2600.c apple3.c comp4.c elecdet.c fmtowns.c gamate.c ngen.c prestige.c splitsec.c stopthie.c ticalc1x.c tispeak.c
[src/mess/includes]msx.h
[src/mess/layout]elecdet.lay lantutor.lay snspell.lay splitsec.lay tispeak.lay*
[src/mess/machine]ngen_kb.c
[src/osd]osdcore.c osdepend.c* osdepend.h
[src/osd/modules/debugger]debugint.c debugint.h debugosx.h debugosx.m debugqt.c debugqt.h debugwin.c debugwin.h none.c none.h
[src/osd/modules/lib]osdobj_common.c osdobj_common.h
[src/osd/modules/sound]direct_sound.c direct_sound.h none.c none.h sdl_sound.c sdl_sound.h
[src/osd/osdmini]minimain.c osdmini.h osdmini.mak
[src/osd/sdl]draw13.c input.c osdsdl.h output.c sdl.mak sdlmain.c video.c window.c
[src/osd/windows]windows.mak winmain.c winmain.h winprefix.h
[src/regtests/chdman/input/createhd_2]in.params
[src/regtests/chdman/input/createhd_3]in.params
[src/regtests/chdman/input/createhd_4]in.params
[src/regtests/chdman/input/createhd_5]in.params
[src/regtests/chdman/output/createhd_2]out.chd
[src/regtests/chdman/output/createhd_3]out.chd
[src/regtests/chdman/output/createhd_4]out.chd
[src/regtests/chdman/output/createhd_5]out.chd
[src/tools]chdman.c

trunk/3rdparty/lsqlite3/lsqlite3.c
r242959r242960
476476static int dbvm_bind_index(lua_State *L, sqlite3_stmt *vm, int index, int lindex) {
477477   switch (lua_type(L, lindex)) {
478478      case LUA_TSTRING:
479         return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_rawlen(L, lindex), SQLITE_TRANSIENT);
479         return sqlite3_bind_text(vm, index, lua_tostring(L, lindex), lua_strlen(L, lindex), SQLITE_TRANSIENT);
480480      case LUA_TNUMBER:
481481         return sqlite3_bind_double(vm, index, lua_tonumber(L, lindex));
482482      case LUA_TBOOLEAN:
r242959r242960
522522   sdb_vm *svm = lsqlite_checkvm(L, 1);
523523   int index = luaL_checkint(L, 2);
524524   const char *value = luaL_checkstring(L, 3);
525   int len = lua_rawlen(L, 3);
525   int len = lua_strlen(L, 3);
526526
527527   lua_pushnumber(L, sqlite3_bind_blob(svm->vm, index, value, len, SQLITE_TRANSIENT));
528528   return 1;
r242959r242960
797797         sqlite3_result_double(ctx->ctx, luaL_checknumber(L, 2));
798798         break;
799799      case LUA_TSTRING:
800         sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_rawlen(L, 2), SQLITE_TRANSIENT);
800         sqlite3_result_text(ctx->ctx, luaL_checkstring(L, 2), lua_strlen(L, 2), SQLITE_TRANSIENT);
801801         break;
802802      case LUA_TNIL:
803803      case LUA_TNONE:
r242959r242960
814814static int lcontext_result_blob(lua_State *L) {
815815   lcontext *ctx = lsqlite_checkcontext(L, 1);
816816   const char *blob = luaL_checkstring(L, 2);
817   int size = lua_rawlen(L, 2);
817   int size = lua_strlen(L, 2);
818818   sqlite3_result_blob(ctx->ctx, (const void*)blob, size, SQLITE_TRANSIENT);
819819   return 0;
820820}
r242959r242960
829829static int lcontext_result_error(lua_State *L) {
830830   lcontext *ctx = lsqlite_checkcontext(L, 1);
831831   const char *err = luaL_checkstring(L, 2);
832   int size = lua_rawlen(L, 2);
832   int size = lua_strlen(L, 2);
833833   sqlite3_result_error(ctx->ctx, err, size);
834834   return 0;
835835}
r242959r242960
850850static int lcontext_result_text(lua_State *L) {
851851   lcontext *ctx = lsqlite_checkcontext(L, 1);
852852   const char *text = luaL_checkstring(L, 2);
853   int size = lua_rawlen(L, 2);
853   int size = lua_strlen(L, 2);
854854   sqlite3_result_text(ctx->ctx, text, size, SQLITE_TRANSIENT);
855855   return 0;
856856}
r242959r242960
10011001
10021002   if (lua_pcall(L, argc + 1, 0, 0)) {
10031003      const char *errmsg = lua_tostring(L, -1);
1004      int size = lua_rawlen(L, -1);
1004      int size = lua_strlen(L, -1);
10051005      sqlite3_result_error(context, errmsg, size);
10061006   }
10071007
r242959r242960
16581658static int db_prepare(lua_State *L) {
16591659   sdb *db = lsqlite_checkdb(L, 1);
16601660   const char *sql = luaL_checkstring(L, 2);
1661   int sql_len = lua_rawlen(L, 2);
1661   int sql_len = lua_strlen(L, 2);
16621662   const char *sqltail;
16631663   sdb_vm *svm;
16641664   lua_settop(L,2); /* sql is on top of stack for call to newvm */
trunk/3rdparty/lua/Makefile
r242959r242960
3636# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
3737
3838# Convenience platforms targets.
39PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
39PLATS= aix ansi bsd freebsd generic linux macosx mingw posix solaris
4040
4141# What to install.
4242TO_BIN= lua luac
r242959r242960
4545TO_MAN= lua.1 luac.1
4646
4747# Lua version and release.
48V= 5.3
49R= $V.0
48V= 5.2
49R= $V.3
5050
5151# Targets start here.
5252all:   $(PLAT)
trunk/3rdparty/lua/README
r242959r242960
11
2This is Lua 5.3.0, released on 06 Jan 2015.
2This is Lua 5.2.3, released on 11 Nov 2013.
33
44For installation instructions, license details, and
55further information about Lua, see doc/readme.html.
trunk/3rdparty/lua/doc/contents.html
r242959r242960
11<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
22<HTML>
33<HEAD>
4<TITLE>Lua 5.3 Reference Manual - contents</TITLE>
4<TITLE>Lua 5.2 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">
r242959r242960
1717<HR>
1818<H1>
1919<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="" BORDER=0></A>
20Lua 5.3 Reference Manual
20Lua 5.2 Reference Manual
2121</H1>
2222
2323<P>
r242959r242960
3333<A HREF="#index">index</A>
3434<HR>
3535<SMALL>
36Copyright &copy; 2015 Lua.org, PUC-Rio.
36Copyright &copy; 2011&ndash;2013 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>
r242959r242960
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; 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>
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>
8685</UL>
8786<LI><A HREF="manual.html#3.5">3.5 &ndash; Visibility Rules</A>
8887</UL>
r242959r242960
113112<LI><A HREF="manual.html#6.4">6.4 &ndash; String Manipulation</A>
114113<UL>
115114<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>
117115</UL>
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>
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>
121119<LI><A HREF="manual.html#6.8">6.8 &ndash; Input and Output Facilities</A>
122120<LI><A HREF="manual.html#6.9">6.9 &ndash; Operating System Facilities</A>
123121<LI><A HREF="manual.html#6.10">6.10 &ndash; The Debug Library</A>
r242959r242960
141139<TD>
142140<H3><A NAME="functions">Lua functions</A></H3>
143141<P>
144<A HREF="manual.html#6.1">basic</A><BR>
145142<A HREF="manual.html#pdf-_G">_G</A><BR>
146143<A HREF="manual.html#pdf-_VERSION">_VERSION</A><BR>
147144
145<P>
148146<A HREF="manual.html#pdf-assert">assert</A><BR>
149147<A HREF="manual.html#pdf-collectgarbage">collectgarbage</A><BR>
150148<A HREF="manual.html#pdf-dofile">dofile</A><BR>
r242959r242960
170168<A HREF="manual.html#pdf-xpcall">xpcall</A><BR>
171169
172170<P>
173<A HREF="manual.html#6.2">coroutine</A><BR>
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>
174185<A HREF="manual.html#pdf-coroutine.create">coroutine.create</A><BR>
175<A HREF="manual.html#pdf-coroutine.isyieldable">coroutine.isyieldable</A><BR>
176186<A HREF="manual.html#pdf-coroutine.resume">coroutine.resume</A><BR>
177187<A HREF="manual.html#pdf-coroutine.running">coroutine.running</A><BR>
178188<A HREF="manual.html#pdf-coroutine.status">coroutine.status</A><BR>
r242959r242960
180190<A HREF="manual.html#pdf-coroutine.yield">coroutine.yield</A><BR>
181191
182192<P>
183<A HREF="manual.html#6.10">debug</A><BR>
184193<A HREF="manual.html#pdf-debug.debug">debug.debug</A><BR>
194<A HREF="manual.html#pdf-debug.getuservalue">debug.getuservalue</A><BR>
185195<A HREF="manual.html#pdf-debug.gethook">debug.gethook</A><BR>
186196<A HREF="manual.html#pdf-debug.getinfo">debug.getinfo</A><BR>
187197<A HREF="manual.html#pdf-debug.getlocal">debug.getlocal</A><BR>
188198<A HREF="manual.html#pdf-debug.getmetatable">debug.getmetatable</A><BR>
189199<A HREF="manual.html#pdf-debug.getregistry">debug.getregistry</A><BR>
190200<A HREF="manual.html#pdf-debug.getupvalue">debug.getupvalue</A><BR>
191<A HREF="manual.html#pdf-debug.getuservalue">debug.getuservalue</A><BR>
201<A HREF="manual.html#pdf-debug.setuservalue">debug.setuservalue</A><BR>
192202<A HREF="manual.html#pdf-debug.sethook">debug.sethook</A><BR>
193203<A HREF="manual.html#pdf-debug.setlocal">debug.setlocal</A><BR>
194204<A HREF="manual.html#pdf-debug.setmetatable">debug.setmetatable</A><BR>
195205<A HREF="manual.html#pdf-debug.setupvalue">debug.setupvalue</A><BR>
196<A HREF="manual.html#pdf-debug.setuservalue">debug.setuservalue</A><BR>
197206<A HREF="manual.html#pdf-debug.traceback">debug.traceback</A><BR>
198207<A HREF="manual.html#pdf-debug.upvalueid">debug.upvalueid</A><BR>
199208<A HREF="manual.html#pdf-debug.upvaluejoin">debug.upvaluejoin</A><BR>
200209
201210<P>
202<A HREF="manual.html#6.8">io</A><BR>
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>
203220<A HREF="manual.html#pdf-io.close">io.close</A><BR>
204221<A HREF="manual.html#pdf-io.flush">io.flush</A><BR>
205222<A HREF="manual.html#pdf-io.input">io.input</A><BR>
r242959r242960
215232<A HREF="manual.html#pdf-io.type">io.type</A><BR>
216233<A HREF="manual.html#pdf-io.write">io.write</A><BR>
217234
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
226235</TD>
227236<TD>
228237<H3>&nbsp;</H3>
229238<P>
230<A HREF="manual.html#6.7">math</A><BR>
231239<A HREF="manual.html#pdf-math.abs">math.abs</A><BR>
232240<A HREF="manual.html#pdf-math.acos">math.acos</A><BR>
233241<A HREF="manual.html#pdf-math.asin">math.asin</A><BR>
234242<A HREF="manual.html#pdf-math.atan">math.atan</A><BR>
243<A HREF="manual.html#pdf-math.atan2">math.atan2</A><BR>
235244<A HREF="manual.html#pdf-math.ceil">math.ceil</A><BR>
236245<A HREF="manual.html#pdf-math.cos">math.cos</A><BR>
246<A HREF="manual.html#pdf-math.cosh">math.cosh</A><BR>
237247<A HREF="manual.html#pdf-math.deg">math.deg</A><BR>
238248<A HREF="manual.html#pdf-math.exp">math.exp</A><BR>
239249<A HREF="manual.html#pdf-math.floor">math.floor</A><BR>
240250<A HREF="manual.html#pdf-math.fmod">math.fmod</A><BR>
251<A HREF="manual.html#pdf-math.frexp">math.frexp</A><BR>
241252<A HREF="manual.html#pdf-math.huge">math.huge</A><BR>
253<A HREF="manual.html#pdf-math.ldexp">math.ldexp</A><BR>
242254<A HREF="manual.html#pdf-math.log">math.log</A><BR>
243255<A HREF="manual.html#pdf-math.max">math.max</A><BR>
244<A HREF="manual.html#pdf-math.maxinteger">math.maxinteger</A><BR>
245256<A HREF="manual.html#pdf-math.min">math.min</A><BR>
246<A HREF="manual.html#pdf-math.mininteger">math.mininteger</A><BR>
247257<A HREF="manual.html#pdf-math.modf">math.modf</A><BR>
248258<A HREF="manual.html#pdf-math.pi">math.pi</A><BR>
259<A HREF="manual.html#pdf-math.pow">math.pow</A><BR>
249260<A HREF="manual.html#pdf-math.rad">math.rad</A><BR>
250261<A HREF="manual.html#pdf-math.random">math.random</A><BR>
251262<A HREF="manual.html#pdf-math.randomseed">math.randomseed</A><BR>
252263<A HREF="manual.html#pdf-math.sin">math.sin</A><BR>
264<A HREF="manual.html#pdf-math.sinh">math.sinh</A><BR>
253265<A HREF="manual.html#pdf-math.sqrt">math.sqrt</A><BR>
254266<A HREF="manual.html#pdf-math.tan">math.tan</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>
267<A HREF="manual.html#pdf-math.tanh">math.tanh</A><BR>
258268
259269<P>
260<A HREF="manual.html#6.9">os</A><BR>
261270<A HREF="manual.html#pdf-os.clock">os.clock</A><BR>
262271<A HREF="manual.html#pdf-os.date">os.date</A><BR>
263272<A HREF="manual.html#pdf-os.difftime">os.difftime</A><BR>
r242959r242960
271280<A HREF="manual.html#pdf-os.tmpname">os.tmpname</A><BR>
272281
273282<P>
274<A HREF="manual.html#6.3">package</A><BR>
275283<A HREF="manual.html#pdf-package.config">package.config</A><BR>
276284<A HREF="manual.html#pdf-package.cpath">package.cpath</A><BR>
277285<A HREF="manual.html#pdf-package.loaded">package.loaded</A><BR>
r242959r242960
282290<A HREF="manual.html#pdf-package.searchpath">package.searchpath</A><BR>
283291
284292<P>
285<A HREF="manual.html#6.4">string</A><BR>
286293<A HREF="manual.html#pdf-string.byte">string.byte</A><BR>
287294<A HREF="manual.html#pdf-string.char">string.char</A><BR>
288295<A HREF="manual.html#pdf-string.dump">string.dump</A><BR>
r242959r242960
293300<A HREF="manual.html#pdf-string.len">string.len</A><BR>
294301<A HREF="manual.html#pdf-string.lower">string.lower</A><BR>
295302<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>
298303<A HREF="manual.html#pdf-string.rep">string.rep</A><BR>
299304<A HREF="manual.html#pdf-string.reverse">string.reverse</A><BR>
300305<A HREF="manual.html#pdf-string.sub">string.sub</A><BR>
301<A HREF="manual.html#pdf-string.unpack">string.unpack</A><BR>
302306<A HREF="manual.html#pdf-string.upper">string.upper</A><BR>
303307
304308<P>
305<A HREF="manual.html#6.6">table</A><BR>
306309<A HREF="manual.html#pdf-table.concat">table.concat</A><BR>
307310<A HREF="manual.html#pdf-table.insert">table.insert</A><BR>
308<A HREF="manual.html#pdf-table.move">table.move</A><BR>
309311<A HREF="manual.html#pdf-table.pack">table.pack</A><BR>
310312<A HREF="manual.html#pdf-table.remove">table.remove</A><BR>
311313<A HREF="manual.html#pdf-table.sort">table.sort</A><BR>
312314<A HREF="manual.html#pdf-table.unpack">table.unpack</A><BR>
313315
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
331316</TD>
332317<TD>
333<H3><A NAME="api">C API</A></H3>
318<H3>C API</H3>
334319<P>
335320<A HREF="manual.html#lua_Alloc">lua_Alloc</A><BR>
336321<A HREF="manual.html#lua_CFunction">lua_CFunction</A><BR>
337322<A HREF="manual.html#lua_Debug">lua_Debug</A><BR>
338323<A HREF="manual.html#lua_Hook">lua_Hook</A><BR>
339324<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>
342325<A HREF="manual.html#lua_Number">lua_Number</A><BR>
343326<A HREF="manual.html#lua_Reader">lua_Reader</A><BR>
344327<A HREF="manual.html#lua_State">lua_State</A><BR>
r242959r242960
361344<A HREF="manual.html#lua_error">lua_error</A><BR>
362345<A HREF="manual.html#lua_gc">lua_gc</A><BR>
363346<A HREF="manual.html#lua_getallocf">lua_getallocf</A><BR>
364<A HREF="manual.html#lua_getextraspace">lua_getextraspace</A><BR>
347<A HREF="manual.html#lua_getctx">lua_getctx</A><BR>
365348<A HREF="manual.html#lua_getfield">lua_getfield</A><BR>
366349<A HREF="manual.html#lua_getglobal">lua_getglobal</A><BR>
367350<A HREF="manual.html#lua_gethook">lua_gethook</A><BR>
368351<A HREF="manual.html#lua_gethookcount">lua_gethookcount</A><BR>
369352<A HREF="manual.html#lua_gethookmask">lua_gethookmask</A><BR>
370<A HREF="manual.html#lua_geti">lua_geti</A><BR>
371353<A HREF="manual.html#lua_getinfo">lua_getinfo</A><BR>
372354<A HREF="manual.html#lua_getlocal">lua_getlocal</A><BR>
373355<A HREF="manual.html#lua_getmetatable">lua_getmetatable</A><BR>
r242959r242960
380362<A HREF="manual.html#lua_isboolean">lua_isboolean</A><BR>
381363<A HREF="manual.html#lua_iscfunction">lua_iscfunction</A><BR>
382364<A HREF="manual.html#lua_isfunction">lua_isfunction</A><BR>
383<A HREF="manual.html#lua_isinteger">lua_isinteger</A><BR>
384365<A HREF="manual.html#lua_islightuserdata">lua_islightuserdata</A><BR>
385366<A HREF="manual.html#lua_isnil">lua_isnil</A><BR>
386367<A HREF="manual.html#lua_isnone">lua_isnone</A><BR>
r242959r242960
390371<A HREF="manual.html#lua_istable">lua_istable</A><BR>
391372<A HREF="manual.html#lua_isthread">lua_isthread</A><BR>
392373<A HREF="manual.html#lua_isuserdata">lua_isuserdata</A><BR>
393<A HREF="manual.html#lua_isyieldable">lua_isyieldable</A><BR>
394374<A HREF="manual.html#lua_len">lua_len</A><BR>
395375<A HREF="manual.html#lua_load">lua_load</A><BR>
396376<A HREF="manual.html#lua_newstate">lua_newstate</A><BR>
r242959r242960
398378<A HREF="manual.html#lua_newthread">lua_newthread</A><BR>
399379<A HREF="manual.html#lua_newuserdata">lua_newuserdata</A><BR>
400380<A HREF="manual.html#lua_next">lua_next</A><BR>
401<A HREF="manual.html#lua_numbertointeger">lua_numbertointeger</A><BR>
402381<A HREF="manual.html#lua_pcall">lua_pcall</A><BR>
403382<A HREF="manual.html#lua_pcallk">lua_pcallk</A><BR>
404383<A HREF="manual.html#lua_pop">lua_pop</A><BR>
r242959r242960
415394<A HREF="manual.html#lua_pushnumber">lua_pushnumber</A><BR>
416395<A HREF="manual.html#lua_pushstring">lua_pushstring</A><BR>
417396<A HREF="manual.html#lua_pushthread">lua_pushthread</A><BR>
397<A HREF="manual.html#lua_pushunsigned">lua_pushunsigned</A><BR>
418398<A HREF="manual.html#lua_pushvalue">lua_pushvalue</A><BR>
419399<A HREF="manual.html#lua_pushvfstring">lua_pushvfstring</A><BR>
420400<A HREF="manual.html#lua_rawequal">lua_rawequal</A><BR>
r242959r242960
429409<A HREF="manual.html#lua_remove">lua_remove</A><BR>
430410<A HREF="manual.html#lua_replace">lua_replace</A><BR>
431411<A HREF="manual.html#lua_resume">lua_resume</A><BR>
432<A HREF="manual.html#lua_rotate">lua_rotate</A><BR>
433412<A HREF="manual.html#lua_setallocf">lua_setallocf</A><BR>
434413<A HREF="manual.html#lua_setfield">lua_setfield</A><BR>
435414<A HREF="manual.html#lua_setglobal">lua_setglobal</A><BR>
436415<A HREF="manual.html#lua_sethook">lua_sethook</A><BR>
437<A HREF="manual.html#lua_seti">lua_seti</A><BR>
438416<A HREF="manual.html#lua_setlocal">lua_setlocal</A><BR>
439417<A HREF="manual.html#lua_setmetatable">lua_setmetatable</A><BR>
440418<A HREF="manual.html#lua_settable">lua_settable</A><BR>
r242959r242960
442420<A HREF="manual.html#lua_setupvalue">lua_setupvalue</A><BR>
443421<A HREF="manual.html#lua_setuservalue">lua_setuservalue</A><BR>
444422<A HREF="manual.html#lua_status">lua_status</A><BR>
445<A HREF="manual.html#lua_stringtonumber">lua_stringtonumber</A><BR>
446423<A HREF="manual.html#lua_toboolean">lua_toboolean</A><BR>
447424<A HREF="manual.html#lua_tocfunction">lua_tocfunction</A><BR>
448425<A HREF="manual.html#lua_tointeger">lua_tointeger</A><BR>
r242959r242960
453430<A HREF="manual.html#lua_topointer">lua_topointer</A><BR>
454431<A HREF="manual.html#lua_tostring">lua_tostring</A><BR>
455432<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>
456435<A HREF="manual.html#lua_touserdata">lua_touserdata</A><BR>
457436<A HREF="manual.html#lua_type">lua_type</A><BR>
458437<A HREF="manual.html#lua_typename">lua_typename</A><BR>
r242959r242960
466445
467446</TD>
468447<TD>
469<H3><A NAME="auxlib">auxiliary library</A></H3>
448<H3>auxiliary library</H3>
470449<P>
471450<A HREF="manual.html#luaL_Buffer">luaL_Buffer</A><BR>
472451<A HREF="manual.html#luaL_Reg">luaL_Reg</A><BR>
473<A HREF="manual.html#luaL_Stream">luaL_Stream</A><BR>
474452
475453<P>
476454<A HREF="manual.html#luaL_addchar">luaL_addchar</A><BR>
r242959r242960
484462<A HREF="manual.html#luaL_buffinitsize">luaL_buffinitsize</A><BR>
485463<A HREF="manual.html#luaL_callmeta">luaL_callmeta</A><BR>
486464<A HREF="manual.html#luaL_checkany">luaL_checkany</A><BR>
465<A HREF="manual.html#luaL_checkint">luaL_checkint</A><BR>
487466<A HREF="manual.html#luaL_checkinteger">luaL_checkinteger</A><BR>
467<A HREF="manual.html#luaL_checklong">luaL_checklong</A><BR>
488468<A HREF="manual.html#luaL_checklstring">luaL_checklstring</A><BR>
489469<A HREF="manual.html#luaL_checknumber">luaL_checknumber</A><BR>
490470<A HREF="manual.html#luaL_checkoption">luaL_checkoption</A><BR>
r242959r242960
492472<A HREF="manual.html#luaL_checkstring">luaL_checkstring</A><BR>
493473<A HREF="manual.html#luaL_checktype">luaL_checktype</A><BR>
494474<A HREF="manual.html#luaL_checkudata">luaL_checkudata</A><BR>
475<A HREF="manual.html#luaL_checkunsigned">luaL_checkunsigned</A><BR>
495476<A HREF="manual.html#luaL_checkversion">luaL_checkversion</A><BR>
496477<A HREF="manual.html#luaL_dofile">luaL_dofile</A><BR>
497478<A HREF="manual.html#luaL_dostring">luaL_dostring</A><BR>
r242959r242960
513494<A HREF="manual.html#luaL_newmetatable">luaL_newmetatable</A><BR>
514495<A HREF="manual.html#luaL_newstate">luaL_newstate</A><BR>
515496<A HREF="manual.html#luaL_openlibs">luaL_openlibs</A><BR>
497<A HREF="manual.html#luaL_optint">luaL_optint</A><BR>
516498<A HREF="manual.html#luaL_optinteger">luaL_optinteger</A><BR>
499<A HREF="manual.html#luaL_optlong">luaL_optlong</A><BR>
517500<A HREF="manual.html#luaL_optlstring">luaL_optlstring</A><BR>
518501<A HREF="manual.html#luaL_optnumber">luaL_optnumber</A><BR>
519502<A HREF="manual.html#luaL_optstring">luaL_optstring</A><BR>
503<A HREF="manual.html#luaL_optunsigned">luaL_optunsigned</A><BR>
520504<A HREF="manual.html#luaL_prepbuffer">luaL_prepbuffer</A><BR>
521505<A HREF="manual.html#luaL_prepbuffsize">luaL_prepbuffsize</A><BR>
522506<A HREF="manual.html#luaL_pushresult">luaL_pushresult</A><BR>
r242959r242960
532516<A HREF="manual.html#luaL_unref">luaL_unref</A><BR>
533517<A HREF="manual.html#luaL_where">luaL_where</A><BR>
534518
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
605519</TD>
606520</TR>
607521</TABLE>
r242959r242960
609523<HR>
610524<SMALL CLASS="footer">
611525Last update:
612Tue Dec 9 21:26:07 BRST 2014
526Tue Mar 12 11:22:18 BRT 2013
613527</SMALL>
614528<!--
615Last change: updated for Lua 5.3.0 (final)
529Last change: revised for Lua 5.2.2
616530-->
617531
618532</BODY>
trunk/3rdparty/lua/doc/lua.1
r242959r242960
1.TH LUA 1 "$Date: 2014/12/10 15:55:45 $"
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 $"
23.SH NAME
34lua \- Lua interpreter
45.SH SYNOPSIS
r242959r242960
4950prompts the user,
5051reads lines from the standard input,
5152and 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.
5453If a line does not contain a complete statement,
5554then a secondary prompt is displayed and
5655lines are read until a complete statement is formed or
5756a 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.
5863.LP
5964At the very start,
6065before even handling the command line,
6166.B lua
6267checks the contents of the environment variables
63.B LUA_INIT_5_3
68.B LUA_INIT_5_2
6469or
6570.BR LUA_INIT ,
6671in that order.
trunk/3rdparty/lua/doc/lua.css
r242959r242960
5353a:link:hover, a:visited:hover {
5454   color: #000080 ;
5555   background-color: #D0D0FF ;
56   border-radius: 4px;
5756}
5857
5958a:link:active, a:visited:active {
6059   color: #FF0000 ;
6160}
6261
63h1 a img {
64   vertical-align: text-bottom ;
65}
66
6762hr {
6863   border: 0 ;
6964   height: 1px ;
r242959r242960
9186input[type=text] {
9287   border: solid #a0a0a0 2px ;
9388   border-radius: 2em ;
89   -moz-border-radius: 2em ;
9490   background-image: url('images/search.png') ;
95   background-repeat: no-repeat ;
91   background-repeat: no-repeat;
9692   background-position: 4px center ;
9793   padding-left: 20px ;
9894   height: 2em ;
9995}
10096
101pre.session {
102   background-color: #F8F8F8 ;
103   padding: 1em ;
104   border-radius: 8px ;
105}
trunk/3rdparty/lua/doc/manual.html
r242959r242960
22<html>
33
44<head>
5<title>Lua 5.3 Reference Manual</title>
5<title>Lua 5.2 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">
r242959r242960
1313<hr>
1414<h1>
1515<a href="http://www.lua.org/"><img src="logo.gif" alt="" border="0"></a>
16Lua 5.3 Reference Manual
16Lua 5.2 Reference Manual
1717</h1>
1818
1919by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, Waldemar Celes
2020<p>
2121<small>
22Copyright &copy; 2015 Lua.org, PUC-Rio.
22Copyright &copy; 2011&ndash;2013 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>
r242959r242960
3333<!-- ====================================================================== -->
3434<p>
3535
36<!-- $Id: manual.of,v 1.146 2015/01/06 11:23:01 roberto Exp $ -->
36<!-- $Id: manual.of,v 1.103 2013/03/14 18:51:56 roberto Exp $ -->
3737
3838
3939
r242959r242960
4444Lua is an extension programming language designed to support
4545general procedural programming with data description
4646facilities.
47Lua also offers good support for object-oriented programming,
47It 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.
r242959r242960
5353
5454
5555<p>
56As an extension language, Lua has no notion of a "main" program:
56Being 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,
r242959r242960
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 both
123integer numbers and real (floating-point) numbers.
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>.)
124130<em>String</em> represents immutable sequences of bytes.
125131
126132Lua is 8-bit clean:
127133strings can contain any 8-bit value,
128134including embedded zeros ('<code>\0</code>').
129Lua is also encoding-agnostic;
130it makes no assumptions about the contents of a string.
131135
132136
133137<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>
152138Lua can call (and manipulate) functions written in Lua and
153functions written in C (see <a href="#3.4.10">&sect;3.4.10</a>).
154Both are represented by the type <em>function</em>.
139functions written in C
140(see <a href="#3.4.9">&sect;3.4.9</a>).
155141
156142
157143<p>
158144The type <em>userdata</em> is provided to allow arbitrary C&nbsp;data to
159145be stored in Lua variables.
160A userdata value represents a block of raw memory.
146A userdata value is a pointer to a block of raw memory.
161147There are two kinds of userdata:
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.
148full userdata, where the block of memory is managed by Lua,
149and light userdata, where the block of memory is managed by the host.
166150Userdata has no predefined operations in Lua,
167151except assignment and identity test.
168152By using <em>metatables</em>,
r242959r242960
176160<p>
177161The type <em>thread</em> represents independent threads of execution
178162and it is used to implement coroutines (see <a href="#2.6">&sect;2.6</a>).
179Lua threads are not related to operating-system threads.
163Do not confuse Lua threads with operating-system threads.
180164Lua supports coroutines on all systems,
181even those that do not support threads natively.
165even those that do not support threads.
182166
183167
184168<p>
185169The type <em>table</em> implements associative arrays,
186170that is, arrays that can be indexed not only with numbers,
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>.)
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>).
190174Tables can be <em>heterogeneous</em>;
191175that is, they can contain values of all types (except <b>nil</b>).
192176Any key with value <b>nil</b> is not considered part of the table.
r242959r242960
195179
196180
197181<p>
198Tables are the sole data-structuring mechanism in Lua;
182Tables are the sole data structuring mechanism in Lua;
199183they can be used to represent ordinary arrays, sequences,
200184symbol tables, sets, records, graphs, trees, etc.
201185To represent records, Lua uses the field name as an index.
202186The language supports this representation by
203187providing <code>a.name</code> as syntactic sugar for <code>a["name"]</code>.
204188There are several convenient ways to create tables in Lua
205(see <a href="#3.4.9">&sect;3.4.9</a>).
189(see <a href="#3.4.8">&sect;3.4.8</a>).
206190
207191
208192<p>
209193We use the term <em>sequence</em> to denote a table where
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>).
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>).
213197
214198
215199<p>
r242959r242960
218202In particular,
219203because functions are first-class values,
220204table fields can contain functions.
221Thus tables can also carry <em>methods</em> (see <a href="#3.4.11">&sect;3.4.11</a>).
205Thus tables can also carry <em>methods</em> (see <a href="#3.4.10">&sect;3.4.10</a>).
222206
223207
224208<p>
r242959r242960
228212denote the same table element
229213if and only if <code>i</code> and <code>j</code> are raw equal
230214(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.)
243215
244216
245217<p>
r242959r242960
263235
264236<p>
265237As will be discussed in <a href="#3.2">&sect;3.2</a> and <a href="#3.3.3">&sect;3.3.3</a>,
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>.
238any reference to a global name <code>var</code> is syntactically translated
239to <code>_ENV.var</code>.
269240Moreover, every chunk is compiled in the scope of
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.
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.
272243
273244
274245<p>
275246Despite the existence of this external <code>_ENV</code> variable and
276the translation of free names,
247the translation of global names,
277248<code>_ENV</code> is a completely regular name.
278249In particular,
279250you can define new variables and parameters with that name.
280Each reference to a free name uses the <code>_ENV</code> that is
251Each reference to a global name uses the <code>_ENV</code> that is
281252visible at that point in the program,
282253following the usual visibility rules of Lua (see <a href="#3.5">&sect;3.5</a>).
283254
r242959r242960
289260<p>
290261Lua keeps a distinguished environment called the <em>global environment</em>.
291262This value is kept at a special index in the C registry (see <a href="#4.5">&sect;4.5</a>).
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.)
263In Lua, the variable <a href="#pdf-_G"><code>_G</code></a> is initialized with this same value.
294264
295265
296266<p>
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>).
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>).
300270Therefore, by default,
301free names in Lua code refer to entries in the global environment
302(and, therefore, they are also called <em>global variables</em>).
271global variables in Lua code refer to entries in the global environment.
303272Moreover, all standard libraries are loaded in the global environment
304and some functions there operate on that environment.
273and several functions there operate on that environment.
305274You can use <a href="#pdf-load"><code>load</code></a> (or <a href="#pdf-loadfile"><code>loadfile</code></a>)
306275to load a chunk with a different environment.
307276(In C, you have to load the chunk and then change the value
308277of its first upvalue.)
309278
310279
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.
311289
312290
313291
292
293
314294<h2>2.3 &ndash; <a name="2.3">Error Handling</a></h2>
315295
316296<p>
317297Because Lua is an embedded extension language,
318298all Lua actions start from C&nbsp;code in the host program
319calling a function from the Lua library.
320(When you use Lua standalone,
321the <code>lua</code> application is the host program.)
299calling a function from the Lua library (see <a href="#lua_pcall"><code>lua_pcall</code></a>).
322300Whenever an error occurs during
323301the compilation or execution of a Lua chunk,
324302control returns to the host,
r242959r242960
338316Whenever there is an error,
339317an <em>error object</em> (also called an <em>error message</em>)
340318is propagated with information about the error.
341Lua itself only generates errors whose error object is a string,
319Lua itself only generates errors where the error object is a string,
342320but programs may generate errors with
343any value as the error object.
344It is up to the Lua program or its host to handle such error objects.
321any value for the error object.
345322
346323
347324<p>
r242959r242960
356333This message handler is still protected by the protected call;
357334so, an error inside the message handler
358335will call the message handler again.
359If this loop goes on for too long,
360Lua breaks it and returns an appropriate message.
336If this loop goes on, Lua breaks it and returns an appropriate message.
361337
362338
363339
r242959r242960
394370You can replace the metatable of tables
395371using the <a href="#pdf-setmetatable"><code>setmetatable</code></a> function.
396372You cannot change the metatable of other types from Lua
397(except by using the debug library (<a href="#6.10">&sect;6.10</a>));
373(except by using the debug library);
398374you must use the C&nbsp;API for that.
399375
400376
r242959r242960
409385
410386
411387<p>
412A metatable controls how an object behaves in
413arithmetic operations, bitwise operations,
414order comparisons, concatenation, length operation, calls, and indexing.
388A metatable controls how an object behaves in arithmetic operations,
389order comparisons, concatenation, length operation, and indexing.
415390A metatable also can define a function to be called
416when a userdata or a table is garbage collected (<a href="#2.5">&sect;2.5</a>).
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.
417396
418397
419398<p>
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
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
423402two underscores, '<code>__</code>';
424403for instance, the key for operation "add" is the
425404string "<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:
430405
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
431419<pre>
432     rawget(getmetatable(obj) or {}, "__" .. event_name)
433</pre>
420     metatable(obj)[event]
421</pre><p>
422This should be read as
434423
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
435432<p>
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.)
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.)
443439
444440
445441
r242959r242960
448444<li><b>"add": </b>
449445the <code>+</code> operation.
450446
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.
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>
464480</li>
465481
466482<li><b>"sub": </b>
r242959r242960
484500<li><b>"mod": </b>
485501the <code>%</code> operation.
486502
487Behavior similar to the "add" operation.
503Behavior similar to the "add" operation,
504with the operation
505<code>o1 - floor(o1/o2)*o2</code> as the primitive operation.
488506</li>
489507
490508<li><b>"pow": </b>
491509the <code>^</code> (exponentiation) operation.
492510
493Behavior similar to the "add" operation.
511Behavior similar to the "add" operation,
512with the function <code>pow</code> (from the C&nbsp;math library)
513as the primitive operation.
494514</li>
495515
496516<li><b>"unm": </b>
497the <code>-</code> (unary minus) operation.
517the unary <code>-</code> operation.
498518
499Behavior similar to the "add" operation.
500</li>
501519
502<li><b>"idiv": </b>
503the <code>//</code> (floor division) operation.
504
505Behavior similar to the "add" operation.
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>
506537</li>
507538
508<li><b>"band": </b>
509the <code>&amp;</code> (bitwise and) operation.
539<li><b>"concat": </b>
540the <code>..</code> (concatenation) operation.
510541
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>
516542
517<li><b>"bor": </b>
518the <code>|</code> (bitwise or) operation.
519
520Behavior similar to the "band" operation.
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>
521558</li>
522559
523<li><b>"bxor": </b>
524the <code>~</code> (bitwise exclusive or) operation.
560<li><b>"len": </b>
561the <code>#</code> operation.
525562
526Behavior similar to the "band" operation.
527</li>
528563
529<li><b>"bnot": </b>
530the <code>~</code> (bitwise unary not) operation.
531
532Behavior similar to the "band" operation.
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.
533581</li>
534582
535<li><b>"shl": </b>
536the <code>&lt;&lt;</code> (bitwise left shift) operation.
583<li><b>"eq": </b>
584the <code>==</code> operation.
537585
538Behavior similar to the "band" operation.
539</li>
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.
540592
541<li><b>"shr": </b>
542the <code>&gt;&gt;</code> (bitwise right shift) operation.
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:
543605
544Behavior similar to the "band" operation.
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.
545621</li>
546622
547<li><b>"concat": </b>
548the <code>..</code> (concatenation) operation.
623<li><b>"lt": </b>
624the <code>&lt;</code> operation.
549625
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>
555626
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.
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.
569644</li>
570645
571<li><b>"eq": </b>
572the <code>==</code> (equal) operation.
646<li><b>"le": </b>
647the <code>&lt;=</code> operation.
573648
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>
580649
581<li><b>"lt": </b>
582the <code>&lt;</code> (less than) operation.
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>.
583674
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>
589675
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>.
676<p>
600677As with the other comparison operators,
601678the result is always a boolean.
602679</li>
603680
604681<li><b>"index": </b>
605682The indexing access <code>table[key]</code>.
606
607This event happens when <code>table</code> is not a table or
683Note that the metamethod is tried only
608684when <code>key</code> is not present in <code>table</code>.
609The metamethod is looked up in <code>table</code>.
685(When <code>table</code> is not a table,
686no key is ever present,
687so the metamethod is always tried.)
610688
611689
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.)
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>
621711</li>
622712
623713<li><b>"newindex": </b>
624714The indexing assignment <code>table[key] = value</code>.
625
626Like the index event,
627this event happens when <code>table</code> is not a table or
715Note that the metamethod is tried only
628716when <code>key</code> is not present in <code>table</code>.
629The metamethod is looked up in <code>table</code>.
630717
631718
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.)
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>
649740</li>
650741
651742<li><b>"call": </b>
652The call operation <code>func(args)</code>.
743called when Lua calls a value.
653744
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>).
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>
660760</li>
661761
662762</ul>
r242959r242960
669769<p>
670770Lua performs automatic memory management.
671771This means that
672you do not have to worry about allocating memory for new objects
673or freeing it when the objects are no longer needed.
772you have to worry neither about allocating memory for new objects
773nor about freeing it when the objects are no longer needed.
674774Lua manages memory automatically by running
675775a <em>garbage collector</em> to collect all <em>dead objects</em>
676776(that is, objects that are no longer accessible from Lua).
r242959r242960
703803memory allocation.
704804Larger values make the collector more aggressive but also increase
705805the size of each incremental step.
706You should not use values smaller than 100,
707because they make the collector too slow and
806Values smaller than 100 make the collector too slow and
708807can result in the collector never finishing a cycle.
709808The default is 200,
710809which means that the collector runs at "twice"
r242959r242960
729828the collector directly (e.g., stop and restart it).
730829
731830
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.
732844
845
846
733847<h3>2.5.1 &ndash; <a name="2.5.1">Garbage-Collection Metamethods</a></h3>
734848
735849<p>
r242959r242960
752866Note that if you set a metatable without a <code>__gc</code> field
753867and later create that field in the metatable,
754868the object will not be marked for finalization.
755However, after an object has been marked,
869However, after an object is marked,
756870you can freely change the <code>__gc</code> field of its metatable.
757871
758872
r242959r242960
761875it is not collected immediately by the garbage collector.
762876Instead, Lua puts it in a list.
763877After the collection,
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.
878Lua does the equivalent of the following function
879for each object in that list:
771880
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>
772889
773890<p>
774891At the end of each garbage-collection cycle,
775892the finalizers for objects are called in
776the reverse order that the objects were marked for finalization,
893the reverse order that they were marked for collection,
777894among those collected in that cycle;
778895that is, the first finalizer to be called is the one associated
779896with the object marked last in the program.
r242959r242960
783900
784901<p>
785902Because the object being collected must still be used by the finalizer,
786that object (and other objects accessible only through it)
903it (and other objects accessible only through it)
787904must be <em>resurrected</em> by Lua.
788905Usually, this resurrection is transient,
789906and the object memory is freed in the next garbage-collection cycle.
790907However, if the finalizer stores the object in some global place
791908(e.g., a global variable),
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.
909then there is a permanent resurrection.
796910In any case,
797the object memory is freed only in the GC cycle where
798the object is unreachable and not marked for finalization.
911the object memory is freed only when it becomes completely inaccessible;
912its finalizer will never be called twice.
799913
800914
801915<p>
802916When you close a state (see <a href="#lua_close"><code>lua_close</code></a>),
803917Lua calls the finalizers of all objects marked for finalization,
804918following the reverse order that they were marked.
805If any finalizer marks objects for collection during that phase,
806these marks have no effect.
919If any finalizer marks new objects for collection during that phase,
920these new objects will not be finalized.
807921
808922
809923
r242959r242960
860974Values, such as numbers and light C functions,
861975are not subject to garbage collection,
862976and therefore are not removed from weak tables
863(unless their associated values are collected).
977(unless its associated value is collected).
864978Although strings are subject to garbage collection,
865979they do not have an explicit construction,
866980and therefore are not removed from weak tables.
r242959r242960
9151029a thread returned by <a href="#pdf-coroutine.create"><code>coroutine.create</code></a>,
9161030the coroutine starts its execution,
9171031at the first line of its 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.
1032Extra arguments passed to <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> are passed on
1033to the coroutine main function.
9201034After the coroutine starts running,
9211035it runs until it terminates or <em>yields</em>.
9221036
r242959r242960
9261040normally, when its main function returns
9271041(explicitly or implicitly, after the last instruction);
9281042and abnormally, if there is an unprotected error.
929In case of normal termination,
930<a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
1043In the first case, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>true</b>,
9311044plus any values returned by the coroutine main function.
9321045In case of errors, <a href="#pdf-coroutine.resume"><code>coroutine.resume</code></a> returns <b>false</b>
9331046plus an error message.
r242959r242960
10661179Lua is a case-sensitive language:
10671180<code>and</code> is a reserved word, but <code>And</code> and <code>AND</code>
10681181are two different, valid names.
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>).
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.
10731185
10741186
10751187<p>
r242959r242960
10771189
10781190<pre>
10791191     +     -     *     /     %     ^     #
1080     &amp;     ~     |     &lt;&lt;    &gt;&gt;    //
10811192     ==    ~=    &lt;=    &gt;=    &lt;     &gt;     =
10821193     (     )     {     }     [     ]     ::
10831194     ;     :     ,     .     ..    ...
r242959r242960
11081219
11091220
11101221<p>
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>,
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>,
11171224where <em>XX</em> is a sequence of exactly two hexadecimal digits,
11181225or with the escape sequence <code>\<em>ddd</em></code>,
11191226where <em>ddd</em> is a sequence of up to three decimal digits.
1120(Note that if a decimal escape sequence is to be followed by a digit,
1227(Note that if a decimal escape is to be followed by a digit,
11211228it 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>'.
11221231
11231232
11241233<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>
11341234Literal strings can also be defined using a long format
11351235enclosed by <em>long brackets</em>.
11361236We define an <em>opening long bracket of level <em>n</em></em> as an opening
11371237square bracket followed by <em>n</em> equal signs followed by another
11381238opening square bracket.
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>,
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>,
11411241and so on.
11421242A <em>closing long bracket</em> is defined similarly;
1143for instance,
1144a closing long bracket of level&nbsp;4 is written as  <code>]====]</code>.
1243for instance, a closing long bracket of level&nbsp;4 is written as <code>]====]</code>.
11451244A <em>long literal</em> starts with an opening long bracket of any level and
11461245ends at the first closing long bracket of the same level.
1147It can contain any text except a closing bracket of the same level.
1246It can contain any text except a closing bracket of the proper level.
11481247Literals in this bracketed form can run for several lines,
11491248do not interpret any escape sequences,
11501249and ignore long brackets of any other level.
r242959r242960
11861285</pre>
11871286
11881287<p>
1189A <em>numerical constant</em> (or <em>numeral</em>)
1190can be written with an optional fractional part
1288A <em>numerical constant</em> can be written with an optional fractional part
11911289and an optional decimal exponent,
11921290marked by a letter '<code>e</code>' or '<code>E</code>'.
11931291Lua also accepts hexadecimal constants,
r242959r242960
11951293Hexadecimal constants also accept an optional fractional part
11961294plus an optional binary exponent,
11971295marked by a letter '<code>p</code>' or '<code>P</code>'.
1198A numeric constant with a fractional dot or an exponent
1199denotes a float;
1200otherwise it denotes an integer.
1201Examples of valid integer constants are
1296Examples of valid numerical constants are
12021297
12031298<pre>
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
1299     3     3.0     3.1416     314.16e-2     0.31416E1
1300     0xff  0x0.1E  0xA23p-4   0X1.921FB54442D18P+1
12111301</pre>
12121302
12131303<p>
r242959r242960
13761466<p>
13771467Lua handles a chunk as the body of an anonymous function
13781468with a variable number of arguments
1379(see <a href="#3.4.11">&sect;3.4.11</a>).
1469(see <a href="#3.4.10">&sect;3.4.10</a>).
13801470As such, chunks can define local variables,
13811471receive arguments, and return values.
13821472Moreover, such anonymous function is compiled as in the
r242959r242960
13881478<p>
13891479A chunk can be stored in a file or in a string inside the host program.
13901480To execute a chunk,
1391Lua first <em>loads</em> it,
1392precompiling the chunk's code into instructions for a virtual machine,
1393and then Lua executes the compiled code
1481Lua first precompiles the chunk into instructions for a virtual machine,
1482and then it executes the compiled code
13941483with an interpreter for the virtual machine.
13951484
13961485
13971486<p>
13981487Chunks can also be precompiled into binary form;
1399see program <code>luac</code> and function <a href="#pdf-string.dump"><code>string.dump</code></a> for details.
1488see program <code>luac</code> for details.
14001489Programs in source and compiled forms are interchangeable;
1401Lua automatically detects the file type and acts accordingly (see <a href="#pdf-load"><code>load</code></a>).
1490Lua automatically detects the file type and acts accordingly.
14021491
14031492
14041493
14051494
14061495
1496
14071497<h3>3.3.3 &ndash; <a name="3.3.3">Assignment</a></h3>
14081498
14091499<p>
r242959r242960
14371527
14381528<p>
14391529The assignment statement first evaluates all its expressions
1440and only then the assignments are performed.
1530and only then are the assignments performed.
14411531Thus the code
14421532
14431533<pre>
r242959r242960
14731563
14741564
14751565<p>
1476An assignment to a global name <code>x = val</code>
1566An assignment to a global variable <code>x = val</code>
14771567is equivalent to the assignment
14781568<code>_ENV.x = val</code> (see <a href="#2.2">&sect;2.2</a>).
14791569
r242959r242960
15541644
15551645<p>
15561646The <b>return</b> statement is used to return values
1557from a function or a chunk
1558(which is an anonymous function).
1647from a function or a chunk (which is a function in disguise).
15591648
15601649Functions can return more than one value,
15611650so the syntax for the <b>return</b> statement is
r242959r242960
16061695     do
16071696       local <em>var</em>, <em>limit</em>, <em>step</em> = tonumber(<em>e1</em>), tonumber(<em>e2</em>), tonumber(<em>e3</em>)
16081697       if not (<em>var</em> and <em>limit</em> and <em>step</em>) then error() end
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
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
16151699         local v = <em>var</em>
16161700         <em>block</em>
1701         <em>var</em> = <em>var</em> + <em>step</em>
16171702       end
16181703     end
1619</pre>
1620
1621<p>
1704</pre><p>
16221705Note the following:
16231706
16241707<ul>
r242959r242960
16401723</li>
16411724
16421725<li>
1643You can use <b>break</b> and <b>goto</b> to exit a <b>for</b> loop.
1726You can use <b>break</b> to exit a <b>for</b> loop.
16441727</li>
16451728
16461729<li>
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.
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.
16501734</li>
16511735
16521736</ul>
r242959r242960
17201804   stat ::= functioncall
17211805</pre><p>
17221806In this case, all returned values are thrown away.
1723Function calls are explained in <a href="#3.4.10">&sect;3.4.10</a>.
1807Function calls are explained in <a href="#3.4.9">&sect;3.4.9</a>.
17241808
17251809
17261810
r242959r242960
17601844<pre>
17611845   exp ::= prefixexp
17621846   exp ::= <b>nil</b> | <b>false</b> | <b>true</b>
1763   exp ::= Numeral
1764   exp ::= LiteralString
1847   exp ::= Number
1848   exp ::= String
17651849   exp ::= functiondef
17661850   exp ::= tableconstructor
17671851   exp ::= &lsquo;<b>...</b>&rsquo;
r242959r242960
17711855</pre>
17721856
17731857<p>
1774Numerals and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
1858Numbers and literal strings are explained in <a href="#3.1">&sect;3.1</a>;
17751859variables are explained in <a href="#3.2">&sect;3.2</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>.
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>.
17791863Vararg expressions,
17801864denoted by three dots ('<code>...</code>'), can only be used when
17811865directly inside a vararg function;
1782they are explained in <a href="#3.4.11">&sect;3.4.11</a>.
1866they are explained in <a href="#3.4.10">&sect;3.4.10</a>.
17831867
17841868
17851869<p>
17861870Binary operators comprise arithmetic operators (see <a href="#3.4.1">&sect;3.4.1</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>).
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>).
17901873Unary operators comprise the unary minus (see <a href="#3.4.1">&sect;3.4.1</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>).
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>).
17941876
17951877
17961878<p>
r242959r242960
18411923
18421924
18431925<h3>3.4.1 &ndash; <a name="3.4.1">Arithmetic Operators</a></h3><p>
1844Lua supports the following arithmetic operators:
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
18451937
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>
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.
18561943
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.
18701944
18711945
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.
18781946
18791947
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.
1948<h3>3.4.2 &ndash; <a name="3.4.2">Coercion</a></h3>
18841949
1885
18861950<p>
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.
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.
19821958For complete control over how numbers are converted to strings,
19831959use the <code>format</code> function from the string library
19841960(see <a href="#pdf-string.format"><code>string.format</code></a>).
r242959r242960
19871963
19881964
19891965
1990<h3>3.4.4 &ndash; <a name="3.4.4">Relational Operators</a></h3><p>
1991Lua supports the following relational operators:
1966<h3>3.4.3 &ndash; <a name="3.4.3">Relational Operators</a></h3><p>
1967The relational operators in Lua are
19921968
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>
1969<pre>
1970     ==    ~=    &lt;     &gt;     &lt;=    &gt;=
1971</pre><p>
20011972These operators always result in <b>false</b> or <b>true</b>.
20021973
20031974
r242959r242960
20051976Equality (<code>==</code>) first compares the type of its operands.
20061977If the types are different, then the result is <b>false</b>.
20071978Otherwise, the values of the operands are compared.
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>
1979Numbers and strings are compared in the usual way.
20171980Tables, userdata, and threads
20181981are compared by reference:
20191982two objects are considered equal only if they are the same object.
r242959r242960
20311994
20321995
20331996<p>
2034Equality comparisons do not convert strings to numbers
2035or vice versa.
1997The conversion rules of <a href="#3.4.2">&sect;3.4.2</a>
1998do not apply to equality comparisons.
20361999Thus, <code>"0"==0</code> evaluates to <b>false</b>,
20372000and <code>t[0]</code> and <code>t["0"]</code> denote different
20382001entries in a table.
r242959r242960
20442007
20452008<p>
20462009The order operators work as follows.
2047If both arguments are numbers,
2048then they are compared following
2049the usual rule for binary operations.
2010If both arguments are numbers, then they are compared as such.
20502011Otherwise, if both arguments are strings,
20512012then their values are compared according to the current locale.
20522013Otherwise, Lua tries to call the "lt" or the "le"
r242959r242960
20582019
20592020
20602021
2061<h3>3.4.5 &ndash; <a name="3.4.5">Logical Operators</a></h3><p>
2022<h3>3.4.4 &ndash; <a name="3.4.4">Logical Operators</a></h3><p>
20622023The logical operators in Lua are
20632024<b>and</b>, <b>or</b>, and <b>not</b>.
20642025Like the control structures (see <a href="#3.3.4">&sect;3.3.4</a>),
r242959r242960
20742035The disjunction operator <b>or</b> returns its first argument
20752036if this value is different from <b>nil</b> and <b>false</b>;
20762037otherwise, <b>or</b> returns its second argument.
2077Both <b>and</b> and <b>or</b> use short-circuit evaluation;
2038Both <b>and</b> and <b>or</b> use short-cut evaluation;
20782039that is,
20792040the second operand is evaluated only if necessary.
20802041Here are some examples:
r242959r242960
20962057
20972058
20982059
2099<h3>3.4.6 &ndash; <a name="3.4.6">Concatenation</a></h3><p>
2060<h3>3.4.5 &ndash; <a name="3.4.5">Concatenation</a></h3><p>
21002061The string concatenation operator in Lua is
21012062denoted by two dots ('<code>..</code>').
21022063If both operands are strings or numbers, then they are converted to
2103strings according to the rules described in <a href="#3.4.3">&sect;3.4.3</a>.
2064strings according to the rules mentioned in <a href="#3.4.2">&sect;3.4.2</a>.
21042065Otherwise, the <code>__concat</code> metamethod is called (see <a href="#2.4">&sect;2.4</a>).
21052066
21062067
21072068
21082069
21092070
2110<h3>3.4.7 &ndash; <a name="3.4.7">The Length Operator</a></h3>
2071<h3>3.4.6 &ndash; <a name="3.4.6">The Length Operator</a></h3>
21112072
21122073<p>
21132074The length operator is denoted by the unary prefix operator <code>#</code>.
r242959r242960
21272088table is a <em>sequence</em>,
21282089that is,
21292090the set of its positive numeric keys is equal to <em>{1..n}</em>
2130for some non-negative integer <em>n</em>.
2091for some integer <em>n</em>.
21312092In that case, <em>n</em> is its length.
21322093Note that a table like
21332094
r242959r242960
21452106
21462107
21472108
2148<h3>3.4.8 &ndash; <a name="3.4.8">Precedence</a></h3><p>
2109<h3>3.4.7 &ndash; <a name="3.4.7">Precedence</a></h3><p>
21492110Operator precedence in Lua follows the table below,
21502111from lower to higher priority:
21512112
r242959r242960
21532114     or
21542115     and
21552116     &lt;     &gt;     &lt;=    &gt;=    ~=    ==
2156     |
2157     ~
2158     &amp;
2159     &lt;&lt;    &gt;&gt;
21602117     ..
21612118     +     -
2162     *     /     //    %
2163     unary operators (not   #     -     ~)
2119     *     /     %
2120     not   #     - (unary)
21642121     ^
21652122</pre><p>
21662123As usual,
r242959r242960
21732130
21742131
21752132
2176<h3>3.4.9 &ndash; <a name="3.4.9">Table Constructors</a></h3><p>
2133<h3>3.4.8 &ndash; <a name="3.4.8">Table Constructors</a></h3><p>
21772134Table constructors are expressions that create tables.
21782135Every time a constructor is evaluated, a new table is created.
21792136A constructor can be used to create an empty table
r242959r242960
21932150A field of the form <code>name = exp</code> is equivalent to
21942151<code>["name"] = exp</code>.
21952152Finally, fields of the form <code>exp</code> are equivalent to
2196<code>[i] = exp</code>, where <code>i</code> are consecutive integers
2153<code>[i] = exp</code>, where <code>i</code> are consecutive numerical integers,
21972154starting with 1.
21982155Fields in the other formats do not affect this counting.
21992156For example,
r242959r242960
22182175</pre>
22192176
22202177<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>
22262178If the last field in the list has the form <code>exp</code>
22272179and the expression is a function call or a vararg expression,
22282180then all values returned by this expression enter the list consecutively
2229(see <a href="#3.4.10">&sect;3.4.10</a>).
2181(see <a href="#3.4.9">&sect;3.4.9</a>).
22302182
22312183
22322184<p>
r242959r242960
22372189
22382190
22392191
2240<h3>3.4.10 &ndash; <a name="3.4.10">Function Calls</a></h3><p>
2192<h3>3.4.9 &ndash; <a name="3.4.9">Function Calls</a></h3><p>
22412193A function call in Lua has the following syntax:
22422194
22432195<pre>
r242959r242960
22722224<pre>
22732225   args ::= &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo;
22742226   args ::= tableconstructor
2275   args ::= LiteralString
2227   args ::= String
22762228</pre><p>
22772229All argument expressions are evaluated before the call.
22782230A call of the form <code>f{<em>fields</em>}</code> is
r242959r242960
23122264
23132265
23142266
2315<h3>3.4.11 &ndash; <a name="3.4.11">Function Definitions</a></h3>
2267<h3>3.4.10 &ndash; <a name="3.4.10">Function Definitions</a></h3>
23162268
23172269<p>
23182270The syntax for function definition is
r242959r242960
26032555In particular,
26042556<em>you are responsible for controlling stack overflow</em>.
26052557You can use the function <a href="#lua_checkstack"><code>lua_checkstack</code></a>
2606to ensure that the stack has enough space for pushing new elements.
2558to ensure that the stack has extra slots when pushing new elements.
26072559
26082560
26092561<p>
26102562Whenever Lua calls C,
2611it ensures that the stack has space for
2612at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
2563it ensures that the stack has at least <a name="pdf-LUA_MINSTACK"><code>LUA_MINSTACK</code></a> extra slots.
26132564<code>LUA_MINSTACK</code> is defined as 20,
26142565so that usually you do not have to worry about stack space
26152566unless your code has loops pushing elements onto the stack.
r242959r242960
26182569<p>
26192570When you call a Lua function
26202571without a fixed number of results (see <a href="#lua_call"><code>lua_call</code></a>),
2621Lua ensures that the stack has enough space for all results,
2572Lua ensures that the stack has enough size for all results,
26222573but it does not ensure any extra space.
26232574So, before pushing anything in the stack after such a call
26242575you should use <a href="#lua_checkstack"><code>lua_checkstack</code></a>.
r242959r242960
27222673<a name="pdf-LUA_REGISTRYINDEX"><code>LUA_REGISTRYINDEX</code></a>,
27232674which is a valid index.
27242675Any C&nbsp;library can store data into this table,
2725but it must take care to choose keys
2676but it should take care to choose keys
27262677that are different from those used
27272678by other libraries, to avoid collisions.
27282679Typically, you should use as key a string containing your library name,
27292680or a light userdata with the address of a C&nbsp;object in your code,
27302681or any Lua object created by your code.
2731As with variable names,
2682As with global names,
27322683string keys starting with an underscore followed by
27332684uppercase letters are reserved for Lua.
27342685
27352686
27362687<p>
2737The integer keys in the registry are used
2738by the reference mechanism (see <a href="#luaL_ref"><code>luaL_ref</code></a>)
2688The integer keys in the registry are used by the reference mechanism,
2689implemented by the auxiliary library,
27392690and by some predefined values.
2740Therefore, integer keys must not be used for other purposes.
2691Therefore, integer keys should not be used for other purposes.
27412692
27422693
27432694<p>
r242959r242960
27652716
27662717<p>
27672718Internally, Lua uses the C <code>longjmp</code> facility to handle errors.
2768(Lua will use exceptions if you compile it as C++;
2769search for <code>LUAI_THROW</code> in the source code for details.)
2719(You can also choose to use exceptions if you compile Lua as C++;
2720search for <code>LUAI_THROW</code> in the source code.)
27702721When Lua faces any error
27712722(such as a memory allocation error, type errors, syntax errors,
27722723and runtime errors)
r242959r242960
27902741<p>
27912742The panic function runs as if it were a message handler (see <a href="#2.3">&sect;2.3</a>);
27922743in particular, the error message is at the top of the stack.
2793However, there is no guarantee about stack space.
2744However, there is no guarantees about stack space.
27942745To push anything on the stack,
2795the panic function must first check the available space (see <a href="#4.2">&sect;4.2</a>).
2746the panic function should first check the available space (see <a href="#4.2">&sect;4.2</a>).
27962747
27972748
27982749<p>
2799Most functions in the API can raise an error,
2750Most functions in the API can throw an error,
28002751for instance due to a memory allocation error.
28012752The documentation for each function indicates whether
2802it can raise errors.
2753it can throw errors.
28032754
28042755
28052756<p>
2806Inside a C&nbsp;function you can raise an error by calling <a href="#lua_error"><code>lua_error</code></a>.
2757Inside a C&nbsp;function you can throw an error by calling <a href="#lua_error"><code>lua_error</code></a>.
28072758
28082759
28092760
r242959r242960
28132764
28142765<p>
28152766Internally, Lua uses the C <code>longjmp</code> facility to yield a coroutine.
2816Therefore, if a C function <code>foo</code> calls an API function
2767Therefore, if a function <code>foo</code> calls an API function
28172768and this API function yields
28182769(directly or indirectly by calling another function that yields),
28192770Lua cannot return to <code>foo</code> any more,
r242959r242960
28262777except for three functions:
28272778<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>.
28282779All those functions receive a <em>continuation function</em>
2829(as a parameter named <code>k</code>) to continue execution after a yield.
2780(as a parameter called <code>k</code>) to continue execution after a yield.
28302781
28312782
28322783<p>
r242959r242960
28562807
28572808
28582809<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>
29342810Lua treats the continuation function as if it were the original function.
29352811The continuation function receives the same Lua stack
29362812from the original function,
r242959r242960
29432819of the original function.
29442820
29452821
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>.
29462825
29472826
29482827
2828
2829
29492830<h2>4.8 &ndash; <a name="4.8">Functions and Types</a></h2>
29502831
29512832<p>
r242959r242960
29692850by looking only at its arguments
29702851(e.g., they may depend on what is on the stack).
29712852The third field, <code>x</code>,
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.
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.
29762857
29772858
29782859
r242959r242960
30042885<code>ptr</code>, a pointer to the block being allocated/reallocated/freed;
30052886<code>osize</code>, the original size of the block or some code about what
30062887is being allocated;
3007and <code>nsize</code>, the new size of the block.
2888<code>nsize</code>, the new size of the block.
30082889
30092890
30102891<p>
r242959r242960
30302911
30312912<p>
30322913When <code>nsize</code> is zero,
3033the allocator must behave like <code>free</code>
2914the allocator should behave like <code>free</code>
30342915and return <code>NULL</code>.
30352916
30362917
30372918<p>
30382919When <code>nsize</code> is not zero,
3039the allocator must behave like <code>realloc</code>.
2920the allocator should behave like <code>realloc</code>.
30402921The allocator returns <code>NULL</code>
30412922if and only if it cannot fulfill the request.
30422923Lua assumes that the allocator never fails when
r242959r242960
30612942</pre><p>
30622943Note that Standard&nbsp;C ensures
30632944that <code>free(NULL)</code> has no effect and that
3064<code>realloc(NULL,size)</code> is equivalent to <code>malloc(size)</code>.
2945<code>realloc(NULL, size)</code> is equivalent to <code>malloc(size)</code>.
30652946This code assumes that <code>realloc</code> does not fail when shrinking a block.
30662947(Although Standard&nbsp;C does not ensure this behavior,
30672948it seems to be a safe assumption.)
r242959r242960
30752956<pre>void lua_arith (lua_State *L, int op);</pre>
30762957
30772958<p>
3078Performs an arithmetic or bitwise operation over the two values
3079(or one, in the case of negations)
2959Performs an arithmetic operation over the two values
2960(or one, in the case of negation)
30802961at the top of the stack,
30812962with the value at the top being the second operand,
30822963pops these values, and pushes the result of the operation.
r242959r242960
30922973<li><b><a name="pdf-LUA_OPADD"><code>LUA_OPADD</code></a>: </b> performs addition (<code>+</code>)</li>
30932974<li><b><a name="pdf-LUA_OPSUB"><code>LUA_OPSUB</code></a>: </b> performs subtraction (<code>-</code>)</li>
30942975<li><b><a name="pdf-LUA_OPMUL"><code>LUA_OPMUL</code></a>: </b> performs multiplication (<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>
2976<li><b><a name="pdf-LUA_OPDIV"><code>LUA_OPDIV</code></a>: </b> performs division (<code>/</code>)</li>
30972977<li><b><a name="pdf-LUA_OPMOD"><code>LUA_OPMOD</code></a>: </b> performs modulo (<code>%</code>)</li>
30982978<li><b><a name="pdf-LUA_OPPOW"><code>LUA_OPPOW</code></a>: </b> performs exponentiation (<code>^</code>)</li>
30992979<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>
31062980
31072981</ul>
31082982
r242959r242960
31643038
31653039<pre>
31663040     lua_getglobal(L, "f");                  /* function to be called */
3167     lua_pushliteral(L, "how");                       /* 1st argument */
3041     lua_pushstring(L, "how");                        /* 1st argument */
31683042     lua_getglobal(L, "t");                    /* table to be indexed */
31693043     lua_getfield(L, -1, "x");        /* push result of t.x (2nd arg) */
31703044     lua_remove(L, -2);                  /* remove 't' from the stack */
r242959r242960
31723046     lua_call(L, 3, 1);     /* call 'f' with 3 arguments and 1 result */
31733047     lua_setglobal(L, "a");                         /* set global 'a' */
31743048</pre><p>
3175Note that the code above is <em>balanced</em>:
3049Note that the code above is "balanced":
31763050at its end, the stack is back to its original configuration.
31773051This is considered good programming practice.
31783052
r242959r242960
31823056
31833057<hr><h3><a name="lua_callk"><code>lua_callk</code></a></h3><p>
31843058<span class="apii">[-(nargs + 1), +nresults, <em>e</em>]</span>
3185<pre>void lua_callk (lua_State *L,
3186                int nargs,
3187                int nresults,
3188                lua_KContext ctx,
3189                lua_KFunction k);</pre>
3059<pre>void lua_callk (lua_State *L, int nargs, int nresults, int ctx,
3060                lua_CFunction k);</pre>
31903061
31913062<p>
31923063This function behaves exactly like <a href="#lua_call"><code>lua_call</code></a>,
r242959r242960
32243095
32253096<p>
32263097As an example, the following function receives a variable number
3227of numerical arguments and returns their average and their sum:
3098of numerical arguments and returns their average and sum:
32283099
32293100<pre>
32303101     static int foo (lua_State *L) {
32313102       int n = lua_gettop(L);    /* number of arguments */
3232       lua_Number sum = 0.0;
3103       lua_Number sum = 0;
32333104       int i;
32343105       for (i = 1; i &lt;= n; i++) {
32353106         if (!lua_isnumber(L, i)) {
3236           lua_pushliteral(L, "incorrect argument");
3107           lua_pushstring(L, "incorrect argument");
32373108           lua_error(L);
32383109         }
32393110         sum += lua_tonumber(L, i);
r242959r242960
32493120
32503121<hr><h3><a name="lua_checkstack"><code>lua_checkstack</code></a></h3><p>
32513122<span class="apii">[-0, +0, &ndash;]</span>
3252<pre>int lua_checkstack (lua_State *L, int n);</pre>
3123<pre>int lua_checkstack (lua_State *L, int extra);</pre>
32533124
32543125<p>
3255Ensures that the stack has space for at least <code>n</code> extra slots.
3126Ensures that there are at least <code>extra</code> free stack slots in the stack.
32563127It returns false if it cannot fulfill the request,
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.
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.
32613131This function never shrinks the stack;
32623132if the stack is already larger than the new size,
32633133it is left unchanged.
r242959r242960
32783148because all resources are naturally released when the host program ends.
32793149On the other hand, long-running programs that create multiple states,
32803150such as daemons or web servers,
3281will probably need to close states as soon as they are not needed.
3151might need to close states as soon as they are not needed.
32823152
32833153
32843154
r242959r242960
32953165following the semantics of the corresponding Lua operator
32963166(that is, it may call metamethods).
32973167Otherwise returns&nbsp;0.
3298Also returns&nbsp;0 if any of the indices is not valid.
3168Also returns&nbsp;0 if any of the indices is non valid.
32993169
33003170
33013171<p>
r242959r242960
33233193(that is, the function does nothing);
33243194if <code>n</code> is 0, the result is the empty string.
33253195Concatenation is performed following the usual semantics of Lua
3326(see <a href="#3.4.6">&sect;3.4.6</a>).
3196(see <a href="#3.4.5">&sect;3.4.5</a>).
33273197
33283198
33293199
r242959r242960
33343204<pre>void lua_copy (lua_State *L, int fromidx, int toidx);</pre>
33353205
33363206<p>
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.
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).
33413211
33423212
33433213
r242959r242960
33643234
33653235<hr><h3><a name="lua_dump"><code>lua_dump</code></a></h3><p>
33663236<span class="apii">[-0, +0, <em>e</em>]</span>
3367<pre>int lua_dump (lua_State *L,
3368                        lua_Writer writer,
3369                        void *data,
3370                        int strip);</pre>
3237<pre>int lua_dump (lua_State *L, lua_Writer writer, void *data);</pre>
33713238
33723239<p>
33733240Dumps a function as a binary chunk.
r242959r242960
33823249
33833250
33843251<p>
3385If <code>strip</code> is true,
3386the binary representation is created without debug information
3387about the function.
3388
3389
3390<p>
33913252The value returned is the error code returned by the last
33923253call to the writer;
339332540&nbsp;means no errors.
r242959r242960
34053266<pre>int lua_error (lua_State *L);</pre>
34063267
34073268<p>
3408Generates a Lua error,
3409using the value at the top of the stack as the error object.
3269Generates a Lua error.
3270The error message (which can actually be a Lua value of any type)
3271must be on the stack top.
34103272This function does a long jump,
34113273and therefore never returns
34123274(see <a href="#luaL_error"><code>luaL_error</code></a>).
r242959r242960
34523314
34533315<li><b><code>LUA_GCSTEP</code>: </b>
34543316performs 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.
34553323</li>
34563324
34573325<li><b><code>LUA_GCSETPAUSE</code>: </b>
34583326sets <code>data</code> as the new value
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.
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.
34613329</li>
34623330
34633331<li><b><code>LUA_GCSETSTEPMUL</code>: </b>
34643332sets <code>data</code> as the new value for the <em>step multiplier</em> of
3465the collector (see <a href="#2.5">&sect;2.5</a>)
3466and returns the previous value of the step multiplier.
3333the collector (see <a href="#2.5">&sect;2.5</a>).
3334The function returns the previous value of the step multiplier.
34673335</li>
34683336
34693337<li><b><code>LUA_GCISRUNNING</code>: </b>
r242959r242960
34713339(i.e., not stopped).
34723340</li>
34733341
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
34743352</ul>
34753353
34763354<p>
r242959r242960
34883366<p>
34893367Returns the memory-allocation function of a given state.
34903368If <code>ud</code> is not <code>NULL</code>, Lua stores in <code>*ud</code> the
3491opaque pointer given when the memory-allocator function was set.
3369opaque pointer passed to <a href="#lua_newstate"><code>lua_newstate</code></a>.
34923370
34933371
34943372
34953373
34963374
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>
3375<hr><h3><a name="lua_getctx"><code>lua_getctx</code></a></h3><p>
35163376<span class="apii">[-0, +0, &ndash;]</span>
3517<pre>void *lua_getextraspace (lua_State *L);</pre>
3377<pre>int lua_getctx (lua_State *L, int *ctx);</pre>
35183378
35193379<p>
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.
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.
35243382
35253383
35263384<p>
3527Each new thread has this area initialized with a copy
3528of the area of the main thread.
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).
35293393
35303394
35313395<p>
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>.)
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.
35353406
35363407
35373408
35383409
35393410
3540<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
3411<hr><h3><a name="lua_getfield"><code>lua_getfield</code></a></h3><p>
35413412<span class="apii">[-0, +1, <em>e</em>]</span>
3542<pre>int lua_getglobal (lua_State *L, const char *name);</pre>
3413<pre>void lua_getfield (lua_State *L, int index, const char *k);</pre>
35433414
35443415<p>
3545Pushes onto the stack the value of the global <code>name</code>.
3546Returns the type of that value.
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>).
35473420
35483421
35493422
35503423
35513424
3552<hr><h3><a name="lua_geti"><code>lua_geti</code></a></h3><p>
3425<hr><h3><a name="lua_getglobal"><code>lua_getglobal</code></a></h3><p>
35533426<span class="apii">[-0, +1, <em>e</em>]</span>
3554<pre>int lua_geti (lua_State *L, int index, lua_Integer i);</pre>
3427<pre>void lua_getglobal (lua_State *L, const char *name);</pre>
35553428
35563429<p>
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>).
3430Pushes onto the stack the value of the global <code>name</code>.
35613431
35623432
3563<p>
3564Returns the type of the pushed value.
35653433
35663434
35673435
3568
3569
35703436<hr><h3><a name="lua_getmetatable"><code>lua_getmetatable</code></a></h3><p>
35713437<span class="apii">[-0, +(0|1), &ndash;]</span>
35723438<pre>int lua_getmetatable (lua_State *L, int index);</pre>
35733439
35743440<p>
3575If the value at the given index has a metatable,
3576the function pushes that metatable onto the stack and returns&nbsp;1.
3577Otherwise,
3441Pushes onto the stack the metatable of the value at the given index.
3442If the value does not have a metatable,
35783443the function returns&nbsp;0 and pushes nothing on the stack.
35793444
35803445
r242959r242960
35833448
35843449<hr><h3><a name="lua_gettable"><code>lua_gettable</code></a></h3><p>
35853450<span class="apii">[-1, +1, <em>e</em>]</span>
3586<pre>int lua_gettable (lua_State *L, int index);</pre>
3451<pre>void lua_gettable (lua_State *L, int index);</pre>
35873452
35883453<p>
35893454Pushes onto the stack the value <code>t[k]</code>,
r242959r242960
35923457
35933458
35943459<p>
3595This function pops the key from the stack,
3596pushing the resulting value in its place.
3460This function pops the key from the stack
3461(putting the resulting value in its place).
35973462As in Lua, this function may trigger a metamethod
35983463for the "index" event (see <a href="#2.4">&sect;2.4</a>).
35993464
36003465
3601<p>
3602Returns the type of the pushed value.
36033466
36043467
36053468
3606
3607
36083469<hr><h3><a name="lua_gettop"><code>lua_gettop</code></a></h3><p>
36093470<span class="apii">[-0, +0, &ndash;]</span>
36103471<pre>int lua_gettop (lua_State *L);</pre>
r242959r242960
36123473<p>
36133474Returns the index of the top element in the stack.
36143475Because indices start at&nbsp;1,
3615this result is equal to the number of elements in the stack;
3616in particular, 0&nbsp;means an empty stack.
3476this result is equal to the number of elements in the stack
3477(and so 0&nbsp;means an empty stack).
36173478
36183479
36193480
r242959r242960
36213482
36223483<hr><h3><a name="lua_getuservalue"><code>lua_getuservalue</code></a></h3><p>
36233484<span class="apii">[-0, +1, &ndash;]</span>
3624<pre>int lua_getuservalue (lua_State *L, int index);</pre>
3485<pre>void lua_getuservalue (lua_State *L, int index);</pre>
36253486
36263487<p>
36273488Pushes onto the stack the Lua value associated with the userdata
36283489at the given index.
3490This Lua value must be a table or <b>nil</b>.
36293491
36303492
3631<p>
3632Returns the type of the pushed value.
36333493
36343494
36353495
3636
3637
36383496<hr><h3><a name="lua_insert"><code>lua_insert</code></a></h3><p>
36393497<span class="apii">[-1, +1, &ndash;]</span>
36403498<pre>void lua_insert (lua_State *L, int index);</pre>
r242959r242960
36503508
36513509
36523510<hr><h3><a name="lua_Integer"><code>lua_Integer</code></a></h3>
3653<pre>typedef ... lua_Integer;</pre>
3511<pre>typedef ptrdiff_t lua_Integer;</pre>
36543512
36553513<p>
3656The type of integers in Lua.
3514The type used by the Lua API to represent signed integral values.
36573515
36583516
36593517<p>
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>.)
3518By default it is a <code>ptrdiff_t</code>,
3519which is usually the largest signed integral type the machine handles
3520"comfortably".
36653521
36663522
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.
36713523
36723524
36733525
3674
3675
36763526<hr><h3><a name="lua_isboolean"><code>lua_isboolean</code></a></h3><p>
36773527<span class="apii">[-0, +0, &ndash;]</span>
36783528<pre>int lua_isboolean (lua_State *L, int index);</pre>
r242959r242960
37093559
37103560
37113561
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
37253562<hr><h3><a name="lua_islightuserdata"><code>lua_islightuserdata</code></a></h3><p>
37263563<span class="apii">[-0, +0, &ndash;]</span>
37273564<pre>int lua_islightuserdata (lua_State *L, int index);</pre>
r242959r242960
38333670
38343671
38353672
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
38733673<hr><h3><a name="lua_len"><code>lua_len</code></a></h3><p>
38743674<span class="apii">[-0, +1, <em>e</em>]</span>
38753675<pre>void lua_len (lua_State *L, int index);</pre>
38763676
38773677<p>
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>).
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>).
38813680The result is pushed on the stack.
38823681
38833682
r242959r242960
38893688<pre>int lua_load (lua_State *L,
38903689              lua_Reader reader,
38913690              void *data,
3892              const char *chunkname,
3691              const char *source,
38933692              const char *mode);</pre>
38943693
38953694<p>
3896Loads a Lua chunk without running it.
3695Loads a Lua chunk (without running it).
38973696If there are no errors,
38983697<code>lua_load</code> pushes the compiled chunk as a Lua
38993698function on top of the stack.
r242959r242960
39283727
39293728
39303729<p>
3931The <code>chunkname</code> argument gives a name to the chunk,
3730The <code>source</code> argument gives a name to the chunk,
39323731which is used for error messages and in debug information (see <a href="#4.9">&sect;4.9</a>).
39333732
39343733
r242959r242960
39423741
39433742<p>
39443743<code>lua_load</code> uses the stack internally,
3945so the reader function must always leave the stack
3744so the reader function should always leave the stack
39463745unmodified when returning.
39473746
39483747
39493748<p>
3950If the resulting function has upvalues,
3951its first upvalue is set to the value of the global environment
3749If the resulting function has one upvalue,
3750this upvalue is set to the value of the global environment
39523751stored at index <code>LUA_RIDX_GLOBALS</code> in the registry (see <a href="#4.5">&sect;4.5</a>).
39533752When loading main chunks,
39543753this 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>.
39563754
39573755
39583756
r242959r242960
39643762
39653763<p>
39663764Creates a new thread running in a new, independent state.
3967Returns <code>NULL</code> if it cannot create the thread or the state
3765Returns <code>NULL</code> if cannot create the thread or the state
39683766(due to lack of memory).
39693767The argument <code>f</code> is the allocator function;
39703768Lua does all memory allocation for this state through this function.
r242959r242960
40713869<pre>typedef double lua_Number;</pre>
40723870
40733871<p>
4074The type of floats in Lua.
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).
40753876
40763877
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>.)
40813878
40823879
40833880
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
41083881<hr><h3><a name="lua_pcall"><code>lua_pcall</code></a></h3><p>
41093882<span class="apii">[-(nargs + 1), +(nresults|1), &ndash;]</span>
41103883<pre>int lua_pcall (lua_State *L, int nargs, int nresults, int msgh);</pre>
r242959r242960
41483921
41493922
41503923<p>
4151The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following constants
3924The <a href="#lua_pcall"><code>lua_pcall</code></a> function returns one of the following codes
41523925(defined in <code>lua.h</code>):
41533926
41543927<ul>
r242959r242960
41713944
41723945<li><b><a name="pdf-LUA_ERRGCMM"><code>LUA_ERRGCMM</code></a>: </b>
41733946error while running a <code>__gc</code> metamethod.
4174(This error typically has no relation with the function being called.)
3947(This error typically has no relation with the function being called.
3948It is generated by the garbage collector.)
41753949</li>
41763950
41773951</ul>
r242959r242960
41843958<pre>int lua_pcallk (lua_State *L,
41853959                int nargs,
41863960                int nresults,
4187                int msgh,
4188                lua_KContext ctx,
4189                lua_KFunction k);</pre>
3961                int errfunc,
3962                int ctx,
3963                lua_CFunction k);</pre>
41903964
41913965<p>
41923966This function behaves exactly like <a href="#lua_pcall"><code>lua_pcall</code></a>,
r242959r242960
42324006thus creating a C&nbsp;closure (see <a href="#4.4">&sect;4.4</a>);
42334007these values are then accessible to the function whenever it is called.
42344008To associate values with a C&nbsp;function,
4235first these values must be pushed onto the stack
4009first these values should be pushed onto the stack
42364010(when there are multiple values, the first value is pushed first).
42374011Then <a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a>
42384012is called to create and push the C&nbsp;function onto the stack,
4239with the argument <code>n</code> telling how many values will be
4013with the argument <code>n</code> telling how many values should be
42404014associated with the function.
42414015<a href="#lua_pushcclosure"><code>lua_pushcclosure</code></a> also pops these values from the stack.
42424016
r242959r242960
42494023When <code>n</code> is zero,
42504024this function creates a <em>light C function</em>,
42514025which is just a pointer to the C&nbsp;function.
4252In that case, it never raises a memory error.
4026In that case, it never throws a memory error.
42534027
42544028
42554029
r242959r242960
42914065<p>
42924066Pushes onto the stack a formatted string
42934067and returns a pointer to this string.
4294It is similar to the ISO&nbsp;C function <code>sprintf</code>,
4068It is similar to the ANSI&nbsp;C function <code>sprintf</code>,
42954069but has some important differences:
42964070
42974071<ul>
r242959r242960
43064080The conversion specifiers are quite restricted.
43074081There are no flags, widths, or precisions.
43084082The conversion specifiers can only be
4309'<code>%%</code>' (inserts the character '<code>%</code>'),
4083'<code>%%</code>' (inserts a '<code>%</code>' in the string),
43104084'<code>%s</code>' (inserts a zero-terminated string, with no size restrictions),
43114085'<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>),
43134086'<code>%p</code>' (inserts a pointer as a hexadecimal numeral),
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).
4087'<code>%d</code>' (inserts an <code>int</code>), and
4088'<code>%c</code>' (inserts an <code>int</code> as a byte).
43174089</li>
43184090
43194091</ul>
r242959r242960
43374109<pre>void lua_pushinteger (lua_State *L, lua_Integer n);</pre>
43384110
43394111<p>
4340Pushes an integer with value <code>n</code> onto the stack.
4112Pushes a number with value <code>n</code> onto the stack.
43414113
43424114
43434115
r242959r242960
44144186<pre>void lua_pushnumber (lua_State *L, lua_Number n);</pre>
44154187
44164188<p>
4417Pushes a float with value <code>n</code> onto the stack.
4189Pushes a number with value <code>n</code> onto the stack.
44184190
44194191
44204192
r242959r242960
44554227
44564228
44574229
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
44584241<hr><h3><a name="lua_pushvalue"><code>lua_pushvalue</code></a></h3><p>
44594242<span class="apii">[-0, +1, &ndash;]</span>
44604243<pre>void lua_pushvalue (lua_State *L, int index);</pre>
r242959r242960
44904273<code>index2</code> are primitively equal
44914274(that is, without calling metamethods).
44924275Otherwise returns&nbsp;0.
4493Also returns&nbsp;0 if any of the indices are not valid.
4276Also returns&nbsp;0 if any of the indices are non valid.
44944277
44954278
44964279
r242959r242960
44984281
44994282<hr><h3><a name="lua_rawget"><code>lua_rawget</code></a></h3><p>
45004283<span class="apii">[-1, +1, &ndash;]</span>
4501<pre>int lua_rawget (lua_State *L, int index);</pre>
4284<pre>void lua_rawget (lua_State *L, int index);</pre>
45024285
45034286<p>
45044287Similar to <a href="#lua_gettable"><code>lua_gettable</code></a>, but does a raw access
r242959r242960
45104293
45114294<hr><h3><a name="lua_rawgeti"><code>lua_rawgeti</code></a></h3><p>
45124295<span class="apii">[-0, +1, &ndash;]</span>
4513<pre>int lua_rawgeti (lua_State *L, int index, lua_Integer n);</pre>
4296<pre>void lua_rawgeti (lua_State *L, int index, int n);</pre>
45144297
45154298<p>
45164299Pushes onto the stack the value <code>t[n]</code>,
r242959r242960
45194302that is, it does not invoke metamethods.
45204303
45214304
4522<p>
4523Returns the type of the pushed value.
45244305
45254306
45264307
4527
4528
45294308<hr><h3><a name="lua_rawgetp"><code>lua_rawgetp</code></a></h3><p>
45304309<span class="apii">[-0, +1, &ndash;]</span>
4531<pre>int lua_rawgetp (lua_State *L, int index, const void *p);</pre>
4310<pre>void lua_rawgetp (lua_State *L, int index, const void *p);</pre>
45324311
45334312<p>
45344313Pushes onto the stack the value <code>t[k]</code>,
r242959r242960
45384317that is, it does not invoke metamethods.
45394318
45404319
4541<p>
4542Returns the type of the pushed value.
45434320
45444321
45454322
4546
4547
45484323<hr><h3><a name="lua_rawlen"><code>lua_rawlen</code></a></h3><p>
45494324<span class="apii">[-0, +0, &ndash;]</span>
45504325<pre>size_t lua_rawlen (lua_State *L, int index);</pre>
r242959r242960
45764351
45774352<hr><h3><a name="lua_rawseti"><code>lua_rawseti</code></a></h3><p>
45784353<span class="apii">[-1, +0, <em>e</em>]</span>
4579<pre>void lua_rawseti (lua_State *L, int index, lua_Integer i);</pre>
4354<pre>void lua_rawseti (lua_State *L, int index, int n);</pre>
45804355
45814356<p>
4582Does the equivalent of <code>t[i] = v</code>,
4357Does the equivalent of <code>t[n] = v</code>,
45834358where <code>t</code> is the table at the given index
45844359and <code>v</code> is the value at the top of the stack.
45854360
r242959r242960
47264501
47274502
47284503
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
47454504<hr><h3><a name="lua_setallocf"><code>lua_setallocf</code></a></h3><p>
47464505<span class="apii">[-0, +0, &ndash;]</span>
47474506<pre>void lua_setallocf (lua_State *L, lua_Alloc f, void *ud);</pre>
r242959r242960
47854544
47864545
47874546
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
48074547<hr><h3><a name="lua_setmetatable"><code>lua_setmetatable</code></a></h3><p>
48084548<span class="apii">[-1, +0, &ndash;]</span>
48094549<pre>void lua_setmetatable (lua_State *L, int index);</pre>
r242959r242960
48564596<pre>void lua_setuservalue (lua_State *L, int index);</pre>
48574597
48584598<p>
4859Pops a value from the stack and sets it as
4599Pops a table or <b>nil</b> from the stack and sets it as
48604600the new value associated to the userdata at the given index.
48614601
48624602
r242959r242960
49084648
49094649
49104650
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
49324651<hr><h3><a name="lua_toboolean"><code>lua_toboolean</code></a></h3><p>
49334652<span class="apii">[-0, +0, &ndash;]</span>
49344653<pre>int lua_toboolean (lua_State *L, int index);</pre>
r242959r242960
49784697<p>
49794698Converts the Lua value at the given index
49804699to the signed integral type <a href="#lua_Integer"><code>lua_Integer</code></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>);
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>);
49834702otherwise, <code>lua_tointegerx</code> returns&nbsp;0.
49844703
49854704
49864705<p>
4706If the number is not an integer,
4707it is truncated in some non-specified way.
4708
4709
4710<p>
49874711If <code>isnum</code> is not <code>NULL</code>,
49884712its referent is assigned a boolean value that
49894713indicates whether the operation succeeded.
r242959r242960
50154739This string always has a zero ('<code>\0</code>')
50164740after its last character (as in&nbsp;C),
50174741but can contain other zeros in its body.
5018
5019
5020<p>
50214742Because Lua has garbage collection,
50224743there is no guarantee that the pointer returned by <code>lua_tolstring</code>
5023will be valid after the corresponding Lua value is removed from the stack.
4744will be valid after the corresponding value is removed from the stack.
50244745
50254746
50264747
r242959r242960
50454766Converts the Lua value at the given index
50464767to the C&nbsp;type <a href="#lua_Number"><code>lua_Number</code></a> (see <a href="#lua_Number"><code>lua_Number</code></a>).
50474768The Lua value must be a number or a string convertible to a number
5048(see <a href="#3.4.3">&sect;3.4.3</a>);
4769(see <a href="#3.4.2">&sect;3.4.2</a>);
50494770otherwise, <a href="#lua_tonumberx"><code>lua_tonumberx</code></a> returns&nbsp;0.
50504771
50514772
r242959r242960
51034824
51044825
51054826
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
51064867<hr><h3><a name="lua_touserdata"><code>lua_touserdata</code></a></h3><p>
51074868<span class="apii">[-0, +0, &ndash;]</span>
51084869<pre>void *lua_touserdata (lua_State *L, int index);</pre>
r242959r242960
51554916
51564917
51574918<hr><h3><a name="lua_Unsigned"><code>lua_Unsigned</code></a></h3>
5158<pre>typedef ... lua_Unsigned;</pre>
4919<pre>typedef unsigned long lua_Unsigned;</pre>
51594920
51604921<p>
5161The unsigned version of <a href="#lua_Integer"><code>lua_Integer</code></a>.
4922The type used by the Lua API to represent unsigned integral values.
4923It must have at least 32 bits.
51624924
51634925
4926<p>
4927By default it is an <code>unsigned int</code> or an <code>unsigned long</code>,
4928whichever can hold 32-bit values.
51644929
51654930
51664931
4932
4933
51674934<hr><h3><a name="lua_upvalueindex"><code>lua_upvalueindex</code></a></h3><p>
51684935<span class="apii">[-0, +0, &ndash;]</span>
51694936<pre>int lua_upvalueindex (int i);</pre>
r242959r242960
52335000
52345001
52355002<hr><h3><a name="lua_yield"><code>lua_yield</code></a></h3><p>
5236<span class="apii">[-?, +?, <em>e</em>]</span>
5003<span class="apii">[-?, +?, &ndash;]</span>
52375004<pre>int lua_yield (lua_State *L, int nresults);</pre>
52385005
52395006<p>
52405007This function is equivalent to <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
52415008but it has no continuation (see <a href="#4.7">&sect;4.7</a>).
52425009Therefore, when the thread resumes,
5243it continues the function that called
5010it returns to the function that called
52445011the function calling <code>lua_yield</code>.
52455012
52465013
r242959r242960
52485015
52495016
52505017<hr><h3><a name="lua_yieldk"><code>lua_yieldk</code></a></h3><p>
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>
5018<span class="apii">[-?, +?, &ndash;]</span>
5019<pre>int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k);</pre>
52565020
52575021<p>
5258Yields a coroutine (thread).
5022Yields a coroutine.
52595023
52605024
52615025<p>
5262When a C&nbsp;function calls <a href="#lua_yieldk"><code>lua_yieldk</code></a>,
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,
52635033the running coroutine suspends its execution,
52645034and the call to <a href="#lua_resume"><code>lua_resume</code></a> that started this coroutine returns.
52655035The parameter <code>nresults</code> is the number of values from the stack
5266that will be passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
5036that are passed as results to <a href="#lua_resume"><code>lua_resume</code></a>.
52675037
52685038
52695039<p>
r242959r242960
52725042the execution of the C function that yielded (see <a href="#4.7">&sect;4.7</a>).
52735043This continuation function receives the same stack
52745044from the previous function,
5275with the <code>n</code> results removed and
5045with the results removed and
52765046replaced by the arguments passed to <a href="#lua_resume"><code>lua_resume</code></a>.
52775047Moreover,
5278the continuation function receives the value <code>ctx</code>
5279that was passed to <a href="#lua_yieldk"><code>lua_yieldk</code></a>.
5048the continuation function may access the value <code>ctx</code>
5049by calling <a href="#lua_getctx"><code>lua_getctx</code></a>.
52805050
52815051
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.
52965052
52975053
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).
53035054
53045055
53055056
5306
5307
5308
5309
53105057<h2>4.9 &ndash; <a name="4.9">The Debug Interface</a></h2>
53115058
53125059<p>
r242959r242960
53535100<ul>
53545101
53555102<li><b><code>source</code>: </b>
5356the name of the chunk that created the function.
5103the source of the chunk that created the function.
53575104If <code>source</code> starts with a '<code>@</code>',
53585105it means that the function was defined in a file where
53595106the file name follows the '<code>@</code>'.
r242959r242960
55325279(A <em>valid line</em> is a line with some associated code,
55335280that is, a line where you can put a break point.
55345281Non-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.
55405282</li>
55415283
55425284</ul>
r242959r242960
55515293
55525294<hr><h3><a name="lua_getlocal"><code>lua_getlocal</code></a></h3><p>
55535295<span class="apii">[-0, +(0|1), &ndash;]</span>
5554<pre>const char *lua_getlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
5296<pre>const char *lua_getlocal (lua_State *L, lua_Debug *ar, int n);</pre>
55555297
55565298<p>
55575299Gets information about a local variable of
r242959r242960
55745316
55755317
55765318<p>
5577In the second case, <code>ar</code> must be <code>NULL</code> and the function
5319In the second case, <code>ar</code> should be <code>NULL</code> and the function
55785320to be inspected must be at the top of the stack.
55795321In this case, only parameters of Lua functions are visible
55805322(as there is no information about what variables are active)
r242959r242960
56915433
56925434<hr><h3><a name="lua_sethook"><code>lua_sethook</code></a></h3><p>
56935435<span class="apii">[-0, +0, &ndash;]</span>
5694<pre>void lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
5436<pre>int lua_sethook (lua_State *L, lua_Hook f, int mask, int count);</pre>
56955437
56965438<p>
56975439Sets the debugging hook function.
r242959r242960
57445486
57455487<hr><h3><a name="lua_setlocal"><code>lua_setlocal</code></a></h3><p>
57465488<span class="apii">[-(0|1), +0, &ndash;]</span>
5747<pre>const char *lua_setlocal (lua_State *L, const lua_Debug *ar, int n);</pre>
5489<pre>const char *lua_setlocal (lua_State *L, lua_Debug *ar, int n);</pre>
57485490
57495491<p>
57505492Sets the value of a local variable of a given activation record.
r242959r242960
57905532<pre>void *lua_upvalueid (lua_State *L, int funcindex, int n);</pre>
57915533
57925534<p>
5793Returns a unique identifier for the upvalue numbered <code>n</code>
5535Returns an unique identifier for the upvalue numbered <code>n</code>
57945536from the closure at index <code>funcindex</code>.
57955537Parameters <code>funcindex</code> and <code>n</code> are as in the <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>
57965538(see <a href="#lua_getupvalue"><code>lua_getupvalue</code></a>)
r242959r242960
58675609
58685610<p>
58695611Functions called <code>luaL_check*</code>
5870always raise an error if the check is not satisfied.
5612always throw an error if the check is not satisfied.
58715613
58725614
58735615
r242959r242960
59265668Adds the zero-terminated string pointed to by <code>s</code>
59275669to the buffer <code>B</code>
59285670(see <a href="#luaL_Buffer"><code>luaL_Buffer</code></a>).
5671The string cannot contain embedded zeros.
59295672
59305673
59315674
r242959r242960
59605703
59615704<p>
59625705Checks whether <code>cond</code> is true.
5963If it is not, raises an error with a standard message (see <a href="#luaL_argerror"><code>luaL_argerror</code></a>).
5706If not, raises an error with a standard message.
59645707
59655708
59665709
r242959r242960
59715714<pre>int luaL_argerror (lua_State *L, int arg, const char *extramsg);</pre>
59725715
59735716<p>
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:
5717Raises an error with a standard message
5718that includes <code>extramsg</code> as a comment.
59785719
5979<pre>
5980     bad argument #<em>arg</em> to '<em>funcname</em>' (<em>extramsg</em>)
5981</pre><p>
5982This function never returns.
59835720
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>.
59845725
59855726
59865727
59875728
5729
59885730<hr><h3><a name="luaL_Buffer"><code>luaL_Buffer</code></a></h3>
59895731<pre>typedef struct luaL_Buffer luaL_Buffer;</pre>
59905732
r242959r242960
61145856
61155857
61165858
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
61175871<hr><h3><a name="luaL_checkinteger"><code>luaL_checkinteger</code></a></h3><p>
61185872<span class="apii">[-0, +0, <em>v</em>]</span>
61195873<pre>lua_Integer luaL_checkinteger (lua_State *L, int arg);</pre>
61205874
61215875<p>
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>.
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>.
61255878
61265879
61275880
61285881
61295882
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
61305895<hr><h3><a name="luaL_checklstring"><code>luaL_checklstring</code></a></h3><p>
61315896<span class="apii">[-0, +0, <em>v</em>]</span>
61325897<pre>const char *luaL_checklstring (lua_State *L, int arg, size_t *l);</pre>
r242959r242960
62456010
62466011
62476012
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
62486025<hr><h3><a name="luaL_checkversion"><code>luaL_checkversion</code></a></h3><p>
62496026<span class="apii">[-0, +0, &ndash;]</span>
62506027<pre>void luaL_checkversion (lua_State *L);</pre>
r242959r242960
63526129
63536130<p>
63546131Pushes onto the stack the field <code>e</code> from the metatable
6355of the object at index <code>obj</code> and returns the type of pushed value.
6132of the object at index <code>obj</code>.
63566133If the object does not have a metatable,
63576134or if the metatable does not have this field,
6358pushes nothing and returns <code>LUA_TNIL</code>.
6135returns false and pushes nothing.
63596136
63606137
63616138
r242959r242960
63636140
63646141<hr><h3><a name="luaL_getmetatable"><code>luaL_getmetatable</code></a></h3><p>
63656142<span class="apii">[-0, +1, &ndash;]</span>
6366<pre>int luaL_getmetatable (lua_State *L, const char *tname);</pre>
6143<pre>void luaL_getmetatable (lua_State *L, const char *tname);</pre>
63676144
63686145<p>
63696146Pushes onto the stack the metatable associated with name <code>tname</code>
63706147in 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>.
63736148
63746149
63756150
r242959r242960
64106185
64116186<hr><h3><a name="luaL_len"><code>luaL_len</code></a></h3><p>
64126187<span class="apii">[-0, +0, <em>e</em>]</span>
6413<pre>lua_Integer luaL_len (lua_State *L, int index);</pre>
6188<pre>int luaL_len (lua_State *L, int index);</pre>
64146189
64156190<p>
64166191Returns the "length" of the value at the given index
64176192as 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.
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.
64206195(This case only can happen through metamethods.)
64216196
64226197
r242959r242960
65286303
65296304<hr><h3><a name="luaL_newlib"><code>luaL_newlib</code></a></h3><p>
65306305<span class="apii">[-0, +1, <em>e</em>]</span>
6531<pre>void luaL_newlib (lua_State *L, const luaL_Reg l[]);</pre>
6306<pre>void luaL_newlib (lua_State *L, const luaL_Reg *l);</pre>
65326307
65336308<p>
65346309Creates a new table and registers there
65356310the functions in list <code>l</code>.
6536
6537
6538<p>
65396311It is implemented as the following macro:
65406312
65416313<pre>
65426314     (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
6543</pre><p>
6544The array <code>l</code> must be the actual array,
6545not a pointer to it.
6315</pre>
65466316
65476317
65486318
65496319
6550
65516320<hr><h3><a name="luaL_newlibtable"><code>luaL_newlibtable</code></a></h3><p>
65526321<span class="apii">[-0, +1, <em>e</em>]</span>
65536322<pre>void luaL_newlibtable (lua_State *L, const luaL_Reg l[]);</pre>
r242959r242960
65786347returns 0.
65796348Otherwise,
65806349creates a new table to be used as a metatable for userdata,
6581adds to this new table the pair <code>__name = tname</code>,
6582adds to the registry the pair <code>[tname] = new table</code>,
6350adds it to the registry with key <code>tname</code>,
65836351and returns 1.
6584(The entry <code>__name</code> is used by some error-reporting functions.)
65856352
65866353
65876354<p>
r242959r242960
66246391
66256392
66266393
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
66276409<hr><h3><a name="luaL_optinteger"><code>luaL_optinteger</code></a></h3><p>
66286410<span class="apii">[-0, +0, <em>v</em>]</span>
66296411<pre>lua_Integer luaL_optinteger (lua_State *L,
r242959r242960
66316413                             lua_Integer d);</pre>
66326414
66336415<p>
6634If the function argument <code>arg</code> is an integer
6635(or convertible to an integer),
6636returns this integer.
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>.
66376418If this argument is absent or is <b>nil</b>,
66386419returns <code>d</code>.
66396420Otherwise, raises an error.
r242959r242960
66426423
66436424
66446425
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
66456441<hr><h3><a name="luaL_optlstring"><code>luaL_optlstring</code></a></h3><p>
66466442<span class="apii">[-0, +0, <em>v</em>]</span>
66476443<pre>const char *luaL_optlstring (lua_State *L,
r242959r242960
66976493
66986494
66996495
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
67006513<hr><h3><a name="luaL_prepbuffer"><code>luaL_prepbuffer</code></a></h3><p>
67016514<span class="apii">[-?, +?, <em>e</em>]</span>
67026515<pre>char *luaL_prepbuffer (luaL_Buffer *B);</pre>
r242959r242960
67886601<a href="#luaL_setfuncs"><code>luaL_setfuncs</code></a>.
67896602<code>name</code> is the function name and <code>func</code> is a pointer to
67906603the function.
6791Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with a sentinel entry
6604Any array of <a href="#luaL_Reg"><code>luaL_Reg</code></a> must end with an sentinel entry
67926605in which both <code>name</code> and <code>func</code> are <code>NULL</code>.
67936606
67946607
r242959r242960
68016614                    lua_CFunction openf, int glb);</pre>
68026615
68036616<p>
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
6617Calls function <code>openf</code> with string <code>modname</code> as an argument
68066618and sets the call result in <code>package.loaded[modname]</code>,
68076619as if that function has been called through <a href="#pdf-require"><code>require</code></a>.
68086620
68096621
68106622<p>
68116623If <code>glb</code> is true,
6812also stores the module into global <code>modname</code>.
6624also stores the result into global <code>modname</code>.
68136625
68146626
68156627<p>
6816Leaves a copy of the module on the stack.
6628Leaves a copy of that result on the stack.
68176629
68186630
68196631
r242959r242960
68536665
68546666
68556667
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
68946668<hr><h3><a name="luaL_testudata"><code>luaL_testudata</code></a></h3><p>
68956669<span class="apii">[-0, +0, <em>e</em>]</span>
68966670<pre>void *luaL_testudata (lua_State *L, int arg, const char *tname);</pre>
r242959r242960
68986672<p>
68996673This function works like <a href="#luaL_checkudata"><code>luaL_checkudata</code></a>,
69006674except that, when the test fails,
6901it returns <code>NULL</code> instead of raising an error.
6675it returns <code>NULL</code> instead of throwing an error.
69026676
69036677
69046678
r242959r242960
70286802
70296803<li>string manipulation (<a href="#6.4">&sect;6.4</a>);</li>
70306804
7031<li>basic UTF-8 support (<a href="#6.5">&sect;6.5</a>);</li>
6805<li>table manipulation (<a href="#6.5">&sect;6.5</a>);</li>
70326806
7033<li>table manipulation (<a href="#6.6">&sect;6.6</a>);</li>
6807<li>mathematical functions (<a href="#6.6">&sect;6.6</a>) (sin, log, etc.);</li>
70346808
7035<li>mathematical functions (<a href="#6.7">&sect;6.7</a>) (sin, log, etc.);</li>
6809<li>bitwise operations (<a href="#6.7">&sect;6.7</a>);</li>
70366810
70376811<li>input and output (<a href="#6.8">&sect;6.8</a>);</li>
70386812
r242959r242960
70576831<a name="pdf-luaopen_package"><code>luaopen_package</code></a> (for the package library),
70586832<a name="pdf-luaopen_coroutine"><code>luaopen_coroutine</code></a> (for the coroutine library),
70596833<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),
70616834<a name="pdf-luaopen_table"><code>luaopen_table</code></a> (for the table library),
70626835<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),
70636837<a name="pdf-luaopen_io"><code>luaopen_io</code></a> (for the I/O library),
7064<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the operating system library),
6838<a name="pdf-luaopen_os"><code>luaopen_os</code></a> (for the Operating System library),
70656839and <a name="pdf-luaopen_debug"><code>luaopen_debug</code></a> (for the debug library).
70666840These functions are declared in <a name="pdf-lualib.h"><code>lualib.h</code></a>.
70676841
r242959r242960
70786852
70796853<p>
70806854<hr><h3><a name="pdf-assert"><code>assert (v [, message])</code></a></h3>
7081
7082
7083<p>
7084Calls <a href="#pdf-error"><code>error</code></a> if
6855Issues an  error when
70856856the value of its argument <code>v</code> is false (i.e., <b>nil</b> or <b>false</b>);
70866857otherwise, returns all its arguments.
7087In case of error,
7088<code>message</code> is the error object;
7089when absent, it defaults to "<code>assertion failed!</code>"
6858<code>message</code> is an error message;
6859when absent, it defaults to "assertion failed!"
70906860
70916861
70926862
r242959r242960
71176887</li>
71186888
71196889<li><b>"<code>count</code>": </b>
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).
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.)
71256901</li>
71266902
71276903<li><b>"<code>step</code>": </b>
71286904performs a garbage-collection step.
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.
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>.
71356909Returns <b>true</b> if the step finished a collection cycle.
71366910</li>
71376911
r242959r242960
71526926(i.e., not stopped).
71536927</li>
71546928
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
71556939</ul>
71566940
71576941
r242959r242960
71716955<p>
71726956<hr><h3><a name="pdf-error"><code>error (message [, level])</code></a></h3>
71736957Terminates the last protected function called
7174and returns <code>message</code> as the error object.
6958and returns <code>message</code> as the error message.
71756959Function <code>error</code> never returns.
71766960
71776961
r242959r242960
71956979holds the global environment (see <a href="#2.2">&sect;2.2</a>).
71966980Lua itself does not use this variable;
71976981changing its value does not affect any environment,
7198nor vice versa.
6982nor vice-versa.
71996983
72006984
72016985
r242959r242960
72197003
72207004
72217005<p>
7222Returns three values (an iterator function, the table <code>t</code>, and 0)
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,
72237014so that the construction
72247015
72257016<pre>
72267017     for i,v in ipairs(t) do <em>body</em> end
72277018</pre><p>
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.
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.
72317021
72327022
72337023
72347024
72357025<p>
7236<hr><h3><a name="pdf-load"><code>load (chunk [, chunkname [, mode [, env]]])</code></a></h3>
7026<hr><h3><a name="pdf-load"><code>load (ld [, source [, mode [, env]]])</code></a></h3>
72377027
72387028
72397029<p>
r242959r242960
72417031
72427032
72437033<p>
7244If <code>chunk</code> is a string, the chunk is this string.
7245If <code>chunk</code> is a function,
7034If <code>ld</code> is a string, the chunk is this string.
7035If <code>ld</code> is a function,
72467036<code>load</code> calls it repeatedly to get the chunk pieces.
7247Each call to <code>chunk</code> must return a string that concatenates
7037Each call to <code>ld</code> must return a string that concatenates
72487038with previous results.
72497039A return of an empty string, <b>nil</b>, or no value signals the end of the chunk.
72507040
r242959r242960
72607050the first upvalue is set to the value of <code>env</code>,
72617051if that parameter is given,
72627052or to the value of the global environment.
7263Other upvalues are initialized with <b>nil</b>.
72647053(When you load a main chunk,
72657054the resulting function will always have exactly one upvalue,
72667055the <code>_ENV</code> variable (see <a href="#2.2">&sect;2.2</a>).
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.
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.)
72727058
72737059
72747060<p>
7275<code>chunkname</code> is used as the name of the chunk for error messages
7061<code>source</code> is used as the source of the chunk for error messages
72767062and debug information (see <a href="#4.9">&sect;4.9</a>).
72777063When absent,
7278it defaults to <code>chunk</code>, if <code>chunk</code> is a string,
7064it defaults to <code>ld</code>, if <code>ld</code> is a string,
72797065or to "<code>=(load)</code>" otherwise.
72807066
72817067
r242959r242960
72887074The default is "<code>bt</code>".
72897075
72907076
7291<p>
7292Lua does not check the consistency of binary chunks.
7293Maliciously crafted binary chunks can crash
7294the interpreter.
72957077
72967078
7297
7298
72997079<p>
73007080<hr><h3><a name="pdf-loadfile"><code>loadfile ([filename [, mode [, env]]])</code></a></h3>
73017081
r242959r242960
74327212Returns the length of the object <code>v</code>,
74337213which must be a table or a string,
74347214without invoking any metamethod.
7435Returns an integer.
7215Returns an integer number.
74367216
74377217
74387218
r242959r242960
74937273When called with no <code>base</code>,
74947274<code>tonumber</code> tries to convert its argument to a number.
74957275If the argument is already a number or
7496a string convertible to a number,
7276a string convertible to a number (see <a href="#3.4.2">&sect;3.4.2</a>),
74977277then <code>tonumber</code> returns this number;
74987278otherwise, it returns <b>nil</b>.
74997279
75007280
75017281<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>
75087282When called with <code>base</code>,
7509then <code>e</code> must be a string to be interpreted as
7283then <code>e</code> should be a string to be interpreted as
75107284an integer numeral in that base.
75117285The base may be any integer between 2 and 36, inclusive.
75127286In bases above&nbsp;10, the letter '<code>A</code>' (in either upper or lower case)
r242959r242960
75217295<p>
75227296<hr><h3><a name="pdf-tostring"><code>tostring (v)</code></a></h3>
75237297Receives a value of any type and
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).
7298converts it to a string in a reasonable format.
75277299(For complete control of how numbers are converted,
75287300use <a href="#pdf-string.format"><code>string.format</code></a>.)
75297301
r242959r242960
75577329<hr><h3><a name="pdf-_VERSION"><code>_VERSION</code></a></h3>
75587330A global variable (not a function) that
75597331holds a string containing the current interpreter version.
7560The current value of this variable is "<code>Lua 5.3</code>".
7332The current contents of this variable is "<code>Lua 5.2</code>".
75617333
75627334
75637335
r242959r242960
75987370
75997371
76007372<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>
76167373<hr><h3><a name="pdf-coroutine.resume"><code>coroutine.resume (co [, val1, &middot;&middot;&middot;])</code></a></h3>
76177374
76187375
r242959r242960
76317388<p>
76327389If the coroutine runs without any errors,
76337390<code>resume</code> returns <b>true</b> plus any values passed to <code>yield</code>
7634(when the coroutine yields) or any values returned by the body function
7635(when the coroutine terminates).
7391(if the coroutine yields) or any values returned by the body function
7392(if the coroutine terminates).
76367393If there is any error,
76377394<code>resume</code> returns <b>false</b> plus the error message.
76387395
r242959r242960
77347491<p>
77357492First <code>require</code> queries <code>package.preload[modname]</code>.
77367493If it has a value,
7737this value (which must be a function) is the loader.
7494this value (which should be a function) is the loader.
77387495Otherwise <code>require</code> searches for a Lua loader using the
77397496path stored in <a href="#pdf-package.path"><code>package.path</code></a>.
77407497If that also fails, it searches for a C&nbsp;loader using the
r242959r242960
77907547is replaced by the executable's directory.
77917548Default is '<code>!</code>'.</li>
77927549
7793<li>The fifth line is a mark to ignore all text after it
7550<li>The fifth line is a mark to ignore all text before it
77947551when building the <code>luaopen_</code> function name.
77957552Default is '<code>-</code>'.</li>
77967553
r242959r242960
78097566<p>
78107567Lua initializes the C&nbsp;path <a href="#pdf-package.cpath"><code>package.cpath</code></a> in the same way
78117568it initializes the Lua path <a href="#pdf-package.path"><code>package.path</code></a>,
7812using the environment variable <a name="pdf-LUA_CPATH_5_3"><code>LUA_CPATH_5_3</code></a>
7569using the environment variable <a name="pdf-LUA_CPATH_5_2"><code>LUA_CPATH_5_2</code></a>
78137570or the environment variable <a name="pdf-LUA_CPATH"><code>LUA_CPATH</code></a>
78147571or a default path defined in <code>luaconf.h</code>.
78157572
r242959r242960
78877644
78887645<p>
78897646At start-up, Lua initializes this variable with
7890the value of the environment variable <a name="pdf-LUA_PATH_5_3"><code>LUA_PATH_5_3</code></a> or
7647the value of the environment variable <a name="pdf-LUA_PATH_5_2"><code>LUA_PATH_5_2</code></a> or
78917648the environment variable <a name="pdf-LUA_PATH"><code>LUA_PATH</code></a> or
78927649with a default path defined in <code>luaconf.h</code>,
78937650if those environment variables are not defined.
r242959r242960
79727729concatenated with a copy of the module name where each dot
79737730is replaced by an underscore.
79747731Moreover, if the module name has a hyphen,
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>.
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>.
79787735
79797736
79807737<p>
r242959r242960
81027859
81037860
81047861<p>
8105<hr><h3><a name="pdf-string.dump"><code>string.dump (function [, strip])</code></a></h3>
7862<hr><h3><a name="pdf-string.dump"><code>string.dump (function)</code></a></h3>
81067863
81077864
81087865<p>
8109Returns a string containing a binary representation
8110(a <em>binary chunk</em>)
8111of the given function,
7866Returns a string containing a binary representation of the given function,
81127867so that a later <a href="#pdf-load"><code>load</code></a> on this string returns
81137868a 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.).
81187869
81197870
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.)
81277871
81287872
8129
8130
81317873<p>
81327874<hr><h3><a name="pdf-string.find"><code>string.find (s, pattern [, init [, plain]])</code></a></h3>
81337875
81347876
81357877<p>
81367878Looks for the first match of
8137<code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
7879<code>pattern</code> in the string <code>s</code>.
81387880If it finds a match, then <code>find</code> returns the indices of&nbsp;<code>s</code>
81397881where this occurrence starts and ends;
81407882otherwise, it returns <b>nil</b>.
r242959r242960
81647906<p>
81657907Returns a formatted version of its variable number of arguments
81667908following the description given in its first argument (which must be a string).
8167The format string follows the same rules as the ISO&nbsp;C function <code>sprintf</code>.
7909The format string follows the same rules as the ANSI&nbsp;C function <code>sprintf</code>.
81687910The only differences are that the options/modifiers
81697911<code>*</code>, <code>h</code>, <code>L</code>, <code>l</code>, <code>n</code>,
81707912and <code>p</code> are not supported
r242959r242960
81917933<code>G</code>, and <code>g</code> all expect a number as argument.
81927934Options <code>c</code>, <code>d</code>,
81937935<code>i</code>, <code>o</code>, <code>u</code>, <code>X</code>, and <code>x</code>
8194expect an integer.
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.
81957941Option <code>q</code> expects a string;
81967942option <code>s</code> expects a string without embedded zeros.
81977943If the argument to option <code>s</code> is not a string,
r242959r242960
82047950<hr><h3><a name="pdf-string.gmatch"><code>string.gmatch (s, pattern)</code></a></h3>
82057951Returns an iterator function that,
82067952each time it is called,
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>.
7953returns the next captures from <code>pattern</code> over the string <code>s</code>.
82097954If <code>pattern</code> specifies no captures,
82107955then the whole match is produced in each call.
82117956
r242959r242960
82437988<hr><h3><a name="pdf-string.gsub"><code>string.gsub (s, pattern, repl [, n])</code></a></h3>
82447989Returns a copy of <code>s</code>
82457990in which all (or the first <code>n</code>, if given)
8246occurrences of the <code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) have been
7991occurrences of the <code>pattern</code> have been
82477992replaced by a replacement string specified by <code>repl</code>,
82487993which can be a string, a table, or a function.
82497994<code>gsub</code> also returns, as its second value,
r242959r242960
83088053         end)
83098054     --&gt; x="4+5 = 9"
83108055     
8311     local t = {name="lua", version="5.3"}
8056     local t = {name="lua", version="5.2"}
83128057     x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)
8313     --&gt; x="lua-5.3.tar.gz"
8058     --&gt; x="lua-5.2.tar.gz"
83148059</pre>
83158060
83168061
r242959r242960
83388083<p>
83398084<hr><h3><a name="pdf-string.match"><code>string.match (s, pattern [, init])</code></a></h3>
83408085Looks for the first <em>match</em> of
8341<code>pattern</code> (see <a href="#6.4.1">&sect;6.4.1</a>) in the string <code>s</code>.
8086<code>pattern</code> in the string <code>s</code>.
83428087If it finds one, then <code>match</code> returns
83438088the captures from the pattern;
83448089otherwise it returns <b>nil</b>.
r242959r242960
83528097
83538098
83548099<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>
83808100<hr><h3><a name="pdf-string.rep"><code>string.rep (s, n [, sep])</code></a></h3>
83818101Returns a string that is the concatenation of <code>n</code> copies of
83828102the string <code>s</code> separated by the string <code>sep</code>.
83838103The default value for <code>sep</code> is the empty string
83848104(that is, no separator).
8385Returns the empty string if <code>n</code> is not positive.
83868105
83878106
83888107
r242959r242960
84228141
84238142
84248143<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>
84408144<hr><h3><a name="pdf-string.upper"><code>string.upper (s)</code></a></h3>
84418145Receives a string and returns a copy of this string with all
84428146lowercase letters changed to uppercase.
r242959r242960
84458149
84468150
84478151
8448
8449
84508152<h3>6.4.1 &ndash; <a name="6.4.1">Patterns</a></h3>
84518153
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.
84618154
8462
8463
84648155<h4>Character Class:</h4><p>
84658156A <em>character class</em> is used to represent a set of characters.
84668157The following combinations are allowed in describing a character class:
r242959r242960
84988189<li><b><code>%<em>x</em></code>: </b> (where <em>x</em> is any non-alphanumeric character)
84998190represents the character <em>x</em>.
85008191This is the standard way to escape the magic characters.
8501Any non-alphanumeric character
8502(including all punctuations, even the non-magical)
8192Any punctuation character (even the non magic)
85038193can be preceded by a '<code>%</code>'
85048194when used to represent itself in a pattern.
85058195</li>
r242959r242960
85098199characters in <em>set</em>.
85108200A range of characters can be specified by
85118201separating the end characters of the range,
8512in ascending order, with a '<code>-</code>'.
8202in ascending order, with a '<code>-</code>',
85138203All classes <code>%</code><em>x</em> described above can also be used as
85148204components in <em>set</em>.
85158205All other characters in <em>set</em> represent themselves.
r242959r242960
85588248
85598249<li>
85608250a single character class followed by '<code>*</code>',
8561which matches zero or more repetitions of characters in the class.
8251which matches 0 or more repetitions of characters in the class.
85628252These repetition items will always match the longest possible sequence;
85638253</li>
85648254
85658255<li>
85668256a single character class followed by '<code>+</code>',
8567which matches one or more repetitions of characters in the class.
8257which matches 1 or more repetitions of characters in the class.
85688258These repetition items will always match the longest possible sequence;
85698259</li>
85708260
85718261<li>
85728262a single character class followed by '<code>-</code>',
8573which also matches zero or more repetitions of characters in the class.
8263which also matches 0 or more repetitions of characters in the class.
85748264Unlike '<code>*</code>',
85758265these repetition items will always match the shortest possible sequence;
85768266</li>
85778267
85788268<li>
85798269a single character class followed by '<code>?</code>',
8580which matches zero or one occurrence of a character in the class.
8581It always matches one occurrence if possible;
8270which matches 0 or 1 occurrence of a character in the class;
85828271</li>
85838272
85848273<li>
r242959r242960
86518340
86528341
86538342
8654<h3>6.4.2 &ndash; <a name="6.4.2">Format Strings for Pack and Unpack</a></h3>
86558343
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.
86618344
86628345
8663<p>
8664A format string is a sequence of conversion options.
8665The conversion options are as follows:
86668346
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>).
8347<h2>6.5 &ndash; <a name="6.5">Table Manipulation</a></h2>
87058348
8706
87078349<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>
88548350This library provides generic functions for table manipulation.
88558351It provides all its functions inside the table <a name="pdf-table"><code>table</code></a>.
88568352
88578353
88588354<p>
88598355Remember that, whenever an operation needs the length of a table,
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>).
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>).
88628358All functions ignore non-numeric keys
8863in the tables given as arguments.
8359in tables given as arguments.
88648360
88658361
88668362<p>
8363For performance reasons,
8364all table accesses (get/set) performed by these functions are raw.
8365
8366
8367<p>
88678368<hr><h3><a name="pdf-table.concat"><code>table.concat (list [, sep [, i [, j]]])</code></a></h3>
88688369
88698370
r242959r242960
88948395
88958396
88968397<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>
89138398<hr><h3><a name="pdf-table.pack"><code>table.pack (&middot;&middot;&middot;)</code></a></h3>
89148399
89158400
r242959r242960
89398424
89408425<p>
89418426The default value for <code>pos</code> is <code>#list</code>,
8942so that a call <code>table.remove(l)</code> removes the last element
8943of list <code>l</code>.
8427so that a call <code>table.remove(t)</code> removes the last element
8428of list <code>t</code>.
89448429
89458430
89468431
r242959r242960
89748459
89758460
89768461<p>
8977Returns the elements from the given list.
8462Returns the elements from the given table.
89788463This function is equivalent to
89798464
89808465<pre>
r242959r242960
89888473
89898474
89908475
8991<h2>6.7 &ndash; <a name="6.7">Mathematical Functions</a></h2>
8476<h2>6.6 &ndash; <a name="6.6">Mathematical Functions</a></h2>
89928477
89938478<p>
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.
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>.
90038481
90048482
90058483<p>
r242959r242960
90078485
90088486
90098487<p>
9010Returns the absolute value of <code>x</code>. (integer/float)
8488Returns the absolute value of <code>x</code>.
90118489
90128490
90138491
r242959r242960
90338511
90348512
90358513<p>
9036<hr><h3><a name="pdf-math.atan"><code>math.atan (y [, x])</code></a></h3>
8514<hr><h3><a name="pdf-math.atan"><code>math.atan (x)</code></a></h3>
90378515
90388516
90398517<p>
8518Returns the arc tangent of <code>x</code> (in radians).
90408519
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>
90418528Returns the arc tangent of <code>y/x</code> (in radians),
90428529but uses the signs of both parameters to find the
90438530quadrant of the result.
90448531(It also handles correctly the case of <code>x</code> being zero.)
90458532
90468533
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>.
90518534
90528535
9053
9054
90558536<p>
90568537<hr><h3><a name="pdf-math.ceil"><code>math.ceil (x)</code></a></h3>
90578538
90588539
90598540<p>
9060Returns the smallest integral value larger than or equal to <code>x</code>.
8541Returns the smallest integer larger than or equal to <code>x</code>.
90618542
90628543
90638544
r242959r242960
90738554
90748555
90758556<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>
90768567<hr><h3><a name="pdf-math.deg"><code>math.deg (x)</code></a></h3>
90778568
90788569
90798570<p>
9080Converts the angle <code>x</code> from radians to degrees.
8571Returns the angle <code>x</code> (given in radians) in degrees.
90818572
90828573
90838574
r242959r242960
90878578
90888579
90898580<p>
9090Returns the value <em>e<sup>x</sup></em>
9091(where <code>e</code> is the base of natural logarithms).
8581Returns the value <em>e<sup>x</sup></em>.
90928582
90938583
90948584
r242959r242960
90988588
90998589
91008590<p>
9101Returns the largest integral value smaller than or equal to <code>x</code>.
8591Returns the largest integer smaller than or equal to <code>x</code>.
91028592
91038593
91048594
r242959r242960
91098599
91108600<p>
91118601Returns the remainder of the division of <code>x</code> by <code>y</code>
9112that rounds the quotient towards zero. (integer/float)
8602that rounds the quotient towards zero.
91138603
91148604
91158605
91168606
91178607<p>
9118<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
8608<hr><h3><a name="pdf-math.frexp"><code>math.frexp (x)</code></a></h3>
91198609
91208610
91218611<p>
9122The float value <code>HUGE_VAL</code>,
9123a value larger than any other numerical value.
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).
91248616
91258617
91268618
91278619
91288620<p>
9129<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
8621<hr><h3><a name="pdf-math.huge"><code>math.huge</code></a></h3>
91308622
91318623
91328624<p>
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>).
8625The value <code>HUGE_VAL</code>,
8626a value larger than or equal to any other numerical value.
91368627
91378628
91388629
91398630
91408631<p>
9141<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
8632<hr><h3><a name="pdf-math.ldexp"><code>math.ldexp (m, e)</code></a></h3>
91428633
91438634
91448635<p>
9145Returns the argument with the maximum value,
9146according to the Lua operator <code>&lt;</code>. (integer/float)
8636Returns <em>m2<sup>e</sup></em> (<code>e</code> should be an integer).
91478637
91488638
91498639
91508640
91518641<p>
9152<hr><h3><a name="pdf-math.maxinteger"><code>math.maxinteger</code></a></h3>
9153An integer with the maximum value for an integer.
8642<hr><h3><a name="pdf-math.log"><code>math.log (x [, base])</code></a></h3>
91548643
91558644
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>).
91568649
91578650
8651
8652
91588653<p>
9159<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
8654<hr><h3><a name="pdf-math.max"><code>math.max (x, &middot;&middot;&middot;)</code></a></h3>
91608655
91618656
91628657<p>
9163Returns the argument with the minimum value,
9164according to the Lua operator <code>&lt;</code>. (integer/float)
8658Returns the maximum value among its arguments.
91658659
91668660
91678661
91688662
91698663<p>
9170<hr><h3><a name="pdf-math.mininteger"><code>math.mininteger</code></a></h3>
9171An integer with the minimum value for an integer.
8664<hr><h3><a name="pdf-math.min"><code>math.min (x, &middot;&middot;&middot;)</code></a></h3>
91728665
91738666
8667<p>
8668Returns the minimum value among its arguments.
91748669
91758670
8671
8672
91768673<p>
91778674<hr><h3><a name="pdf-math.modf"><code>math.modf (x)</code></a></h3>
91788675
91798676
91808677<p>
9181Returns the integral part of <code>x</code> and the fractional part of <code>x</code>.
9182Its second result is always a float.
8678Returns two numbers,
8679the integral part of <code>x</code> and the fractional part of <code>x</code>.
91838680
91848681
91858682
r242959r242960
91958692
91968693
91978694<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>
91988706<hr><h3><a name="pdf-math.rad"><code>math.rad (x)</code></a></h3>
91998707
92008708
92018709<p>
9202Converts the angle <code>x</code> from degrees to radians.
8710Returns the angle <code>x</code> (given in degrees) in radians.
92038711
92048712
92058713
r242959r242960
92098717
92108718
92118719<p>
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>.
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.)
92208723
92218724
92228725<p>
9223This function is an interface to the underling
9224pseudo-random generator function provided by C.
9225No guarantees can be given for its statistical properties.
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>.
92268735
92278736
92288737
r242959r242960
92508759
92518760
92528761<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>
92538772<hr><h3><a name="pdf-math.sqrt"><code>math.sqrt (x)</code></a></h3>
92548773
92558774
r242959r242960
92718790
92728791
92738792<p>
9274<hr><h3><a name="pdf-math.tointeger"><code>math.tointeger (x)</code></a></h3>
8793<hr><h3><a name="pdf-math.tanh"><code>math.tanh (x)</code></a></h3>
92758794
92768795
92778796<p>
9278If the value <code>x</code> is convertible to an integer,
9279returns that integer.
9280Otherwise, returns <b>nil</b>.
8797Returns the hyperbolic tangent of <code>x</code>.
92818798
92828799
92838800
92848801
8802
8803
8804
8805<h2>6.7 &ndash; <a name="6.7">Bitwise Operations</a></h2>
8806
92858807<p>
9286<hr><h3><a name="pdf-math.type"><code>math.type (x)</code></a></h3>
8808This library provides bitwise operations.
8809It provides all its functions inside the table <a name="pdf-bit32"><code>bit32</code></a>.
92878810
92888811
92898812<p>
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.
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>.
92938823
92948824
8825<p>
8826<hr><h3><a name="pdf-bit32.arshift"><code>bit32.arshift (x, disp)</code></a></h3>
92958827
92968828
92978829<p>
9298<hr><h3><a name="pdf-math.ult"><code>math.ult (m, n)</code></a></h3>
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.
92998833
93008834
93018835<p>
9302Returns a boolean,
9303true if integer <code>m</code> is below integer <code>n</code> when
9304they are compared as unsigned integers.
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).
93058843
93068844
93078845
93088846
8847<p>
8848<hr><h3><a name="pdf-bit32.band"><code>bit32.band (&middot;&middot;&middot;)</code></a></h3>
93098849
93108850
8851<p>
8852Returns the bitwise <em>and</em> of its operands.
93118853
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
93129032<h2>6.8 &ndash; <a name="6.8">Input and Output Facilities</a></h2>
93139033
93149034<p>
93159035The I/O library provides two different styles for file manipulation.
9316The first one uses implicit file handles;
9036The first one uses implicit file descriptors;
93179037that is, there are operations to set a default input file and a
93189038default output file,
93199039and all input/output operations are over these default files.
9320The second style uses explicit file handles.
9040The second style uses explicit file descriptors.
93219041
93229042
93239043<p>
9324When using implicit file handles,
9044When using implicit file descriptors,
93259045all operations are supplied by table <a name="pdf-io"><code>io</code></a>.
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.
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.
93299049
93309050
93319051<p>
93329052The table <code>io</code> also provides
9333three predefined file handles with their usual meanings from C:
9053three predefined file descriptors with their usual meanings from C:
93349054<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>.
93359055The I/O library never closes these files.
93369056
r242959r242960
93419061(plus an error message as a second result and
93429062a system-dependent error code as a third result)
93439063and some value different from <b>nil</b> on success.
9344On non-POSIX systems,
9064On non-Posix systems,
93459065the computation of the error message and error code
93469066in case of errors
93479067may be not thread safe,
r242959r242960
93989118and returns an iterator function that
93999119works like <code>file:lines(&middot;&middot;&middot;)</code> over the opened file.
94009120When the iterator function detects the end of file,
9401it returns no values (to finish the loop) and automatically closes the file.
9121it returns <b>nil</b> (to finish the loop) and automatically closes the file.
94029122
94039123
94049124<p>
94059125The call <code>io.lines()</code> (with no file name) is equivalent
9406to <code>io.input():lines("*l")</code>;
9126to <code>io.input():lines()</code>;
94079127that is, it iterates over the lines of the default input file.
94089128In this case it does not close the file when the loop ends.
94099129
r242959r242960
95569276each time it is called,
95579277reads the file according to the given formats.
95589278When no format is given,
9559uses "<code>l</code>" as a default.
9279uses "*l" as a default.
95609280As an example, the construction
95619281
95629282<pre>
r242959r242960
95839303Reads the file <code>file</code>,
95849304according to the given formats, which specify what to read.
95859305For each format,
9586the function returns a string or a number with the characters read,
9306the function returns a string (or a number) with the characters read,
95879307or <b>nil</b> if it cannot read data with the specified format.
9588(In this latter case,
9589the function does not read subsequent formats.)
95909308When called without formats,
95919309it uses a default format that reads the next line
95929310(see below).
r242959r242960
95979315
95989316<ul>
95999317
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>.
9318<li><b>"<code>*n</code>": </b>
9319reads a number;
9320this is the only format that returns a number instead of a string.
96099321</li>
96109322
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>
9323<li><b>"<code>*a</code>": </b>
96169324reads the whole file, starting at the current position.
96179325On end of file, it returns the empty string.
96189326</li>
96199327
9620<li><b>"<code>l</code>": </b>
9328<li><b>"<code>*l</code>": </b>
96219329reads the next line skipping the end of line,
96229330returning <b>nil</b> on end of file.
96239331This is the default format.
96249332</li>
96259333
9626<li><b>"<code>L</code>": </b>
9627reads the next line keeping the end-of-line character (if present),
9334<li><b>"<code>*L</code>": </b>
9335reads the next line keeping the end of line (if present),
96289336returning <b>nil</b> on end of file.
96299337</li>
96309338
96319339<li><b><em>number</em>: </b>
96329340reads a string with up to this number of bytes,
96339341returning <b>nil</b> on end of file.
9634If <code>number</code> is zero,
9342If number is zero,
96359343it reads nothing and returns an empty string,
96369344or <b>nil</b> on end of file.
96379345</li>
96389346
9639</ul><p>
9640The formats "<code>l</code>" and "<code>L</code>" should be used only for text files.
9347</ul>
96419348
96429349
96439350
9644
96459351<p>
96469352<hr><h3><a name="pdf-file:seek"><code>file:seek ([whence [, offset]])</code></a></h3>
96479353
r242959r242960
97809486<p>
97819487If <code>format</code> is not "<code>*t</code>",
97829488then <code>date</code> returns the date as a string,
9783formatted according to the same rules as the ISO&nbsp;C function <code>strftime</code>.
9489formatted according to the same rules as the ANSI&nbsp;C function <code>strftime</code>.
97849490
97859491
97869492<p>
r242959r242960
97919497
97929498
97939499<p>
9794On non-POSIX systems,
9500On non-Posix systems,
97959501this function may be not thread safe
97969502because of its reliance on C&nbsp;function <code>gmtime</code> and C&nbsp;function <code>localtime</code>.
97979503
r242959r242960
98039509
98049510
98059511<p>
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>).
9512Returns the number of seconds from time <code>t1</code> to time <code>t2</code>.
98099513In POSIX, Windows, and some other systems,
98109514this value is exactly <code>t2</code><em>-</em><code>t1</code>.
98119515
r242959r242960
98179521
98189522
98199523<p>
9820This function is equivalent to the ISO&nbsp;C function <code>system</code>.
9524This function is equivalent to the ANSI&nbsp;C function <code>system</code>.
98219525It passes <code>command</code> to be executed by an operating system shell.
98229526Its first result is <b>true</b>
98239527if the command terminated successfully,
98249528or <b>nil</b> otherwise.
98259529After this first result
9826the function returns a string plus a number,
9530the function returns a string and a number,
98279531as follows:
98289532
98299533<ul>
r242959r242960
98489552
98499553
98509554<p>
9851<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close]])</code></a></h3>
9555<hr><h3><a name="pdf-os.exit"><code>os.exit ([code [, close])</code></a></h3>
98529556
98539557
98549558<p>
9855Calls the ISO&nbsp;C function <code>exit</code> to terminate the host program.
9559Calls the ANSI&nbsp;C function <code>exit</code> to terminate the host program.
98569560If <code>code</code> is <b>true</b>,
98579561the returned status is <code>EXIT_SUCCESS</code>;
98589562if <code>code</code> is <b>false</b>,
r242959r242960
101159819
101169820<p>
101179821The first parameter or local variable has index&nbsp;1, and so on,
10118following the order that they are declared in the code,
10119counting only the variables that are active
10120in the current scope of the function.
9822until the last active variable.
101219823Negative indices refer to vararg parameters;
101229824-1 is the first vararg parameter.
101239825The function returns <b>nil</b> if there is no variable with the given index,
r242959r242960
101269828
101279829
101289830<p>
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).
9831Variable names starting with '<code>(</code>' (open parenthesis)
9832represent internal variables
9833(loop control variables, temporaries, varargs, and C&nbsp;function locals).
101339834
101349835
101359836<p>
r242959r242960
101709871The function returns <b>nil</b> if there is no upvalue with the given index.
101719872
101729873
10173<p>
10174Variable names starting with '<code>(</code>' (open parenthesis)
10175represent variables with no known names
10176(variables from chunks saved without debug information).
101779874
101789875
10179
10180
101819876<p>
101829877<hr><h3><a name="pdf-debug.getuservalue"><code>debug.getuservalue (u)</code></a></h3>
101839878
r242959r242960
101989893Sets the given function as a hook.
101999894The string <code>mask</code> and the number <code>count</code> describe
102009895when the hook will be called.
10201The string mask may have any combination of the following characters,
9896The string mask may have the following characters,
102029897with the given meaning:
102039898
102049899<ul>
r242959r242960
102069901<li><b>'<code>r</code>': </b> the hook is called every time Lua returns from a function;</li>
102079902<li><b>'<code>l</code>': </b> the hook is called every time Lua enters a new line of code.</li>
102089903</ul><p>
10209Moreover,
10210with a <code>count</code> different from zero,
10211the hook is called also after every <code>count</code> instructions.
9904With a <code>count</code> different from zero,
9905the hook is called after every <code>count</code> instructions.
102129906
102139907
102149908<p>
r242959r242960
102879981<p>
102889982Sets the given <code>value</code> as
102899983the Lua value associated to the given <code>udata</code>.
9984<code>value</code> must be a table or <b>nil</b>;
102909985<code>udata</code> must be a full userdata.
102919986
102929987
r242959r242960
1030510000this function returns <code>message</code> without further processing.
1030610001Otherwise,
1030710002it returns a string with a traceback of the call stack.
10308The optional <code>message</code> string is appended
10003An optional <code>message</code> string is appended
1030910004at the beginning of the traceback.
1031010005An optional <code>level</code> number tells at which level
1031110006to start the traceback
r242959r242960
1031910014
1032010015
1032110016<p>
10322Returns a unique identifier (as a light userdata)
10017Returns an unique identifier (as a light userdata)
1032310018for the upvalue numbered <code>n</code>
1032410019from the given function.
1032510020
r242959r242960
1037510070<li><b><code>--</code>: </b> stops handling options;</li>
1037610071<li><b><code>-</code>: </b> executes <code>stdin</code> as a file and stops handling options.</li>
1037710072</ul><p>
10378After handling its options, <code>lua</code> runs the given <em>script</em>.
10073After handling its options, <code>lua</code> runs the given <em>script</em>,
10074passing to it the given <em>args</em> as string arguments.
1037910075When called without arguments,
1038010076<code>lua</code> behaves as <code>lua -v -i</code>
1038110077when the standard input (<code>stdin</code>) is a terminal,
r242959r242960
1038410080
1038510081<p>
1038610082When called without option <code>-E</code>,
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)
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)
1038910085before running any argument.
1039010086If the variable content has the format <code>@<em>filename</em></code>,
1039110087then <code>lua</code> executes the file.
r242959r242960
1041510111
1041610112
1041710113<p>
10418Before running any code,
10419<code>lua</code> collects all command-line arguments
10114Before starting to run the script,
10115<code>lua</code> collects all arguments in the command line
1042010116in a global table called <code>arg</code>.
10421The script name goes to index 0,
10117The script name is stored at index 0,
1042210118the first argument after the script name goes to index 1,
1042310119and so on.
1042410120Any arguments before the script name
10425(that is, the interpreter name plus its options)
10121(that is, the interpreter name plus the options)
1042610122go to negative indices.
1042710123For instance, in the call
1042810124
1042910125<pre>
1043010126     $ lua -la b.lua t1 t2
1043110127</pre><p>
10432the table is like this:
10128the interpreter first runs the file <code>a.lua</code>,
10129then creates a table
1043310130
1043410131<pre>
1043510132     arg = { [-2] = "lua", [-1] = "-la",
1043610133             [0] = "b.lua",
1043710134             [1] = "t1", [2] = "t2" }
1043810135</pre><p>
10439If there is no script in the call,
10440the interpreter name goes to index 0,
10441followed by the other arguments.
10442For instance, the call
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>'.
1044310140
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.)
1045310141
10454
1045510142<p>
1045610143In interactive mode,
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,
10144if you write an incomplete statement,
1046310145the interpreter waits for its completion
1046410146by issuing a different prompt.
1046510147
r242959r242960
1046710149<p>
1046810150In case of unprotected errors in the script,
1046910151the interpreter reports the error to the standard error stream.
10470If the error object is not a string but
10471has a metamethod <code>__tostring</code>,
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>,
1047210155the interpreter calls this metamethod to produce the final message.
10473Otherwise, the interpreter converts the error object to a string
10474and adds a stack traceback to it.
10156Finally, if the error object is <b>nil</b>,
10157the interpreter does not report the error.
1047510158
1047610159
1047710160<p>
r242959r242960
1051010193
1051110194<p>
1051210195Here we list the incompatibilities that you may find when moving a program
10513from Lua&nbsp;5.2 to Lua&nbsp;5.3.
10196from Lua&nbsp;5.1 to Lua&nbsp;5.2.
1051410197You can avoid some incompatibilities by compiling Lua with
1051510198appropriate options (see file <code>luaconf.h</code>).
1051610199However,
10517all these compatibility options will be removed in the future.
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.
1051810204
1051910205
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.
1053010206
10207<h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2>
10208<ul>
1053110209
10532<p>
10533Similarly, Lua versions can always change the internal representation
10534of precompiled chunks;
10535precompiled chunks are not compatible between different Lua versions.
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>.
1053610215
1053710216
1053810217<p>
10539The standard paths in the official distribution may
10540change between versions.
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.)
1054110223
1054210224
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>
1054310231
10544<h2>8.1 &ndash; <a name="8.1">Changes in the Language</a></h2>
10545<ul>
10546
1054710232<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.
10233Lua identifiers cannot use locale-dependent letters.
10234</li>
1055410235
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.)
10236<li>
10237Doing a step or a full collection in the garbage collector
10238does not restart the collector if it has been stopped.
1056710239</li>
1056810240
1056910241<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.
10242Weak tables with weak keys now perform like <em>ephemeron tables</em>.
10243</li>
1057610244
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.)
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.
1058210250</li>
1058310251
1058410252<li>
10585The generational mode for the garbage collector was removed.
10586(It was an experimental feature in Lua&nbsp;5.2.)
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.
1058710257</li>
1058810258
1058910259</ul>
r242959r242960
1059510265<ul>
1059610266
1059710267<li>
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.)
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.
1060310271</li>
1060410272
1060510273<li>
10606The Table library now respects metamethods
10607for setting and getting elements.
10274Functions <code>setfenv</code> and <code>getfenv</code> were removed,
10275because of the changes in environments.
1060810276</li>
1060910277
1061010278<li>
10611The <a href="#pdf-ipairs"><code>ipairs</code></a> iterator now respects metamethods and
10612its <code>__ipairs</code> metamethod has been deprecated.
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.
1061310281</li>
1061410282
1061510283<li>
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.
10284Function <code>loadstring</code> is deprecated.
10285Use <code>load</code> instead; it now accepts string arguments
10286and are exactly equivalent to <code>loadstring</code>.
1061810287</li>
1061910288
1062010289<li>
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.
10290Function <code>table.maxn</code> is deprecated.
10291Write it in Lua if you really need it.
1063110292</li>
1063210293
1063310294<li>
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.)
10295Function <code>os.execute</code> now returns <b>true</b> when command
10296terminates successfully and <b>nil</b> plus error information
10297otherwise.
1064210298</li>
1064310299
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
1064410331</ul>
1064510332
1064610333
1064710334
1064810335
1064910336<h2>8.3 &ndash; <a name="8.3">Changes in the API</a></h2>
10337<ul>
1065010338
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>
1065110344
10652<ul>
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>
1065310351
1065410352<li>
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.
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.)
1065910356</li>
1066010357
1066110358<li>
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.
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.
1066410365</li>
1066510366
1066610367<li>
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.
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.
1067210376</li>
1067310377
1067410378<li>
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).
10379<code>luaL_typerror</code> was removed.
10380Write your own version if you need it.
1068010381</li>
1068110382
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
1068210408</ul>
1068310409
1068410410
r242959r242960
1068810414
1068910415<p>
1069010416Here is the complete syntax of Lua in extended BNF.
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>.)
10417(It does not describe operator precedences.)
1069810418
1069910419
1070010420
r242959r242960
1073510455
1073610456   explist ::= exp {&lsquo;<b>,</b>&rsquo; exp}
1073710457
10738   exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Numeral | LiteralString | &lsquo;<b>...</b>&rsquo; | functiondef |
10458   exp ::=  <b>nil</b> | <b>false</b> | <b>true</b> | Number | String | &lsquo;<b>...</b>&rsquo; | functiondef |
1073910459       prefixexp | tableconstructor | exp binop exp | unop exp
1074010460
1074110461   prefixexp ::= var | functioncall | &lsquo;<b>(</b>&rsquo; exp &lsquo;<b>)</b>&rsquo;
1074210462
1074310463   functioncall ::=  prefixexp args | prefixexp &lsquo;<b>:</b>&rsquo; Name args
1074410464
10745   args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | LiteralString
10465   args ::=  &lsquo;<b>(</b>&rsquo; [explist] &lsquo;<b>)</b>&rsquo; | tableconstructor | String
1074610466
1074710467   functiondef ::= <b>function</b> funcbody
1074810468
r242959r242960
1075810478
1075910479   fieldsep ::= &lsquo;<b>,</b>&rsquo; | &lsquo;<b>;</b>&rsquo;
1076010480
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; |
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; |
1076310482       &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; |
1076410483       <b>and</b> | <b>or</b>
1076510484
10766   unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo; | &lsquo;<b>~</b>&rsquo;
10485   unop ::= &lsquo;<b>-</b>&rsquo; | <b>not</b> | &lsquo;<b>#</b>&rsquo;
1076710486
1076810487</pre>
1076910488
r242959r242960
1077510494
1077610495
1077710496
10778
1077910497<HR>
1078010498<SMALL CLASS="footer">
1078110499Last update:
10782Tue Jan  6 10:10:50 BRST 2015
10500Thu Mar 21 12:58:59 BRT 2013
1078310501</SMALL>
1078410502<!--
10785Last change: revised for Lua 5.3.0 (final)
10503Last change: revised for Lua 5.2.2
1078610504-->
1078710505
1078810506</body></html>
trunk/3rdparty/lua/doc/readme.html
r242959r242960
11<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
22<HTML>
33<HEAD>
4<TITLE>Lua 5.3 readme</TITLE>
4<TITLE>Lua 5.2 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 ;
1011   padding: 1em ;
1112   margin: 0px ;
12   border-radius: 8px ;
1313}
1414
1515.display {
r242959r242960
3131<HR>
3232<H1>
3333<A HREF="http://www.lua.org/"><IMG SRC="logo.gif" ALT="Lua" BORDER=0></A>
34Welcome to Lua 5.3.0
34Welcome to Lua 5.2
3535</H1>
3636
3737<P>
r242959r242960
7070updated
7171<A HREF="http://www.lua.org/docs.html">documentation</A>,
7272especially the
73<A HREF="http://www.lua.org/manual/5.3/">reference manual</A>,
73<A HREF="http://www.lua.org/manual/5.2/">reference manual</A>,
7474which may differ slightly from the
7575<A HREF="contents.html">local copy</A>
7676distributed in this package.
r242959r242960
9898get a binary from
9999<A HREF="http://lua-users.org/wiki/LuaBinaries">LuaBinaries</A>.
100100Try also
101<A HREF="http://luadist.org/">LuaDist</A>,
102a multi-platform distribution of Lua that includes batteries.
101<A HREF="http://luaforwindows.luaforge.net/">Lua for Windows</A>,
102an easy-to-use distribution of Lua that includes many useful libraries.
103103
104104<H3>Building Lua</H3>
105105
r242959r242960
110110<OL>
111111<LI>
112112Open a terminal window and move to
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.
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.
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 bsd c89 freebsd generic linux macosx mingw posix solaris
121   aix ansi bsd 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  c89, in this order.
128  ansi, in this order.
129129<P>
130130<LI>
131131The compilation takes only a few moments
r242959r242960
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.
139  after building Lua. This will run the interpreter and print its version string.
140140</OL>
141141<P>
142142If you're running Linux and get compilation errors,
r242959r242960
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 <TT>Makefile</TT>. You'll
151  place and the way to install files are defined in the Makefile. You'll
152152  probably need the right permissions to install files.
153153
154154<P>
r242959r242960
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>, <TT>share</TT>,
161  <TT>bin</TT>, <TT>include</TT>, <TT>lib</TT>, <TT>man</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.
168166
169167<DL CLASS="display">
170168<DT>
r242959r242960
174172<DT>
175173    include:
176174<DD>
177    lauxlib.h lua.h lua.hpp luaconf.h lualib.h
175    lua.h luaconf.h lualib.h lauxlib.h lua.hpp
178176<DT>
179177    lib:
180178<DD>
r242959r242960
188186<P>
189187  These are the only directories you need for development.
190188  If you only want to run Lua programs,
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
189  you only need the files in bin and man.
190  The files in include and lib are needed for
193191  embedding Lua in C or C++ programs.
194192
195193<H3><A NAME="customization">Customization</A></H3>
r242959r242960
205203  You don't actually need to edit the Makefiles because you may set the
206204  relevant variables in the command line when invoking make.
207205  Nevertheless, it's probably best to edit and save the Makefiles to
208  record the changes you've made.
206  record the changes you need.
209207
210208<P>
211209  On the other hand, if you need to customize some Lua features, you'll need
r242959r242960
214212  it will be used by any Lua clients that you build, to ensure consistency.
215213  Further customization is available to experts by editing the Lua sources.
216214
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
217220<H3><A NAME="other">Building Lua on other systems</A></H3>
218221
219222<P>
r242959r242960
230233lmem.c lobject.c lopcodes.c lparser.c lstate.c lstring.c ltable.c
231234ltm.c lundump.c lvm.c lzio.c
232235lauxlib.c lbaselib.c lbitlib.c lcorolib.c ldblib.c liolib.c
233lmathlib.c loslib.c lstrlib.c ltablib.c lutf8lib.c loadlib.c linit.c
236lmathlib.c loslib.c lstrlib.c ltablib.c loadlib.c linit.c
234237<DT>
235238interpreter:
236239<DD>
r242959r242960
251254  be linked statically into the host program and its symbols exported for
252255  dynamic linking; <TT>src/Makefile</TT> does this for the Lua interpreter.
253256  For Windows, we recommend that the Lua library be a DLL.
254  In all cases, the compiler luac should be linked statically.
255257
256258<P>
257259  As mentioned above, you may edit <TT>src/luaconf.h</TT> to customize
258260  some features before building Lua.
259261
260<H2><A NAME="changes">Changes since Lua 5.2</A></H2>
262<H2><A NAME="changes">Changes since Lua 5.1</A></H2>
261263
262264<P>
263Here are the main changes introduced in Lua 5.3.
265Here are the main changes introduced in Lua 5.2.
264266The
265267<A HREF="contents.html">reference manual</A>
266268lists the
r242959r242960
268270
269271<H3>Main changes</H3>
270272<UL>
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
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
277281</UL>
278282
279Here are the other changes introduced in Lua 5.3:
283Here are the other changes introduced in Lua 5.2:
280284<H3>Language</H3>
281285<UL>
282<LI> userdata can have any Lua value as uservalue
283<LI> integer division
284<LI> more flexible rules for some metamethods
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
285295</UL>
286296
287297<H3>Libraries</H3>
288298<UL>
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>
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
296317</UL>
297318
298319<H3>C API</H3>
299320<UL>
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>
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>
309341</UL>
310342
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
311353<H3>Lua standalone interpreter</H3>
312354<UL>
313<LI> can be used as calculator; no need to prefix with '='
314<LI> <CODE>arg</CODE> table available to all code
355<LI> new <CODE>-E</CODE> option to avoid environment variables
356<LI> handling of non-string error messages
315357</UL>
316358
317359<H2><A NAME="license">License</A></H2>
r242959r242960
333375<A HREF="http://www.lua.org/license.html">this</A>.
334376
335377<BLOCKQUOTE STYLE="padding-bottom: 0em">
336Copyright &copy; 1994&ndash;2015 Lua.org, PUC-Rio.
378Copyright &copy; 1994&ndash;2013 Lua.org, PUC-Rio.
337379
338380<P>
339381Permission is hereby granted, free of charge, to any person obtaining a copy
r242959r242960
361403<HR>
362404<SMALL CLASS="footer">
363405Last update:
364Fri Dec 12 09:58:42 BRST 2014
406Sat Nov  9 22:39:16 BRST 2013
365407</SMALL>
366408<!--
367Last change: updated for Lua 5.3.0 (final)
409Last change: revised for Lua 5.2.3
368410-->
369411
370412</BODY>
trunk/3rdparty/lua/src/Makefile
r242959r242960
66# Your platform. See PLATS for possible values.
77PLAT= none
88
9CC= gcc -std=gnu99
10CFLAGS= -O2 -Wall -Wextra -DLUA_COMPAT_5_2 $(SYSCFLAGS) $(MYCFLAGS)
9CC= gcc
10CFLAGS= -O2 -Wall -DLUA_COMPAT_ALL $(SYSCFLAGS) $(MYCFLAGS)
1111LDFLAGS= $(SYSLDFLAGS) $(MYLDFLAGS)
1212LIBS= -lm $(SYSLIBS) $(MYLIBS)
1313
r242959r242960
2626
2727# == END OF USER SETTINGS -- NO NEED TO CHANGE ANYTHING BELOW THIS LINE =======
2828
29PLATS= aix bsd c89 freebsd generic linux macosx mingw posix solaris
29PLATS= aix ansi bsd 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 lutf8lib.o loadlib.o linit.o
36   lmathlib.o loslib.o lstrlib.o ltablib.o loadlib.o linit.o
3737BASE_O= $(CORE_O) $(LIB_O) $(MYOBJS)
3838
3939LUA_T=   lua
r242959r242960
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
9497bsd:
9598   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-Wl,-E"
9699
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
104100freebsd:
105101   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_LINUX" SYSLIBS="-Wl,-E -lreadline"
106102
r242959r242960
113109   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_MACOSX" SYSLIBS="-lreadline" CC=cc
114110
115111mingw:
116   $(MAKE) "LUA_A=lua53.dll" "LUA_T=lua.exe" \
112   $(MAKE) "LUA_A=lua52.dll" "LUA_T=lua.exe" \
117113   "AR=$(CC) -shared -o" "RANLIB=strip --strip-unneeded" \
118114   "SYSCFLAGS=-DLUA_BUILD_AS_DLL" "SYSLIBS=" "SYSLDFLAGS=-s" lua.exe
119115   $(MAKE) "LUAC_T=luac.exe" luac.exe
r242959r242960
122118   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX"
123119
124120solaris:
125   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN -D_REENTRANT" SYSLIBS="-ldl"
121   $(MAKE) $(ALL) SYSCFLAGS="-DLUA_USE_POSIX -DLUA_USE_DLOPEN" SYSLIBS="-ldl"
126122
127123# list targets that do not create files (but not all makes understand .PHONY)
128124.PHONY: all $(PLATS) default o a clean depend echo none
129125
130126# DO NOT DELETE
131127
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
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
196187
197# (end of Makefile)
trunk/3rdparty/lua/src/lapi.c
r242959r242960
11/*
2** $Id: lapi.c,v 2.244 2014/12/26 14:43:45 roberto Exp $
2** $Id: lapi.c,v 2.171.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lua API
44** See Copyright Notice in lua.h
55*/
66
7#define lapi_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
138#include <stdarg.h>
149#include <string.h>
1510
11#define lapi_c
12#define LUA_CORE
13
1614#include "lua.h"
1715
1816#include "lapi.h"
r242959r242960
4543/* test for pseudo index */
4644#define ispseudo(i)      ((i) <= LUA_REGISTRYINDEX)
4745
48/* test for upvalue */
49#define isupvalue(i)      ((i) < LUA_REGISTRYINDEX)
50
5146/* test for valid but not pseudo index */
5247#define isstackindex(i, o)   (isvalid(o) && !ispseudo(i))
5348
54#define api_checkvalidindex(o)  api_check(isvalid(o), "invalid index")
49#define api_checkvalidindex(L, o)  api_check(L, isvalid(o), "invalid index")
5550
56#define api_checkstackindex(i, o)  \
57   api_check(isstackindex(i, o), "index not in the stack")
51#define api_checkstackindex(L, i, o)  \
52   api_check(L, isstackindex(i, o), "index not in the stack")
5853
5954
6055static TValue *index2addr (lua_State *L, int idx) {
6156  CallInfo *ci = L->ci;
6257  if (idx > 0) {
6358    TValue *o = ci->func + idx;
64    api_check(idx <= ci->top - (ci->func + 1), "unacceptable index");
59    api_check(L, idx <= ci->top - (ci->func + 1), "unacceptable index");
6560    if (o >= L->top) return NONVALIDVALUE;
6661    else return o;
6762  }
6863  else if (!ispseudo(idx)) {  /* negative index */
69    api_check(idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
64    api_check(L, idx != 0 && -idx <= L->top - (ci->func + 1), "invalid index");
7065    return L->top + idx;
7166  }
7267  else if (idx == LUA_REGISTRYINDEX)
7368    return &G(L)->l_registry;
7469  else {  /* upvalues */
7570    idx = LUA_REGISTRYINDEX - idx;
76    api_check(idx <= MAXUPVAL + 1, "upvalue index too large");
71    api_check(L, idx <= MAXUPVAL + 1, "upvalue index too large");
7772    if (ttislcf(ci->func))  /* light C function? */
7873      return NONVALIDVALUE;  /* it has no upvalues */
7974    else {
r242959r242960
9489}
9590
9691
97LUA_API int lua_checkstack (lua_State *L, int n) {
92LUA_API int lua_checkstack (lua_State *L, int size) {
9893  int res;
9994  CallInfo *ci = L->ci;
10095  lua_lock(L);
101  api_check(n >= 0, "negative 'n'");
102  if (L->stack_last - L->top > n)  /* stack large enough? */
96  if (L->stack_last - L->top > size)  /* stack large enough? */
10397    res = 1;  /* yes; check is OK */
10498  else {  /* no; need to grow stack */
10599    int inuse = cast_int(L->top - L->stack) + EXTRA_STACK;
106    if (inuse > LUAI_MAXSTACK - n)  /* can grow without overflow? */
100    if (inuse > LUAI_MAXSTACK - size)  /* can grow without overflow? */
107101      res = 0;  /* no */
108102    else  /* try to grow stack */
109      res = (luaD_rawrunprotected(L, &growstack, &n) == LUA_OK);
103      res = (luaD_rawrunprotected(L, &growstack, &size) == LUA_OK);
110104  }
111  if (res && ci->top < L->top + n)
112    ci->top = L->top + n;  /* adjust frame top */
105  if (res && ci->top < L->top + size)
106    ci->top = L->top + size;  /* adjust frame top */
113107  lua_unlock(L);
114108  return res;
115109}
r242959r242960
120114  if (from == to) return;
121115  lua_lock(to);
122116  api_checknelems(from, n);
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");
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");
125119  from->top -= n;
126120  for (i = 0; i < n; i++) {
127121    setobj2s(to, to->top++, from->top + i);
r242959r242960
172166  StkId func = L->ci->func;
173167  lua_lock(L);
174168  if (idx >= 0) {
175    api_check(idx <= L->stack_last - (func + 1), "new top too large");
169    api_check(L, idx <= L->stack_last - (func + 1), "new top too large");
176170    while (L->top < (func + 1) + idx)
177171      setnilvalue(L->top++);
178172    L->top = (func + 1) + idx;
179173  }
180174  else {
181    api_check(-(idx+1) <= (L->top - (func + 1)), "invalid new top");
182    L->top += idx+1;  /* 'subtract' index (index is negative) */
175    api_check(L, -(idx+1) <= (L->top - (func + 1)), "invalid new top");
176    L->top += idx+1;  /* `subtract' index (index is negative) */
183177  }
184178  lua_unlock(L);
185179}
186180
187181
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  }
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);
199190}
200191
201192
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;
193LUA_API void lua_insert (lua_State *L, int idx) {
194  StkId p;
195  StkId q;
208196  lua_lock(L);
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 */
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);
217202  lua_unlock(L);
218203}
219204
220205
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);
206static void moveto (lua_State *L, TValue *fr, int idx) {
207  TValue *to = index2addr(L, idx);
208  api_checkvalidindex(L, to);
227209  setobj(L, to, fr);
228  if (isupvalue(toidx))  /* function upvalue? */
210  if (idx < LUA_REGISTRYINDEX)  /* function upvalue? */
229211    luaC_barrier(L, clCvalue(L->ci->func), fr);
230212  /* LUA_REGISTRYINDEX does not need gc barrier
231213     (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--;
232222  lua_unlock(L);
233223}
234224
235225
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
236235LUA_API void lua_pushvalue (lua_State *L, int idx) {
237236  lua_lock(L);
238237  setobj2s(L, L->top, index2addr(L, idx));
r242959r242960
249248
250249LUA_API int lua_type (lua_State *L, int idx) {
251250  StkId o = index2addr(L, idx);
252  return (isvalid(o) ? ttnov(o) : LUA_TNONE);
251  return (isvalid(o) ? ttypenv(o) : LUA_TNONE);
253252}
254253
255254
256255LUA_API const char *lua_typename (lua_State *L, int t) {
257256  UNUSED(L);
258  api_check(LUA_TNONE <= t && t < LUA_NUMTAGS, "invalid tag");
259257  return ttypename(t);
260258}
261259
r242959r242960
266264}
267265
268266
269LUA_API int lua_isinteger (lua_State *L, int idx) {
270  StkId o = index2addr(L, idx);
271  return ttisinteger(o);
272}
273
274
275267LUA_API int lua_isnumber (lua_State *L, int idx) {
276  lua_Number n;
268  TValue n;
277269  const TValue *o = index2addr(L, idx);
278270  return tonumber(o, &n);
279271}
280272
281273
282274LUA_API int lua_isstring (lua_State *L, int idx) {
283  const TValue *o = index2addr(L, idx);
284  return (ttisstring(o) || cvt2str(o));
275  int t = lua_type(L, idx);
276  return (t == LUA_TSTRING || t == LUA_TNUMBER);
285277}
286278
287279
288280LUA_API int lua_isuserdata (lua_State *L, int idx) {
289281  const TValue *o = index2addr(L, idx);
290  return (ttisfulluserdata(o) || ttislightuserdata(o));
282  return (ttisuserdata(o) || ttislightuserdata(o));
291283}
292284
293285
r242959r242960
299291
300292
301293LUA_API void lua_arith (lua_State *L, int op) {
294  StkId o1;  /* 1st operand */
295  StkId o2;  /* 2nd operand */
302296  lua_lock(L);
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 */
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 */
306300    api_checknelems(L, 1);
307301    setobjs2s(L, L->top, L->top - 1);
308302    L->top++;
309303  }
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 */
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--;
313312  lua_unlock(L);
314313}
315314
r242959r242960
322321  o2 = index2addr(L, index2);
323322  if (isvalid(o1) && isvalid(o2)) {
324323    switch (op) {
325      case LUA_OPEQ: i = luaV_equalobj(L, o1, o2); break;
324      case LUA_OPEQ: i = equalobj(L, o1, o2); break;
326325      case LUA_OPLT: i = luaV_lessthan(L, o1, o2); break;
327326      case LUA_OPLE: i = luaV_lessequal(L, o1, o2); break;
328      default: api_check(0, "invalid option");
327      default: api_check(L, 0, "invalid option");
329328    }
330329  }
331330  lua_unlock(L);
r242959r242960
333332}
334333
335334
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;
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  }
341346}
342347
343348
344LUA_API lua_Number lua_tonumberx (lua_State *L, int idx, int *pisnum) {
345  lua_Number n;
349LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *isnum) {
350  TValue n;
346351  const TValue *o = index2addr(L, idx);
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;
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  }
352363}
353364
354365
355LUA_API lua_Integer lua_tointegerx (lua_State *L, int idx, int *pisnum) {
356  lua_Integer res;
366LUA_API lua_Unsigned lua_tounsignedx (lua_State *L, int idx, int *isnum) {
367  TValue n;
357368  const TValue *o = index2addr(L, idx);
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;
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  }
363380}
364381
365382
r242959r242960
372389LUA_API const char *lua_tolstring (lua_State *L, int idx, size_t *len) {
373390  StkId o = index2addr(L, idx);
374391  if (!ttisstring(o)) {
375    if (!cvt2str(o)) {  /* not convertible? */
392    lua_lock(L);  /* `luaV_tostring' may create a new string */
393    if (!luaV_tostring(L, o)) {  /* conversion failed? */
376394      if (len != NULL) *len = 0;
395      lua_unlock(L);
377396      return NULL;
378397    }
379    lua_lock(L);  /* 'luaO_tostring' may create a new string */
380398    luaC_checkGC(L);
381399    o = index2addr(L, idx);  /* previous call may reallocate the stack */
382    luaO_tostring(L, o);
383400    lua_unlock(L);
384401  }
385402  if (len != NULL) *len = tsvalue(o)->len;
r242959r242960
389406
390407LUA_API size_t lua_rawlen (lua_State *L, int idx) {
391408  StkId o = index2addr(L, idx);
392  switch (ttnov(o)) {
409  switch (ttypenv(o)) {
393410    case LUA_TSTRING: return tsvalue(o)->len;
394411    case LUA_TUSERDATA: return uvalue(o)->len;
395412    case LUA_TTABLE: return luaH_getn(hvalue(o));
r242959r242960
409426
410427LUA_API void *lua_touserdata (lua_State *L, int idx) {
411428  StkId o = index2addr(L, idx);
412  switch (ttnov(o)) {
413    case LUA_TUSERDATA: return getudatamem(uvalue(o));
429  switch (ttypenv(o)) {
430    case LUA_TUSERDATA: return (rawuvalue(o) + 1);
414431    case LUA_TLIGHTUSERDATA: return pvalue(o);
415432    default: return NULL;
416433  }
r242959r242960
455472
456473LUA_API void lua_pushnumber (lua_State *L, lua_Number n) {
457474  lua_lock(L);
458  setfltvalue(L->top, n);
475  setnvalue(L->top, n);
476  luai_checknum(L, L->top,
477    luaG_runerror(L, "C API - attempt to push a signaling NaN"));
459478  api_incr_top(L);
460479  lua_unlock(L);
461480}
r242959r242960
463482
464483LUA_API void lua_pushinteger (lua_State *L, lua_Integer n) {
465484  lua_lock(L);
466  setivalue(L->top, n);
485  setnvalue(L->top, cast_num(n));
467486  api_incr_top(L);
468487  lua_unlock(L);
469488}
470489
471490
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
472501LUA_API const char *lua_pushlstring (lua_State *L, const char *s, size_t len) {
473502  TString *ts;
474503  lua_lock(L);
r242959r242960
529558    setfvalue(L->top, fn);
530559  }
531560  else {
532    CClosure *cl;
561    Closure *cl;
533562    api_checknelems(L, n);
534    api_check(n <= MAXUPVAL, "upvalue index too large");
563    api_check(L, n <= MAXUPVAL, "upvalue index too large");
535564    luaC_checkGC(L);
536565    cl = luaF_newCclosure(L, n);
537    cl->f = fn;
566    cl->c.f = fn;
538567    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    }
568    while (n--)
569      setobj2n(L, &cl->c.upvalue[n], L->top + n);
543570    setclCvalue(L, L->top, cl);
544571  }
545572  api_incr_top(L);
r242959r242960
578605*/
579606
580607
581LUA_API int lua_getglobal (lua_State *L, const char *name) {
608LUA_API void lua_getglobal (lua_State *L, const char *var) {
582609  Table *reg = hvalue(&G(L)->l_registry);
583610  const TValue *gt;  /* global table */
584611  lua_lock(L);
585612  gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
586  setsvalue2s(L, L->top++, luaS_new(L, name));
613  setsvalue2s(L, L->top++, luaS_new(L, var));
587614  luaV_gettable(L, gt, L->top - 1, L->top - 1);
588615  lua_unlock(L);
589  return ttnov(L->top - 1);
590616}
591617
592618
593LUA_API int lua_gettable (lua_State *L, int idx) {
619LUA_API void lua_gettable (lua_State *L, int idx) {
594620  StkId t;
595621  lua_lock(L);
596622  t = index2addr(L, idx);
597623  luaV_gettable(L, t, L->top - 1, L->top - 1);
598624  lua_unlock(L);
599  return ttnov(L->top - 1);
600625}
601626
602627
603LUA_API int lua_getfield (lua_State *L, int idx, const char *k) {
628LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
604629  StkId t;
605630  lua_lock(L);
606631  t = index2addr(L, idx);
r242959r242960
608633  api_incr_top(L);
609634  luaV_gettable(L, t, L->top - 1, L->top - 1);
610635  lua_unlock(L);
611  return ttnov(L->top - 1);
612636}
613637
614638
615LUA_API int lua_geti (lua_State *L, int idx, lua_Integer n) {
639LUA_API void lua_rawget (lua_State *L, int idx) {
616640  StkId t;
617641  lua_lock(L);
618642  t = index2addr(L, idx);
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");
643  api_check(L, ttistable(t), "table expected");
632644  setobj2s(L, L->top - 1, luaH_get(hvalue(t), L->top - 1));
633645  lua_unlock(L);
634  return ttnov(L->top - 1);
635646}
636647
637648
638LUA_API int lua_rawgeti (lua_State *L, int idx, lua_Integer n) {
649LUA_API void lua_rawgeti (lua_State *L, int idx, int n) {
639650  StkId t;
640651  lua_lock(L);
641652  t = index2addr(L, idx);
642  api_check(ttistable(t), "table expected");
653  api_check(L, ttistable(t), "table expected");
643654  setobj2s(L, L->top, luaH_getint(hvalue(t), n));
644655  api_incr_top(L);
645656  lua_unlock(L);
646  return ttnov(L->top - 1);
647657}
648658
649659
650LUA_API int lua_rawgetp (lua_State *L, int idx, const void *p) {
660LUA_API void lua_rawgetp (lua_State *L, int idx, const void *p) {
651661  StkId t;
652662  TValue k;
653663  lua_lock(L);
654664  t = index2addr(L, idx);
655  api_check(ttistable(t), "table expected");
665  api_check(L, ttistable(t), "table expected");
656666  setpvalue(&k, cast(void *, p));
657667  setobj2s(L, L->top, luaH_get(hvalue(t), &k));
658668  api_incr_top(L);
659669  lua_unlock(L);
660  return ttnov(L->top - 1);
661670}
662671
663672
r242959r242960
676685
677686LUA_API int lua_getmetatable (lua_State *L, int objindex) {
678687  const TValue *obj;
679  Table *mt;
680  int res = 0;
688  Table *mt = NULL;
689  int res;
681690  lua_lock(L);
682691  obj = index2addr(L, objindex);
683  switch (ttnov(obj)) {
692  switch (ttypenv(obj)) {
684693    case LUA_TTABLE:
685694      mt = hvalue(obj)->metatable;
686695      break;
r242959r242960
688697      mt = uvalue(obj)->metatable;
689698      break;
690699    default:
691      mt = G(L)->mt[ttnov(obj)];
700      mt = G(L)->mt[ttypenv(obj)];
692701      break;
693702  }
694  if (mt != NULL) {
703  if (mt == NULL)
704    res = 0;
705  else {
695706    sethvalue(L, L->top, mt);
696707    api_incr_top(L);
697708    res = 1;
r242959r242960
701712}
702713
703714
704LUA_API int lua_getuservalue (lua_State *L, int idx) {
715LUA_API void lua_getuservalue (lua_State *L, int idx) {
705716  StkId o;
706717  lua_lock(L);
707718  o = index2addr(L, idx);
708  api_check(ttisfulluserdata(o), "full userdata expected");
709  getuservalue(L, uvalue(o), L->top);
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);
710724  api_incr_top(L);
711725  lua_unlock(L);
712  return ttnov(L->top - 1);
713726}
714727
715728
r242959r242960
718731*/
719732
720733
721LUA_API void lua_setglobal (lua_State *L, const char *name) {
734LUA_API void lua_setglobal (lua_State *L, const char *var) {
722735  Table *reg = hvalue(&G(L)->l_registry);
723736  const TValue *gt;  /* global table */
724737  lua_lock(L);
725738  api_checknelems(L, 1);
726739  gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
727  setsvalue2s(L, L->top++, luaS_new(L, name));
740  setsvalue2s(L, L->top++, luaS_new(L, var));
728741  luaV_settable(L, gt, L->top - 1, L->top - 2);
729742  L->top -= 2;  /* pop value and key */
730743  lua_unlock(L);
r242959r242960
754767}
755768
756769
757LUA_API void lua_seti (lua_State *L, int idx, lua_Integer n) {
770LUA_API void lua_rawset (lua_State *L, int idx) {
758771  StkId t;
759772  lua_lock(L);
760  api_checknelems(L, 1);
773  api_checknelems(L, 2);
761774  t = index2addr(L, idx);
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);
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);
780779  L->top -= 2;
781780  lua_unlock(L);
782781}
783782
784783
785LUA_API void lua_rawseti (lua_State *L, int idx, lua_Integer n) {
786  StkId o;
787  Table *t;
784LUA_API void lua_rawseti (lua_State *L, int idx, int n) {
785  StkId t;
788786  lua_lock(L);
789787  api_checknelems(L, 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);
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);
795792  L->top--;
796793  lua_unlock(L);
797794}
798795
799796
800797LUA_API void lua_rawsetp (lua_State *L, int idx, const void *p) {
801  StkId o;
802  Table *t;
798  StkId t;
803799  TValue k;
804800  lua_lock(L);
805801  api_checknelems(L, 1);
806  o = index2addr(L, idx);
807  api_check(ttistable(o), "table expected");
808  t = hvalue(o);
802  t = index2addr(L, idx);
803  api_check(L, ttistable(t), "table expected");
809804  setpvalue(&k, cast(void *, p));
810  setobj2t(L, luaH_set(L, t, &k), L->top - 1);
811  luaC_barrierback(L, t, L->top - 1);
805  setobj2t(L, luaH_set(L, hvalue(t), &k), L->top - 1);
806  luaC_barrierback(L, gcvalue(t), L->top - 1);
812807  L->top--;
813808  lua_unlock(L);
814809}
r242959r242960
823818  if (ttisnil(L->top - 1))
824819    mt = NULL;
825820  else {
826    api_check(ttistable(L->top - 1), "table expected");
821    api_check(L, ttistable(L->top - 1), "table expected");
827822    mt = hvalue(L->top - 1);
828823  }
829  switch (ttnov(obj)) {
824  switch (ttypenv(obj)) {
830825    case LUA_TTABLE: {
831826      hvalue(obj)->metatable = mt;
832827      if (mt) {
833        luaC_objbarrier(L, gcvalue(obj), mt);
828        luaC_objbarrierback(L, gcvalue(obj), mt);
834829        luaC_checkfinalizer(L, gcvalue(obj), mt);
835830      }
836831      break;
r242959r242960
838833    case LUA_TUSERDATA: {
839834      uvalue(obj)->metatable = mt;
840835      if (mt) {
841        luaC_objbarrier(L, uvalue(obj), mt);
836        luaC_objbarrier(L, rawuvalue(obj), mt);
842837        luaC_checkfinalizer(L, gcvalue(obj), mt);
843838      }
844839      break;
845840    }
846841    default: {
847      G(L)->mt[ttnov(obj)] = mt;
842      G(L)->mt[ttypenv(obj)] = mt;
848843      break;
849844    }
850845  }
r242959r242960
859854  lua_lock(L);
860855  api_checknelems(L, 1);
861856  o = index2addr(L, idx);
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);
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  }
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((nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
876     api_check(L, (nr) == LUA_MULTRET || (L->ci->top - L->top >= (nr) - (na)), \
877877   "results from function overflow current stack size")
878878
879879
880LUA_API void lua_callk (lua_State *L, int nargs, int nresults,
881                        lua_KContext ctx, lua_KFunction k) {
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) {
882891  StkId func;
883892  lua_lock(L);
884  api_check(k == NULL || !isLua(L->ci),
893  api_check(L, k == NULL || !isLua(L->ci),
885894    "cannot use continuations inside hooks");
886895  api_checknelems(L, nargs+1);
887  api_check(L->status == LUA_OK, "cannot do calls on non-normal thread");
896  api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
888897  checkresults(L, nargs, nresults);
889898  func = L->top - (nargs+1);
890899  if (k != NULL && L->nny == 0) {  /* need to prepare continuation? */
r242959r242960
903912/*
904913** Execute a protected call.
905914*/
906struct CallS {  /* data to 'f_call' */
915struct CallS {  /* data to `f_call' */
907916  StkId func;
908917  int nresults;
909918};
r242959r242960
917926
918927
919928LUA_API int lua_pcallk (lua_State *L, int nargs, int nresults, int errfunc,
920                        lua_KContext ctx, lua_KFunction k) {
929                        int ctx, lua_CFunction k) {
921930  struct CallS c;
922931  int status;
923932  ptrdiff_t func;
924933  lua_lock(L);
925  api_check(k == NULL || !isLua(L->ci),
934  api_check(L, k == NULL || !isLua(L->ci),
926935    "cannot use continuations inside hooks");
927936  api_checknelems(L, nargs+1);
928  api_check(L->status == LUA_OK, "cannot do calls on non-normal thread");
937  api_check(L, L->status == LUA_OK, "cannot do calls on non-normal thread");
929938  checkresults(L, nargs, nresults);
930939  if (errfunc == 0)
931940    func = 0;
932941  else {
933942    StkId o = index2addr(L, errfunc);
934    api_checkstackindex(errfunc, o);
943    api_checkstackindex(L, errfunc, o);
935944    func = savestack(L, o);
936945  }
937946  c.func = L->top - (nargs+1);  /* function to be called */
r242959r242960
945954    ci->u.c.ctx = ctx;  /* save context */
946955    /* save information for error recovery */
947956    ci->extra = savestack(L, c.func);
957    ci->u.c.old_allowhook = L->allowhook;
948958    ci->u.c.old_errfunc = L->errfunc;
949959    L->errfunc = func;
950    setoah(ci->callstatus, L->allowhook);  /* save value of 'allowhook' */
951    ci->callstatus |= CIST_YPCALL;  /* function can do error recovery */
960    /* mark that function may do error recovery */
961    ci->callstatus |= CIST_YPCALL;
952962    luaD_call(L, c.func, nresults, 1);  /* do the call */
953963    ci->callstatus &= ~CIST_YPCALL;
954964    L->errfunc = ci->u.c.old_errfunc;
r242959r242960
970980  status = luaD_protectedparser(L, &z, chunkname, mode);
971981  if (status == LUA_OK) {  /* no errors? */
972982    LClosure *f = clLvalue(L->top - 1);  /* get newly created function */
973    if (f->nupvalues >= 1) {  /* does it have an upvalue? */
983    if (f->nupvalues == 1) {  /* does it have one upvalue? */
974984      /* get global table from registry */
975985      Table *reg = hvalue(&G(L)->l_registry);
976986      const TValue *gt = luaH_getint(reg, LUA_RIDX_GLOBALS);
977987      /* set global table as 1st upvalue of 'f' (may be LUA_ENV) */
978988      setobj(L, f->upvals[0]->v, gt);
979      luaC_upvalbarrier(L, f->upvals[0]);
989      luaC_barrier(L, f->upvals[0], gt);
980990    }
981991  }
982992  lua_unlock(L);
r242959r242960
984994}
985995
986996
987LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data, int strip) {
997LUA_API int lua_dump (lua_State *L, lua_Writer writer, void *data) {
988998  int status;
989999  TValue *o;
9901000  lua_lock(L);
9911001  api_checknelems(L, 1);
9921002  o = L->top - 1;
9931003  if (isLfunction(o))
994    status = luaU_dump(L, getproto(o), writer, data, strip);
1004    status = luaU_dump(L, getproto(o), writer, data, 0);
9951005  else
9961006    status = 1;
9971007  lua_unlock(L);
r242959r242960
10371047      break;
10381048    }
10391049    case LUA_GCSTEP: {
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);
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 */
10461053      }
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);
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 */
10511062      }
1052      g->gcrunning = oldrunning;  /* restore previous state */
1053      if (debt > 0 && g->gcstate == GCSpause)  /* end of cycle? */
1054        res = 1;  /* signal it */
10551063      break;
10561064    }
10571065    case LUA_GCSETPAUSE: {
r242959r242960
10591067      g->gcpause = data;
10601068      break;
10611069    }
1070    case LUA_GCSETMAJORINC: {
1071      res = g->gcmajorinc;
1072      g->gcmajorinc = data;
1073      break;
1074    }
10621075    case LUA_GCSETSTEPMUL: {
10631076      res = g->gcstepmul;
1064      if (data < 40) data = 40;  /* avoid ridiculous low values (and 0) */
10651077      g->gcstepmul = data;
10661078      break;
10671079    }
r242959r242960
10691081      res = g->gcrunning;
10701082      break;
10711083    }
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    }
10721092    default: res = -1;  /* invalid option */
10731093  }
10741094  lua_unlock(L);
r242959r242960
10961116  int more;
10971117  lua_lock(L);
10981118  t = index2addr(L, idx);
1099  api_check(ttistable(t), "table expected");
1119  api_check(L, ttistable(t), "table expected");
11001120  more = luaH_next(L, hvalue(t), L->top - 1);
11011121  if (more) {
11021122    api_incr_top(L);
r242959r242960
11561176  Udata *u;
11571177  lua_lock(L);
11581178  luaC_checkGC(L);
1159  u = luaS_newudata(L, size);
1179  u = luaS_newudata(L, size, NULL);
11601180  setuvalue(L, L->top, u);
11611181  api_incr_top(L);
11621182  lua_unlock(L);
1163  return getudatamem(u);
1183  return u + 1;
11641184}
11651185
11661186
11671187
11681188static const char *aux_upvalue (StkId fi, int n, TValue **val,
1169                                CClosure **owner, UpVal **uv) {
1189                                GCObject **owner) {
11701190  switch (ttype(fi)) {
11711191    case LUA_TCCL: {  /* C closure */
11721192      CClosure *f = clCvalue(fi);
11731193      if (!(1 <= n && n <= f->nupvalues)) return NULL;
11741194      *val = &f->upvalue[n-1];
1175      if (owner) *owner = f;
1195      if (owner) *owner = obj2gco(f);
11761196      return "";
11771197    }
11781198    case LUA_TLCL: {  /* Lua closure */
r242959r242960
11811201      Proto *p = f->p;
11821202      if (!(1 <= n && n <= p->sizeupvalues)) return NULL;
11831203      *val = f->upvals[n-1]->v;
1184      if (uv) *uv = f->upvals[n - 1];
1204      if (owner) *owner = obj2gco(f->upvals[n - 1]);
11851205      name = p->upvalues[n-1].name;
1186      return (name == NULL) ? "(*no name)" : getstr(name);
1206      return (name == NULL) ? "" : getstr(name);
11871207    }
11881208    default: return NULL;  /* not a closure */
11891209  }
r242959r242960
11941214  const char *name;
11951215  TValue *val = NULL;  /* to avoid warnings */
11961216  lua_lock(L);
1197  name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL, NULL);
1217  name = aux_upvalue(index2addr(L, funcindex), n, &val, NULL);
11981218  if (name) {
11991219    setobj2s(L, L->top, val);
12001220    api_incr_top(L);
r242959r242960
12071227LUA_API const char *lua_setupvalue (lua_State *L, int funcindex, int n) {
12081228  const char *name;
12091229  TValue *val = NULL;  /* to avoid warnings */
1210  CClosure *owner = NULL;
1211  UpVal *uv = NULL;
1230  GCObject *owner = NULL;  /* to avoid warnings */
12121231  StkId fi;
12131232  lua_lock(L);
12141233  fi = index2addr(L, funcindex);
12151234  api_checknelems(L, 1);
1216  name = aux_upvalue(fi, n, &val, &owner, &uv);
1235  name = aux_upvalue(fi, n, &val, &owner);
12171236  if (name) {
12181237    L->top--;
12191238    setobj(L, val, L->top);
1220    if (owner) { luaC_barrier(L, owner, L->top); }
1221    else if (uv) { luaC_upvalbarrier(L, uv); }
1239    luaC_barrier(L, owner, L->top);
12221240  }
12231241  lua_unlock(L);
12241242  return name;
r242959r242960
12281246static UpVal **getupvalref (lua_State *L, int fidx, int n, LClosure **pf) {
12291247  LClosure *f;
12301248  StkId fi = index2addr(L, fidx);
1231  api_check(ttisLclosure(fi), "Lua function expected");
1249  api_check(L, ttisLclosure(fi), "Lua function expected");
12321250  f = clLvalue(fi);
1233  api_check((1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
1251  api_check(L, (1 <= n && n <= f->p->sizeupvalues), "invalid upvalue index");
12341252  if (pf) *pf = f;
12351253  return &f->upvals[n - 1];  /* get its upvalue pointer */
12361254}
r242959r242960
12441262    }
12451263    case LUA_TCCL: {  /* C closure */
12461264      CClosure *f = clCvalue(fi);
1247      api_check(1 <= n && n <= f->nupvalues, "invalid upvalue index");
1265      api_check(L, 1 <= n && n <= f->nupvalues, "invalid upvalue index");
12481266      return &f->upvalue[n - 1];
12491267    }
12501268    default: {
1251      api_check(0, "closure expected");
1269      api_check(L, 0, "closure expected");
12521270      return NULL;
12531271    }
12541272  }
r242959r242960
12601278  LClosure *f1;
12611279  UpVal **up1 = getupvalref(L, fidx1, n1, &f1);
12621280  UpVal **up2 = getupvalref(L, fidx2, n2, NULL);
1263  luaC_upvdeccount(L, *up1);
12641281  *up1 = *up2;
1265  (*up1)->refcount++;
1266  if (upisopen(*up1)) (*up1)->u.open.touched = 1;
1267  luaC_upvalbarrier(L, *up1);
1282  luaC_objbarrier(L, f1, *up2);
12681283}
12691284
1270
trunk/3rdparty/lua/src/lapi.h
r242959r242960
11/*
2** $Id: lapi.h,v 2.8 2014/07/15 21:26:50 roberto Exp $
2** $Id: lapi.h,v 2.7.1.1 2013/04/12 18:48:47 roberto Exp $
33** Auxiliary functions from Lua API
44** See Copyright Notice in lua.h
55*/
r242959r242960
1111#include "llimits.h"
1212#include "lstate.h"
1313
14#define api_incr_top(L)   {L->top++; api_check(L->top <= L->ci->top, \
14#define api_incr_top(L)   {L->top++; api_check(L, 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((n) < (L->top - L->ci->func), \
20#define api_checknelems(L,n)   api_check(L, (n) < (L->top - L->ci->func), \
2121              "not enough elements in the stack")
2222
2323
trunk/3rdparty/lua/src/lauxlib.c
r242959r242960
11/*
2** $Id: lauxlib.c,v 1.279 2014/12/14 18:32:26 roberto Exp $
2** $Id: lauxlib.c,v 1.248.1.1 2013/04/12 18:48:47 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
97
10#include "lprefix.h"
11
12
138#include <errno.h>
149#include <stdarg.h>
1510#include <stdio.h>
r242959r242960
2116** Any function declared here could be written as an application function.
2217*/
2318
19#define lauxlib_c
20#define LUA_LIB
21
2422#include "lua.h"
2523
2624#include "lauxlib.h"
r242959r242960
6664}
6765
6866
69/*
70** Search for a name for a function in all loaded modules
71** (registry._LOADED).
72*/
7367static int pushglobalfuncname (lua_State *L, lua_Debug *ar) {
7468  int top = lua_gettop(L);
7569  lua_getinfo(L, "f", ar);  /* push function */
76  lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
70  lua_pushglobaltable(L);
7771  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    }
8372    lua_copy(L, -1, top + 1);  /* move name to proper place */
8473    lua_pop(L, 2);  /* remove pushed values */
8574    return 1;
r242959r242960
9281
9382
9483static void pushfuncname (lua_State *L, lua_Debug *ar) {
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 */
84  if (*ar->namewhat != '\0')  /* is there a name? */
85    lua_pushfstring(L, "function " LUA_QS, ar->name);
10186  else if (*ar->what == 'm')  /* main? */
10287      lua_pushliteral(L, "main chunk");
103  else if (*ar->what != 'C')  /* for Lua functions, use <file:line> */
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
10497    lua_pushfstring(L, "function <%s:%d>", ar->short_src, ar->linedefined);
105  else  /* nothing left... */
106    lua_pushliteral(L, "?");
10798}
10899
109100
r242959r242960
159150** =======================================================
160151*/
161152
162LUALIB_API int luaL_argerror (lua_State *L, int arg, const char *extramsg) {
153LUALIB_API int luaL_argerror (lua_State *L, int narg, const char *extramsg) {
163154  lua_Debug ar;
164155  if (!lua_getstack(L, 0, &ar))  /* no stack frame? */
165    return luaL_error(L, "bad argument #%d (%s)", arg, extramsg);
156    return luaL_error(L, "bad argument #%d (%s)", narg, extramsg);
166157  lua_getinfo(L, "n", &ar);
167158  if (strcmp(ar.namewhat, "method") == 0) {
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)",
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)",
171162                           ar.name, extramsg);
172163  }
173164  if (ar.name == NULL)
174165    ar.name = (pushglobalfuncname(L, &ar)) ? lua_tostring(L, -1) : "?";
175  return luaL_error(L, "bad argument #%d to '%s' (%s)",
176                        arg, ar.name, extramsg);
166  return luaL_error(L, "bad argument #%d to " LUA_QS " (%s)",
167                        narg, ar.name, extramsg);
177168}
178169
179170
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);
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);
191175}
192176
193177
194static void tag_error (lua_State *L, int arg, int tag) {
195  typeerror(L, arg, lua_typename(L, tag));
178static void tag_error (lua_State *L, int narg, int tag) {
179  typeerror(L, narg, lua_typename(L, tag));
196180}
197181
198182
r242959r242960
238222}
239223
240224
241#if !defined(l_inspectstat)   /* { */
225#if !defined(inspectstat)   /* { */
242226
243227#if defined(LUA_USE_POSIX)
244228
r242959r242960
247231/*
248232** use appropriate macros to interpret 'pclose' return status
249233*/
250#define l_inspectstat(stat,what)  \
234#define inspectstat(stat,what)  \
251235   if (WIFEXITED(stat)) { stat = WEXITSTATUS(stat); } \
252236   else if (WIFSIGNALED(stat)) { stat = WTERMSIG(stat); what = "signal"; }
253237
254238#else
255239
256#define l_inspectstat(stat,what)  /* no op */
240#define inspectstat(stat,what)  /* no op */
257241
258242#endif
259243
r242959r242960
265249  if (stat == -1)  /* error? */
266250    return luaL_fileresult(L, 0, NULL);
267251  else {
268    l_inspectstat(stat, what);  /* interpret result */
252    inspectstat(stat, what);  /* interpret result */
269253    if (*what == 'e' && stat == 0)  /* successful termination? */
270254      lua_pushboolean(L, 1);
271255    else
r242959r242960
286270*/
287271
288272LUALIB_API int luaL_newmetatable (lua_State *L, const char *tname) {
289  if (luaL_getmetatable(L, tname))  /* name already in use? */
273  luaL_getmetatable(L, tname);  /* try to get metatable */
274  if (!lua_isnil(L, -1))  /* name already in use? */
290275    return 0;  /* leave previous value on top, but return 0 */
291276  lua_pop(L, 1);
292277  lua_newtable(L);  /* create metatable */
293  lua_pushstring(L, tname);
294  lua_setfield(L, -2, "__name");  /* metatable.__name = tname */
295278  lua_pushvalue(L, -1);
296279  lua_setfield(L, LUA_REGISTRYINDEX, tname);  /* registry.name = metatable */
297280  return 1;
r242959r242960
334317** =======================================================
335318*/
336319
337LUALIB_API int luaL_checkoption (lua_State *L, int arg, const char *def,
320LUALIB_API int luaL_checkoption (lua_State *L, int narg, const char *def,
338321                                 const char *const lst[]) {
339  const char *name = (def) ? luaL_optstring(L, arg, def) :
340                             luaL_checkstring(L, arg);
322  const char *name = (def) ? luaL_optstring(L, narg, def) :
323                             luaL_checkstring(L, narg);
341324  int i;
342325  for (i=0; lst[i]; i++)
343326    if (strcmp(lst[i], name) == 0)
344327      return i;
345  return luaL_argerror(L, arg,
346                       lua_pushfstring(L, "invalid option '%s'", name));
328  return luaL_argerror(L, narg,
329                       lua_pushfstring(L, "invalid option " LUA_QS, name));
347330}
348331
349332
r242959r242960
359342}
360343
361344
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);
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);
365348}
366349
367350
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");
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");
371354}
372355
373356
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);
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);
377360  return s;
378361}
379362
380363
381LUALIB_API const char *luaL_optlstring (lua_State *L, int arg,
364LUALIB_API const char *luaL_optlstring (lua_State *L, int narg,
382365                                        const char *def, size_t *len) {
383  if (lua_isnoneornil(L, arg)) {
366  if (lua_isnoneornil(L, narg)) {
384367    if (len)
385368      *len = (def ? strlen(def) : 0);
386369    return def;
387370  }
388  else return luaL_checklstring(L, arg, len);
371  else return luaL_checklstring(L, narg, len);
389372}
390373
391374
392LUALIB_API lua_Number luaL_checknumber (lua_State *L, int arg) {
375LUALIB_API lua_Number luaL_checknumber (lua_State *L, int narg) {
393376  int isnum;
394  lua_Number d = lua_tonumberx(L, arg, &isnum);
377  lua_Number d = lua_tonumberx(L, narg, &isnum);
395378  if (!isnum)
396    tag_error(L, arg, LUA_TNUMBER);
379    tag_error(L, narg, LUA_TNUMBER);
397380  return d;
398381}
399382
400383
401LUALIB_API lua_Number luaL_optnumber (lua_State *L, int arg, lua_Number def) {
402  return luaL_opt(L, luaL_checknumber, arg, def);
384LUALIB_API lua_Number luaL_optnumber (lua_State *L, int narg, lua_Number def) {
385  return luaL_opt(L, luaL_checknumber, narg, def);
403386}
404387
405388
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);
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;
411395}
412396
413397
414LUALIB_API lua_Integer luaL_checkinteger (lua_State *L, int arg) {
398LUALIB_API lua_Unsigned luaL_checkunsigned (lua_State *L, int narg) {
415399  int isnum;
416  lua_Integer d = lua_tointegerx(L, arg, &isnum);
417  if (!isnum) {
418    interror(L, arg);
419  }
400  lua_Unsigned d = lua_tounsignedx(L, narg, &isnum);
401  if (!isnum)
402    tag_error(L, narg, LUA_TNUMBER);
420403  return d;
421404}
422405
423406
424LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int arg,
407LUALIB_API lua_Integer luaL_optinteger (lua_State *L, int narg,
425408                                                      lua_Integer def) {
426  return luaL_opt(L, luaL_checkinteger, arg, def);
409  return luaL_opt(L, luaL_checkinteger, narg, def);
427410}
428411
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
429418/* }====================================================== */
430419
431420
r242959r242960
534523  int ref;
535524  if (lua_isnil(L, -1)) {
536525    lua_pop(L, 1);  /* remove from stack */
537    return LUA_REFNIL;  /* 'nil' has a unique fixed reference */
526    return LUA_REFNIL;  /* `nil' has a unique fixed reference */
538527  }
539528  t = lua_absindex(L, t);
540529  lua_rawgeti(L, t, freelist);  /* get first free element */
r242959r242960
573562typedef struct LoadF {
574563  int n;  /* number of pre-read characters */
575564  FILE *f;  /* file being read */
576  char buff[BUFSIZ];  /* area for reading file */
565  char buff[LUAL_BUFFERSIZE];  /* area for reading file */
577566} LoadF;
578567
579568
r242959r242960
666655  readstatus = ferror(lf.f);
667656  if (filename) fclose(lf.f);  /* close file (even in case of errors) */
668657  if (readstatus) {
669    lua_settop(L, fnameindex);  /* ignore results from 'lua_load' */
658    lua_settop(L, fnameindex);  /* ignore results from `lua_load' */
670659    return errfile(L, "read", fnameindex);
671660  }
672661  lua_remove(L, fnameindex);
r242959r242960
709698
710699LUALIB_API int luaL_getmetafield (lua_State *L, int obj, const char *event) {
711700  if (!lua_getmetatable(L, obj))  /* no metatable? */
712    return LUA_TNIL;
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  }
713708  else {
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 */
709    lua_remove(L, -2);  /* remove only metatable */
710    return 1;
722711  }
723712}
724713
725714
726715LUALIB_API int luaL_callmeta (lua_State *L, int obj, const char *event) {
727716  obj = lua_absindex(L, obj);
728  if (luaL_getmetafield(L, obj, event) == LUA_TNIL)  /* no metafield? */
717  if (!luaL_getmetafield(L, obj, event))  /* no metafield? */
729718    return 0;
730719  lua_pushvalue(L, obj);
731720  lua_call(L, 1, 1);
r242959r242960
733722}
734723
735724
736LUALIB_API lua_Integer luaL_len (lua_State *L, int idx) {
737  lua_Integer l;
725LUALIB_API int luaL_len (lua_State *L, int idx) {
726  int l;
738727  int isnum;
739728  lua_len(L, idx);
740  l = lua_tointegerx(L, -1, &isnum);
729  l = (int)lua_tointegerx(L, -1, &isnum);
741730  if (!isnum)
742    luaL_error(L, "object length is not an integer");
731    luaL_error(L, "object length is not a number");
743732  lua_pop(L, 1);  /* remove object */
744733  return l;
745734}
r242959r242960
748737LUALIB_API const char *luaL_tolstring (lua_State *L, int idx, size_t *len) {
749738  if (!luaL_callmeta(L, idx, "__tostring")) {  /* no metafield? */
750739    switch (lua_type(L, idx)) {
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      }
740      case LUA_TNUMBER:
758741      case LUA_TSTRING:
759742        lua_pushvalue(L, idx);
760743        break;
r242959r242960
789772    e = strchr(fname, '.');
790773    if (e == NULL) e = fname + strlen(fname);
791774    lua_pushlstring(L, fname, e - fname);
792    if (lua_rawget(L, -2) == LUA_TNIL) {  /* no such field? */
775    lua_rawget(L, -2);
776    if (lua_isnil(L, -1)) {  /* no such field? */
793777      lua_pop(L, 1);  /* remove this nil */
794778      lua_createtable(L, 0, (*e == '.' ? 1 : szhint)); /* new table for field */
795779      lua_pushlstring(L, fname, e - fname);
r242959r242960
826810LUALIB_API void luaL_pushmodule (lua_State *L, const char *modname,
827811                                 int sizehint) {
828812  luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 1);  /* get _LOADED table */
829  if (lua_getfield(L, -1, modname) != LUA_TTABLE) {  /* no _LOADED[modname]? */
813  lua_getfield(L, -1, modname);  /* get _LOADED[modname] */
814  if (!lua_istable(L, -1)) {  /* not found? */
830815    lua_pop(L, 1);  /* remove previous result */
831816    /* try global variable (and create one if it does not exist) */
832817    lua_pushglobaltable(L);
833818    if (luaL_findtable(L, 0, modname, sizehint) != NULL)
834      luaL_error(L, "name conflict for module '%s'", modname);
819      luaL_error(L, "name conflict for module " LUA_QS, modname);
835820    lua_pushvalue(L, -1);
836821    lua_setfield(L, -3, modname);  /* _LOADED[modname] = new table */
837822  }
r242959r242960
861846** Returns with only the table at the stack.
862847*/
863848LUALIB_API void luaL_setfuncs (lua_State *L, const luaL_Reg *l, int nup) {
849  luaL_checkversion(L);
864850  luaL_checkstack(L, nup, "too many upvalues");
865851  for (; l->name != NULL; l++) {  /* fill the table with given functions */
866852    int i;
r242959r242960
878864** into the stack
879865*/
880866LUALIB_API int luaL_getsubtable (lua_State *L, int idx, const char *fname) {
881  if (lua_getfield(L, idx, fname) == LUA_TTABLE)
882    return 1;  /* table already there */
867  lua_getfield(L, idx, fname);
868  if (lua_istable(L, -1)) return 1;  /* table already there */
883869  else {
884870    lua_pop(L, 1);  /* remove previous result */
885871    idx = lua_absindex(L, idx);
r242959r242960
892878
893879
894880/*
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.
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.
898884** Leaves resulting module on the top.
899885*/
900886LUALIB_API void luaL_requiref (lua_State *L, const char *modname,
901887                               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 */
902891  luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
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 */
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 */
913895  if (glb) {
914    lua_pushvalue(L, -1);  /* copy of module */
896    lua_pushvalue(L, -1);  /* copy of 'mod' */
915897    lua_setglobal(L, modname);  /* _G[modname] = module */
916898  }
917899}
r242959r242960
926908  while ((wild = strstr(s, p)) != NULL) {
927909    luaL_addlstring(&b, s, wild - s);  /* push prefix */
928910    luaL_addstring(&b, r);  /* push replacement in place of pattern */
929    s = wild + l;  /* continue after 'p' */
911    s = wild + l;  /* continue after `p' */
930912  }
931913  luaL_addstring(&b, s);  /* push last suffix */
932914  luaL_pushresult(&b);
r242959r242960
946928
947929
948930static int panic (lua_State *L) {
949  lua_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
950                        lua_tostring(L, -1));
931  luai_writestringerror("PANIC: unprotected error in call to Lua API (%s)\n",
932                   lua_tostring(L, -1));
951933  return 0;  /* return to Lua to abort */
952934}
953935
r242959r242960
959941}
960942
961943
962LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver, size_t sz) {
944LUALIB_API void luaL_checkversion_ (lua_State *L, lua_Number ver) {
963945  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");
966946  if (v != lua_version(NULL))
967947    luaL_error(L, "multiple Lua VMs detected");
968948  else if (*v != ver)
969949    luaL_error(L, "version mismatch: app. needs %f, Lua core provides %f",
970950                  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);
971958}
972959
trunk/3rdparty/lua/src/lauxlib.h
r242959r242960
11/*
2** $Id: lauxlib.h,v 1.128 2014/10/29 16:11:17 roberto Exp $
2** $Id: lauxlib.h,v 1.120.1.1 2013/04/12 18:48:47 roberto Exp $
33** Auxiliary functions for building Lua libraries
44** See Copyright Notice in lua.h
55*/
r242959r242960
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
r242959r242960
2626} luaL_Reg;
2727
2828
29#define LUAL_NUMSIZES   (sizeof(lua_Integer)*16 + sizeof(lua_Number))
29LUALIB_API void (luaL_checkversion_) (lua_State *L, lua_Number ver);
30#define luaL_checkversion(L)   luaL_checkversion_(L, LUA_VERSION_NUM)
3031
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
3532LUALIB_API int (luaL_getmetafield) (lua_State *L, int obj, const char *e);
3633LUALIB_API int (luaL_callmeta) (lua_State *L, int obj, const char *e);
3734LUALIB_API const char *(luaL_tolstring) (lua_State *L, int idx, size_t *len);
38LUALIB_API int (luaL_argerror) (lua_State *L, int arg, const char *extramsg);
39LUALIB_API const char *(luaL_checklstring) (lua_State *L, int arg,
35LUALIB_API int (luaL_argerror) (lua_State *L, int numarg, const char *extramsg);
36LUALIB_API const char *(luaL_checklstring) (lua_State *L, int numArg,
4037                                                          size_t *l);
41LUALIB_API const char *(luaL_optlstring) (lua_State *L, int arg,
38LUALIB_API const char *(luaL_optlstring) (lua_State *L, int numArg,
4239                                          const char *def, size_t *l);
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);
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);
4542
46LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int arg);
47LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int arg,
43LUALIB_API lua_Integer (luaL_checkinteger) (lua_State *L, int numArg);
44LUALIB_API lua_Integer (luaL_optinteger) (lua_State *L, int nArg,
4845                                          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 arg, int t);
52LUALIB_API void (luaL_checkany) (lua_State *L, int arg);
51LUALIB_API void (luaL_checktype) (lua_State *L, int narg, int t);
52LUALIB_API void (luaL_checkany) (lua_State *L, int narg);
5353
5454LUALIB_API int   (luaL_newmetatable) (lua_State *L, const char *tname);
5555LUALIB_API void  (luaL_setmetatable) (lua_State *L, const char *tname);
r242959r242960
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 arg, const char *def,
62LUALIB_API int (luaL_checkoption) (lua_State *L, int narg, const char *def,
6363                                   const char *const lst[]);
6464
6565LUALIB_API int (luaL_fileresult) (lua_State *L, int stat, const char *fname);
r242959r242960
8383
8484LUALIB_API lua_State *(luaL_newstate) (void);
8585
86LUALIB_API lua_Integer (luaL_len) (lua_State *L, int idx);
86LUALIB_API int (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);
r242959r242960
108108#define luaL_newlibtable(L,l)   \
109109  lua_createtable(L, 0, sizeof(l)/sizeof((l)[0]) - 1)
110110
111#define luaL_newlib(L,l)  \
112  (luaL_checkversion(L), luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
111#define luaL_newlib(L,l)   (luaL_newlibtable(L,l), luaL_setfuncs(L,l,0))
113112
114#define luaL_argcheck(L, cond,arg,extramsg)   \
115      ((void)((cond) || luaL_argerror(L, (arg), (extramsg))))
113#define luaL_argcheck(L, cond,numarg,extramsg)   \
114      ((void)((cond) || luaL_argerror(L, (numarg), (extramsg))))
116115#define luaL_checkstring(L,n)   (luaL_checklstring(L, (n), NULL))
117116#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)))
118121
119122#define luaL_typename(L,i)   lua_typename(L, lua_type(L,(i)))
120123
r242959r242960
204207#endif
205208
206209
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)
216210#endif
217211
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
222212
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
r242959r242960
11/*
2** $Id: lbaselib.c,v 1.309 2014/12/10 12:26:42 roberto Exp $
2** $Id: lbaselib.c,v 1.276.1.1 2013/04/12 18:48:47 roberto Exp $
33** Basic library
44** See Copyright Notice in lua.h
55*/
66
7#define lbaselib_c
8#define LUA_LIB
97
10#include "lprefix.h"
118
12
139#include <ctype.h>
1410#include <stdio.h>
1511#include <stdlib.h>
1612#include <string.h>
1713
14#define lbaselib_c
15#define LUA_LIB
16
1817#include "lua.h"
1918
2019#include "lauxlib.h"
r242959r242960
3332    lua_call(L, 1, 1);
3433    s = lua_tolstring(L, -1, &l);  /* get result */
3534    if (s == NULL)
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);
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);
3939    lua_pop(L, 1);  /* pop result */
4040  }
41  lua_writeline();
41  luai_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
6948static int luaB_tonumber (lua_State *L) {
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 */
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);
7454      return 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    }
55    }  /* else not a number; must be something */
56    luaL_checkany(L, 1);
8357  }
8458  else {
8559    size_t l;
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);
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;
9164    luaL_argcheck(L, 2 <= base && base <= 36, 2, "base out of range");
92    if (b_str2int(s, (int)base, &n) == s + l) {
93      lua_pushinteger(L, n);
94      return 1;
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 */
9582    }  /* else not a number */
96  }  /* else not a number */
83  }
9784  lua_pushnil(L);  /* not a number */
9885  return 1;
9986}
10087
10188
10289static int luaB_error (lua_State *L) {
103  int level = (int)luaL_optinteger(L, 2, 1);
90  int level = luaL_optint(L, 2, 1);
10491  lua_settop(L, 1);
10592  if (lua_isstring(L, 1) && level > 0) {  /* add extra information? */
10693    luaL_where(L, level);
r242959r242960
127114  luaL_checktype(L, 1, LUA_TTABLE);
128115  luaL_argcheck(L, t == LUA_TNIL || t == LUA_TTABLE, 2,
129116                    "nil or table expected");
130  if (luaL_getmetafield(L, 1, "__metatable") != LUA_TNIL)
117  if (luaL_getmetafield(L, 1, "__metatable"))
131118    return luaL_error(L, "cannot change a protected metatable");
132119  lua_settop(L, 2);
133120  lua_setmetatable(L, 1);
r242959r242960
173160static int luaB_collectgarbage (lua_State *L) {
174161  static const char *const opts[] = {"stop", "restart", "collect",
175162    "count", "step", "setpause", "setstepmul",
176    "isrunning", NULL};
163    "setmajorinc", "isrunning", "generational", "incremental", NULL};
177164  static const int optsnum[] = {LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT,
178165    LUA_GCCOUNT, LUA_GCSTEP, LUA_GCSETPAUSE, LUA_GCSETSTEPMUL,
179    LUA_GCISRUNNING};
166    LUA_GCSETMAJORINC, LUA_GCISRUNNING, LUA_GCGEN, LUA_GCINC};
180167  int o = optsnum[luaL_checkoption(L, 1, "collect", opts)];
181  int ex = (int)luaL_optinteger(L, 2, 0);
168  int ex = luaL_optint(L, 2, 0);
182169  int res = lua_gc(L, o, ex);
183170  switch (o) {
184171    case LUA_GCCOUNT: {
185172      int b = lua_gc(L, LUA_GCCOUNTB, 0);
186      lua_pushnumber(L, (lua_Number)res + ((lua_Number)b/1024));
187      return 1;
173      lua_pushnumber(L, res + ((lua_Number)b/1024));
174      lua_pushinteger(L, b);
175      return 2;
188176    }
189177    case LUA_GCSTEP: case LUA_GCISRUNNING: {
190178      lua_pushboolean(L, res);
r242959r242960
198186}
199187
200188
201/*
202** This function has all type names as upvalues, to maximize performance.
203*/
204189static int luaB_type (lua_State *L) {
205190  luaL_checkany(L, 1);
206  lua_pushvalue(L, lua_upvalueindex(lua_type(L, 1) + 1));
191  lua_pushstring(L, luaL_typename(L, 1));
207192  return 1;
208193}
209194
210195
211196static int pairsmeta (lua_State *L, const char *method, int iszero,
212197                      lua_CFunction iter) {
213  if (luaL_getmetafield(L, 1, method) == LUA_TNIL) {  /* no metamethod? */
198  if (!luaL_getmetafield(L, 1, method)) {  /* no metamethod? */
214199    luaL_checktype(L, 1, LUA_TTABLE);  /* argument must be a table */
215200    lua_pushcfunction(L, iter);  /* will return generator, */
216201    lua_pushvalue(L, 1);  /* state, */
r242959r242960
242227}
243228
244229
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;
230static int ipairsaux (lua_State *L) {
231  int i = luaL_checkint(L, 2);
250232  luaL_checktype(L, 1, LUA_TTABLE);
233  i++;  /* next value */
251234  lua_pushinteger(L, i);
252  return (lua_rawgeti(L, 1, i) == LUA_TNIL) ? 1 : 2;
235  lua_rawgeti(L, 1, i);
236  return (lua_isnil(L, -1)) ? 1 : 2;
253237}
254238
255239
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*/
271240static int luaB_ipairs (lua_State *L) {
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
241  return pairsmeta(L, "__ipairs", 1, ipairsaux);
283242}
284243
285244
r242959r242960
325284
326285
327286/*
328** Reader for generic 'load' function: 'lua_load' uses the
287** Reader for generic `load' function: `lua_load' uses the
329288** stack for internal stuff, so the reader cannot change the
330289** stack top. Instead, it keeps its resulting string in a
331290** reserved slot inside the stack.
r242959r242960
369328/* }====================================================== */
370329
371330
372static int dofilecont (lua_State *L, int d1, lua_KContext d2) {
373  (void)d1;  (void)d2;  /* only to match 'lua_Kfunction' prototype */
331static int dofilecont (lua_State *L) {
374332  return lua_gettop(L) - 1;
375333}
376334
r242959r242960
381339  if (luaL_loadfile(L, fname) != LUA_OK)
382340    return lua_error(L);
383341  lua_callk(L, 0, LUA_MULTRET, 0, dofilecont);
384  return dofilecont(L, 0, 0);
342  return dofilecont(L);
385343}
386344
387345
388346static int luaB_assert (lua_State *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  }
347  if (!lua_toboolean(L, 1))
348    return luaL_error(L, "%s", luaL_optstring(L, 2, "assertion failed!"));
349  return lua_gettop(L);
398350}
399351
400352
r242959r242960
405357    return 1;
406358  }
407359  else {
408    lua_Integer i = luaL_checkinteger(L, 1);
360    int i = luaL_checkint(L, 1);
409361    if (i < 0) i = n + i;
410362    else if (i > n) i = n;
411363    luaL_argcheck(L, 1 <= i, 1, "index out of range");
412    return n - (int)i;
364    return n - i;
413365  }
414366}
415367
416368
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 */
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");
428374    return 2;  /* return false, msg */
429375  }
430  else
431    return lua_gettop(L) - (int)extra;  /* return all results */
376  lua_pushboolean(L, status);  /* first result (status) */
377  lua_replace(L, 1);  /* put first result in first slot */
378  return lua_gettop(L);
432379}
433380
434381
382static int pcallcont (lua_State *L) {
383  int status = lua_getctx(L, NULL);
384  return finishpcall(L, (status == LUA_YIELD));
385}
386
387
435388static int luaB_pcall (lua_State *L) {
436389  int status;
437390  luaL_checkany(L, 1);
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);
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));
442395}
443396
444397
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*/
450398static int luaB_xpcall (lua_State *L) {
451399  int status;
452400  int n = lua_gettop(L);
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);
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));
459407}
460408
461409
r242959r242960
490438  {"setmetatable", luaB_setmetatable},
491439  {"tonumber", luaB_tonumber},
492440  {"tostring", luaB_tostring},
441  {"type", luaB_type},
493442  {"xpcall", luaB_xpcall},
494  /* placeholders */
495  {"type", NULL},
496  {"_G", NULL},
497  {"_VERSION", NULL},
498443  {NULL, NULL}
499444};
500445
501446
502447LUAMOD_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);
507448  /* set global _G */
508  lua_pushvalue(L, -1);
449  lua_pushglobaltable(L);
450  lua_pushglobaltable(L);
509451  lua_setfield(L, -2, "_G");
510  /* set global _VERSION */
452  /* open lib into global table */
453  luaL_setfuncs(L, base_funcs, 0);
511454  lua_pushliteral(L, LUA_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");
455  lua_setfield(L, -2, "_VERSION");  /* set global _VERSION */
518456  return 1;
519457}
520458
trunk/3rdparty/lua/src/lbitlib.c
r242959r242960
11/*
2** $Id: lbitlib.c,v 1.28 2014/11/02 19:19:04 roberto Exp $
2** $Id: lbitlib.c,v 1.18.1.2 2013/07/09 18:01:41 roberto Exp $
33** Standard library for bitwise operations
44** See Copyright Notice in lua.h
55*/
r242959r242960
77#define lbitlib_c
88#define LUA_LIB
99
10#include "lprefix.h"
11
12
1310#include "lua.h"
1411
1512#include "lauxlib.h"
1613#include "lualib.h"
1714
1815
19#if defined(LUA_COMPAT_BITLIB)      /* { */
20
21
2216/* number of bits to consider in a number */
2317#if !defined(LUA_NBITS)
2418#define LUA_NBITS   32
2519#endif
2620
2721
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*/
3322#define ALLONES      (~(((~(lua_Unsigned)0) << (LUA_NBITS - 1)) << 1))
3423
35
3624/* macro to trim extra bits */
3725#define trim(x)      ((x) & ALLONES)
3826
r242959r242960
4129#define mask(n)      (~((ALLONES << 1) << ((n) - 1)))
4230
4331
32typedef lua_Unsigned b_uint;
4433
45static lua_Unsigned andaux (lua_State *L) {
34
35
36static b_uint andaux (lua_State *L) {
4637  int i, n = lua_gettop(L);
47  lua_Unsigned r = ~(lua_Unsigned)0;
38  b_uint r = ~(b_uint)0;
4839  for (i = 1; i <= n; i++)
4940    r &= luaL_checkunsigned(L, i);
5041  return trim(r);
r242959r242960
5243
5344
5445static int b_and (lua_State *L) {
55  lua_Unsigned r = andaux(L);
46  b_uint r = andaux(L);
5647  lua_pushunsigned(L, r);
5748  return 1;
5849}
5950
6051
6152static int b_test (lua_State *L) {
62  lua_Unsigned r = andaux(L);
53  b_uint r = andaux(L);
6354  lua_pushboolean(L, r != 0);
6455  return 1;
6556}
r242959r242960
6758
6859static int b_or (lua_State *L) {
6960  int i, n = lua_gettop(L);
70  lua_Unsigned r = 0;
61  b_uint r = 0;
7162  for (i = 1; i <= n; i++)
7263    r |= luaL_checkunsigned(L, i);
7364  lua_pushunsigned(L, trim(r));
r242959r242960
7768
7869static int b_xor (lua_State *L) {
7970  int i, n = lua_gettop(L);
80  lua_Unsigned r = 0;
71  b_uint r = 0;
8172  for (i = 1; i <= n; i++)
8273    r ^= luaL_checkunsigned(L, i);
8374  lua_pushunsigned(L, trim(r));
r242959r242960
8677
8778
8879static int b_not (lua_State *L) {
89  lua_Unsigned r = ~luaL_checkunsigned(L, 1);
80  b_uint r = ~luaL_checkunsigned(L, 1);
9081  lua_pushunsigned(L, trim(r));
9182  return 1;
9283}
9384
9485
95static int b_shift (lua_State *L, lua_Unsigned r, lua_Integer i) {
86static int b_shift (lua_State *L, b_uint r, int i) {
9687  if (i < 0) {  /* shift right? */
9788    i = -i;
9889    r = trim(r);
r242959r242960
110101
111102
112103static int b_lshift (lua_State *L) {
113  return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkinteger(L, 2));
104  return b_shift(L, luaL_checkunsigned(L, 1), luaL_checkint(L, 2));
114105}
115106
116107
117108static int b_rshift (lua_State *L) {
118  return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkinteger(L, 2));
109  return b_shift(L, luaL_checkunsigned(L, 1), -luaL_checkint(L, 2));
119110}
120111
121112
122113static int b_arshift (lua_State *L) {
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))))
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))))
126117    return b_shift(L, r, -i);
127118  else {  /* arithmetic shift for 'negative' number */
128119    if (i >= LUA_NBITS) r = ALLONES;
129120    else
130      r = trim((r >> i) | ~(trim(~(lua_Unsigned)0) >> i));  /* add signal bit */
121      r = trim((r >> i) | ~(~(b_uint)0 >> i));  /* add signal bit */
131122    lua_pushunsigned(L, r);
132123    return 1;
133124  }
134125}
135126
136127
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 */
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 */
140131  r = trim(r);
141132  if (i != 0)  /* avoid undefined shift of LUA_NBITS when i == 0 */
142133    r = (r << i) | (r >> (LUA_NBITS - i));
r242959r242960
146137
147138
148139static int b_lrot (lua_State *L) {
149  return b_rot(L, luaL_checkinteger(L, 2));
140  return b_rot(L, luaL_checkint(L, 2));
150141}
151142
152143
153144static int b_rrot (lua_State *L) {
154  return b_rot(L, -luaL_checkinteger(L, 2));
145  return b_rot(L, -luaL_checkint(L, 2));
155146}
156147
157148
r242959r242960
162153** 'width' being used uninitialized.)
163154*/
164155static int fieldargs (lua_State *L, int farg, int *width) {
165  lua_Integer f = luaL_checkinteger(L, farg);
166  lua_Integer w = luaL_optinteger(L, farg + 1, 1);
156  int f = luaL_checkint(L, farg);
157  int w = luaL_optint(L, farg + 1, 1);
167158  luaL_argcheck(L, 0 <= f, farg, "field cannot be negative");
168159  luaL_argcheck(L, 0 < w, farg + 1, "width must be positive");
169160  if (f + w > LUA_NBITS)
170161    luaL_error(L, "trying to access non-existent bits");
171  *width = (int)w;
172  return (int)f;
162  *width = w;
163  return f;
173164}
174165
175166
176167static int b_extract (lua_State *L) {
177168  int w;
178  lua_Unsigned r = trim(luaL_checkunsigned(L, 1));
169  b_uint r = luaL_checkunsigned(L, 1);
179170  int f = fieldargs(L, 2, &w);
180171  r = (r >> f) & mask(w);
181172  lua_pushunsigned(L, r);
r242959r242960
185176
186177static int b_replace (lua_State *L) {
187178  int w;
188  lua_Unsigned r = trim(luaL_checkunsigned(L, 1));
189  lua_Unsigned v = luaL_checkunsigned(L, 2);
179  b_uint r = luaL_checkunsigned(L, 1);
180  b_uint v = luaL_checkunsigned(L, 2);
190181  int f = fieldargs(L, 3, &w);
191182  int m = mask(w);
192183  v &= m;  /* erase bits outside given width */
r242959r242960
219210  return 1;
220211}
221212
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
r242959r242960
11/*
2** $Id: lcode.c,v 2.99 2014/12/29 16:49:25 roberto Exp $
2** $Id: lcode.c,v 2.62.1.1 2013/04/12 18:48:47 roberto Exp $
33** Code generator for Lua
44** See Copyright Notice in lua.h
55*/
66
7#define lcode_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
13#include <math.h>
148#include <stdlib.h>
159
10#define lcode_c
11#define LUA_CORE
12
1613#include "lua.h"
1714
1815#include "lcode.h"
r242959r242960
2926#include "lvm.h"
3027
3128
32/* Maximum number of registers in a Lua function */
33#define MAXREGS      250
34
35
3629#define hasjumps(e)   ((e)->t != (e)->f)
3730
3831
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  }
32static int isnumeral(expdesc *e) {
33  return (e->k == VKNUM && e->t == NO_JUMP && e->f == NO_JUMP);
5134}
5235
5336
r242959r242960
10588
10689
10790/*
108** returns current 'pc' and marks it as a jump target (to avoid wrong
91** returns current `pc' and marks it as a jump target (to avoid wrong
10992** optimizations with consecutive instructions not in the same basic block).
11093*/
11194int luaK_getlabel (FuncState *fs) {
r242959r242960
193176}
194177
195178
196void luaK_patchclose (FuncState *fs, int list, int level) {
179LUAI_FUNC void luaK_patchclose (FuncState *fs, int list, int level) {
197180  level++;  /* argument is +1 to reserve 0 as non-op */
198181  while (list != NO_JUMP) {
199182    int next = getjump(fs, list);
r242959r242960
228211
229212static int luaK_code (FuncState *fs, Instruction i) {
230213  Proto *f = fs->f;
231  dischargejpc(fs);  /* 'pc' will change */
214  dischargejpc(fs);  /* `pc' will change */
232215  /* put new instruction in code array */
233216  luaM_growvector(fs->ls->L, f->code, fs->pc, f->sizecode, Instruction,
234217                  MAX_INT, "opcodes");
r242959r242960
278261void luaK_checkstack (FuncState *fs, int n) {
279262  int newstack = fs->freereg + n;
280263  if (newstack > fs->f->maxstacksize) {
281    if (newstack >= MAXREGS)
264    if (newstack >= MAXSTACK)
282265      luaX_syntaxerror(fs->ls, "function or expression too complex");
283266    fs->f->maxstacksize = cast_byte(newstack);
284267  }
r242959r242960
305288}
306289
307290
308/*
309** Use scanner's table to cache position of constants in constant list
310** and try to reuse constants
311*/
312291static int addk (FuncState *fs, TValue *key, TValue *v) {
313292  lua_State *L = fs->ls->L;
293  TValue *idx = luaH_set(L, fs->h, key);
314294  Proto *f = fs->f;
315  TValue *idx = luaH_set(L, fs->ls->h, key);  /* index scanner table */
316295  int k, oldsize;
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 */
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 */
323303  }
324304  /* constant not found; create a new entry */
325305  oldsize = f->sizek;
326306  k = fs->nk;
327307  /* numerical value does not need GC barrier;
328308     table has no metatable, so it does not need to invalidate cache */
329  setivalue(idx, k);
309  setnvalue(idx, cast_num(k));
330310  luaM_growvector(L, f->k, k, f->sizek, TValue, MAXARG_Ax, "constants");
331311  while (oldsize < f->sizek) setnilvalue(&f->k[oldsize++]);
332312  setobj(L, &f->k[k], v);
r242959r242960
343323}
344324
345325
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) {
326int luaK_numberK (FuncState *fs, lua_Number r) {
327  int n;
328  lua_State *L = fs->ls->L;
360329  TValue o;
361  setfltvalue(&o, r);
362  return addk(fs, &o, &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;
363340}
364341
365342
r242959r242960
374351  TValue k, v;
375352  setnilvalue(&v);
376353  /* cannot use nil as key; instead use table itself to represent nil */
377  sethvalue(fs->ls->L, &k, fs->ls->h);
354  sethvalue(fs->ls->L, &k, fs->h);
378355  return addk(fs, &k, &v);
379356}
380357
r242959r242960
456433      luaK_codek(fs, reg, e->u.info);
457434      break;
458435    }
459    case VKFLT: {
436    case VKNUM: {
460437      luaK_codek(fs, reg, luaK_numberK(fs, e->u.nval));
461438      break;
462439    }
463    case VKINT: {
464      luaK_codek(fs, reg, luaK_intK(fs, e->u.ival));
465      break;
466    }
467440    case VRELOCABLE: {
468441      Instruction *pc = &getcode(fs, e);
469442      SETARG_A(*pc, reg);
r242959r242960
495468static void exp2reg (FuncState *fs, expdesc *e, int reg) {
496469  discharge2reg(fs, e, reg);
497470  if (e->k == VJMP)
498    luaK_concat(fs, &e->t, e->u.info);  /* put this jump in 't' list */
471    luaK_concat(fs, &e->t, e->u.info);  /* put this jump in `t' list */
499472  if (hasjumps(e)) {
500473    int final;  /* position after whole expression */
501474    int p_f = NO_JUMP;  /* position of an eventual LOAD false */
r242959r242960
565538      }
566539      else break;
567540    }
568    case VKINT: {
569      e->u.info = luaK_intK(fs, e->u.ival);
570      e->k = VK;
571      goto vk;
572    }
573    case VKFLT: {
541    case VKNUM: {
574542      e->u.info = luaK_numberK(fs, e->u.nval);
575543      e->k = VK;
576544      /* go through */
577545    }
578546    case VK: {
579     vk:
580      if (e->u.info <= MAXINDEXRK)  /* constant fits in 'argC'? */
547      if (e->u.info <= MAXINDEXRK)  /* constant fits in argC? */
581548        return RKASK(e->u.info);
582549      else break;
583550    }
r242959r242960
660627      pc = e->u.info;
661628      break;
662629    }
663    case VK: case VKFLT: case VKINT: case VTRUE: {
630    case VK: case VKNUM: case VTRUE: {
664631      pc = NO_JUMP;  /* always true; do nothing */
665632      break;
666633    }
r242959r242960
669636      break;
670637    }
671638  }
672  luaK_concat(fs, &e->f, pc);  /* insert last jump in 'f' list */
639  luaK_concat(fs, &e->f, pc);  /* insert last jump in `f' list */
673640  luaK_patchtohere(fs, e->t);
674641  e->t = NO_JUMP;
675642}
r242959r242960
692659      break;
693660    }
694661  }
695  luaK_concat(fs, &e->t, pc);  /* insert last jump in 't' list */
662  luaK_concat(fs, &e->t, pc);  /* insert last jump in `t' list */
696663  luaK_patchtohere(fs, e->f);
697664  e->f = NO_JUMP;
698665}
r242959r242960
705672      e->k = VTRUE;
706673      break;
707674    }
708    case VK: case VKFLT: case VKINT: case VTRUE: {
675    case VK: case VKNUM: case VTRUE: {
709676      e->k = VFALSE;
710677      break;
711678    }
r242959r242960
743710}
744711
745712
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  }
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;
782720  return 1;
783721}
784722
785723
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 */
724static void codearith (FuncState *fs, OpCode op,
725                       expdesc *e1, expdesc *e2, int line) {
726  if (constfolding(op, e1, e2))
727    return;
798728  else {
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 */
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) {
810732      freeexp(fs, e1);
811733      freeexp(fs, e2);
812734    }
r242959r242960
814736      freeexp(fs, e2);
815737      freeexp(fs, e1);
816738    }
817    e1->u.info = luaK_codeABC(fs, op, 0, o1, o2);  /* generate opcode */
818    e1->k = VRELOCABLE;  /* all those operations are relocable */
739    e1->u.info = luaK_codeABC(fs, op, 0, o1, o2);
740    e1->k = VRELOCABLE;
819741    luaK_fixline(fs, line);
820742  }
821743}
r242959r242960
828750  freeexp(fs, e2);
829751  freeexp(fs, e1);
830752  if (cond == 0 && op != OP_EQ) {
831    int temp;  /* exchange args to replace by '<' or '<=' */
753    int temp;  /* exchange args to replace by `<' or `<=' */
832754    temp = o1; o1 = o2; o2 = temp;  /* o1 <==> o2 */
833755    cond = 1;
834756  }
r242959r242960
839761
840762void luaK_prefix (FuncState *fs, UnOpr op, expdesc *e, int line) {
841763  expdesc e2;
842  e2.t = e2.f = NO_JUMP; e2.k = VKINT; e2.u.ival = 0;
764  e2.t = e2.f = NO_JUMP; e2.k = VKNUM; e2.u.nval = 0;
843765  switch (op) {
844    case OPR_MINUS: case OPR_BNOT: case OPR_LEN: {
845      codeexpval(fs, cast(OpCode, (op - OPR_MINUS) + OP_UNM), e, &e2, line);
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      }
846773      break;
847774    }
848775    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    }
849781    default: lua_assert(0);
850782  }
851783}
r242959r242960
862794      break;
863795    }
864796    case OPR_CONCAT: {
865      luaK_exp2nextreg(fs, v);  /* operand must be on the 'stack' */
797      luaK_exp2nextreg(fs, v);  /* operand must be on the `stack' */
866798      break;
867799    }
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);
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);
874803      break;
875804    }
876805    default: {
r242959r242960
908837      }
909838      else {
910839        luaK_exp2nextreg(fs, e2);  /* operand must be on the 'stack' */
911        codeexpval(fs, OP_CONCAT, e1, e2, line);
840        codearith(fs, OP_CONCAT, e1, e2, line);
912841      }
913842      break;
914843    }
915844    case OPR_ADD: case OPR_SUB: case OPR_MUL: case OPR_DIV:
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);
845    case OPR_MOD: case OPR_POW: {
846      codearith(fs, cast(OpCode, op - OPR_ADD + OP_ADD), e1, e2, line);
920847      break;
921848    }
922849    case OPR_EQ: case OPR_LT: case OPR_LE: {
trunk/3rdparty/lua/src/lcode.h
r242959r242960
11/*
2** $Id: lcode.h,v 1.63 2013/12/30 20:47:58 roberto Exp $
2** $Id: lcode.h,v 1.58.1.1 2013/04/12 18:48:47 roberto Exp $
33** Code generator for Lua
44** See Copyright Notice in lua.h
55*/
r242959r242960
2424** grep "ORDER OPR" if you change these enums  (ORDER OP)
2525*/
2626typedef enum BinOpr {
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,
27  OPR_ADD, OPR_SUB, OPR_MUL, OPR_DIV, OPR_MOD, OPR_POW,
3228  OPR_CONCAT,
3329  OPR_EQ, OPR_LT, OPR_LE,
3430  OPR_NE, OPR_GT, OPR_GE,
r242959r242960
3733} BinOpr;
3834
3935
40typedef enum UnOpr { OPR_MINUS, OPR_BNOT, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
36typedef enum UnOpr { OPR_MINUS, OPR_NOT, OPR_LEN, OPR_NOUNOPR } UnOpr;
4137
4238
4339#define getcode(fs,e)   ((fs)->f->code[(e)->u.info])
r242959r242960
5652LUAI_FUNC void luaK_reserveregs (FuncState *fs, int n);
5753LUAI_FUNC void luaK_checkstack (FuncState *fs, int n);
5854LUAI_FUNC int luaK_stringK (FuncState *fs, TString *s);
59LUAI_FUNC int luaK_intK (FuncState *fs, lua_Integer n);
55LUAI_FUNC int luaK_numberK (FuncState *fs, lua_Number r);
6056LUAI_FUNC void luaK_dischargevars (FuncState *fs, expdesc *e);
6157LUAI_FUNC int luaK_exp2anyreg (FuncState *fs, expdesc *e);
6258LUAI_FUNC void luaK_exp2anyregup (FuncState *fs, expdesc *e);
trunk/3rdparty/lua/src/lcorolib.c
r242959r242960
11/*
2** $Id: lcorolib.c,v 1.9 2014/11/02 19:19:04 roberto Exp $
2** $Id: lcorolib.c,v 1.5.1.1 2013/04/12 18:48:47 roberto Exp $
33** Coroutine Library
44** See Copyright Notice in lua.h
55*/
66
7#define lcorolib_c
8#define LUA_LIB
97
10#include "lprefix.h"
8#include <stdlib.h>
119
1210
13#include <stdlib.h>
11#define lcorolib_c
12#define LUA_LIB
1413
1514#include "lua.h"
1615
r242959r242960
1817#include "lualib.h"
1918
2019
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
2820static int auxresume (lua_State *L, lua_State *co, int narg) {
2921  int status;
3022  if (!lua_checkstack(co, narg)) {
r242959r242960
5547
5648
5749static int luaB_coresume (lua_State *L) {
58  lua_State *co = getco(L);
50  lua_State *co = lua_tothread(L, 1);
5951  int r;
52  luaL_argcheck(L, co, 1, "coroutine expected");
6053  r = auxresume(L, co, lua_gettop(L) - 1);
6154  if (r < 0) {
6255    lua_pushboolean(L, 0);
r242959r242960
6659  else {
6760    lua_pushboolean(L, 1);
6861    lua_insert(L, -(r + 1));
69    return r + 1;  /* return true + 'resume' returns */
62    return r + 1;  /* return true + `resume' returns */
7063  }
7164}
7265
r242959r242960
109102
110103
111104static int luaB_costatus (lua_State *L) {
112  lua_State *co = getco(L);
105  lua_State *co = lua_tothread(L, 1);
106  luaL_argcheck(L, co, 1, "coroutine expected");
113107  if (L == co) lua_pushliteral(L, "running");
114108  else {
115109    switch (lua_status(co)) {
r242959r242960
135129}
136130
137131
138static int luaB_yieldable (lua_State *L) {
139  lua_pushboolean(L, lua_isyieldable(L));
140  return 1;
141}
142
143
144132static int luaB_corunning (lua_State *L) {
145133  int ismain = lua_pushthread(L);
146134  lua_pushboolean(L, ismain);
r242959r242960
155143  {"status", luaB_costatus},
156144  {"wrap", luaB_cowrap},
157145  {"yield", luaB_yield},
158  {"isyieldable", luaB_yieldable},
159146  {NULL, NULL}
160147};
161148
trunk/3rdparty/lua/src/lctype.c
r242959r242960
11/*
2** $Id: lctype.c,v 1.12 2014/11/02 19:19:04 roberto Exp $
2** $Id: lctype.c,v 1.11.1.1 2013/04/12 18:48:47 roberto Exp $
33** 'ctype' functions for Lua
44** See Copyright Notice in lua.h
55*/
r242959r242960
77#define lctype_c
88#define LUA_CORE
99
10#include "lprefix.h"
11
12
1310#include "lctype.h"
1411
1512#if !LUA_USE_CTYPE   /* { */
trunk/3rdparty/lua/src/lctype.h
r242959r242960
11/*
2** $Id: lctype.h,v 1.12 2011/07/15 12:50:29 roberto Exp $
2** $Id: lctype.h,v 1.12.1.1 2013/04/12 18:48:47 roberto Exp $
33** 'ctype' functions for Lua
44** See Copyright Notice in lua.h
55*/
trunk/3rdparty/lua/src/ldblib.c
r242959r242960
11/*
2** $Id: ldblib.c,v 1.148 2015/01/02 12:52:22 roberto Exp $
2** $Id: ldblib.c,v 1.132.1.1 2013/04/12 18:48:47 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
97
10#include "lprefix.h"
11
12
138#include <stdio.h>
149#include <stdlib.h>
1510#include <string.h>
1611
12#define ldblib_c
13#define LUA_LIB
14
1715#include "lua.h"
1816
1917#include "lauxlib.h"
2018#include "lualib.h"
2119
2220
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;
21#define HOOKKEY      "_HKEY"
2822
2923
24
3025static int db_getregistry (lua_State *L) {
3126  lua_pushvalue(L, LUA_REGISTRYINDEX);
3227  return 1;
r242959r242960
6257
6358
6459static 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");
6562  luaL_checktype(L, 1, LUA_TUSERDATA);
66  luaL_checkany(L, 2);
63  if (!lua_isnoneornil(L, 2))
64    luaL_checktype(L, 2, LUA_TTABLE);
6765  lua_settop(L, 2);
6866  lua_setuservalue(L, 1);
6967  return 1;
7068}
7169
7270
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*/
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
7989static lua_State *getthread (lua_State *L, int *arg) {
8090  if (lua_isthread(L, 1)) {
8191    *arg = 1;
r242959r242960
8393  }
8494  else {
8595    *arg = 0;
86    return L;  /* function will operate over current thread */
96    return L;
8797  }
8898}
8999
90100
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*/
119101static void treatstackoption (lua_State *L, lua_State *L1, const char *fname) {
120  if (L == L1)
121    lua_rotate(L, -2, 1);  /* exchange object and table */
102  if (L == L1) {
103    lua_pushvalue(L, -2);
104    lua_remove(L, -3);
105  }
122106  else
123    lua_xmove(L1, L, 1);  /* move object to the "main" stack */
124  lua_setfield(L, -2, fname);  /* put object into table */
107    lua_xmove(L1, L, 1);
108  lua_setfield(L, -2, fname);
125109}
126110
127111
128/*
129** Calls 'lua_getinfo' and collects all results in a new table.
130*/
131112static int db_getinfo (lua_State *L) {
132113  lua_Debug ar;
133114  int arg;
134115  lua_State *L1 = getthread(L, &arg);
135116  const char *options = luaL_optstring(L, arg+2, "flnStu");
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)) {
117  if (lua_isnumber(L, arg+1)) {
118    if (!lua_getstack(L1, (int)lua_tointeger(L, arg+1), &ar)) {
143119      lua_pushnil(L);  /* level out of range */
144120      return 1;
145121    }
146122  }
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");
147131  if (!lua_getinfo(L1, options, &ar))
148132    return luaL_argerror(L, arg+2, "invalid option");
149  lua_newtable(L);  /* table to collect results */
133  lua_createtable(L, 0, 2);
150134  if (strchr(options, 'S')) {
151135    settabss(L, "source", ar.source);
152136    settabss(L, "short_src", ar.short_src);
r242959r242960
180164  lua_State *L1 = getthread(L, &arg);
181165  lua_Debug ar;
182166  const char *name;
183  int nvar = (int)luaL_checkinteger(L, arg + 2);  /* local-variable index */
167  int nvar = luaL_checkint(L, arg+2);  /* local-variable index */
184168  if (lua_isfunction(L, arg + 1)) {  /* function argument? */
185169    lua_pushvalue(L, arg + 1);  /* push function */
186170    lua_pushstring(L, lua_getlocal(L, NULL, nvar));  /* push local name */
187    return 1;  /* return only name (there is no value) */
171    return 1;
188172  }
189173  else {  /* stack-level argument */
190    int level = (int)luaL_checkinteger(L, arg + 1);
191    if (!lua_getstack(L1, level, &ar))  /* out of range? */
174    if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar))  /* out of range? */
192175      return luaL_argerror(L, arg+1, "level out of range");
193176    name = lua_getlocal(L1, &ar, nvar);
194177    if (name) {
195      lua_xmove(L1, L, 1);  /* move local value */
178      lua_xmove(L1, L, 1);  /* push local value */
196179      lua_pushstring(L, name);  /* push name */
197      lua_rotate(L, -2, 1);  /* re-order */
180      lua_pushvalue(L, -2);  /* re-order */
198181      return 2;
199182    }
200183    else {
r242959r242960
207190
208191static int db_setlocal (lua_State *L) {
209192  int arg;
210  const char *name;
211193  lua_State *L1 = getthread(L, &arg);
212194  lua_Debug ar;
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? */
195  if (!lua_getstack(L1, luaL_checkint(L, arg+1), &ar))  /* out of range? */
216196    return luaL_argerror(L, arg+1, "level out of range");
217197  luaL_checkany(L, arg+3);
218198  lua_settop(L, arg+3);
219199  lua_xmove(L, L1, 1);
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);
200  lua_pushstring(L, lua_setlocal(L1, &ar, luaL_checkint(L, arg+2)));
224201  return 1;
225202}
226203
227204
228/*
229** get (if 'get' is true) or set an upvalue from a closure
230*/
231205static int auxupvalue (lua_State *L, int get) {
232206  const char *name;
233  int n = (int)luaL_checkinteger(L, 2);  /* upvalue index */
234  luaL_checktype(L, 1, LUA_TFUNCTION);  /* closure */
207  int n = luaL_checkint(L, 2);
208  luaL_checktype(L, 1, LUA_TFUNCTION);
235209  name = get ? lua_getupvalue(L, 1, n) : lua_setupvalue(L, 1, n);
236210  if (name == NULL) return 0;
237211  lua_pushstring(L, name);
238  lua_insert(L, -(get+1));  /* no-op if get is false */
212  lua_insert(L, -(get+1));
239213  return get + 1;
240214}
241215
r242959r242960
251225}
252226
253227
254/*
255** Check whether a given upvalue from a given closure exists and
256** returns its index
257*/
258228static int checkupval (lua_State *L, int argf, int argnup) {
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");
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");
263235  return nup;
264236}
265237
r242959r242960
281253}
282254
283255
284/*
285** Call hook function registered at hook table for the current
286** thread (if there is one)
287*/
256#define gethooktable(L)   luaL_getsubtable(L, LUA_REGISTRYINDEX, HOOKKEY)
257
258
288259static void hookf (lua_State *L, lua_Debug *ar) {
289260  static const char *const hooknames[] =
290261    {"call", "return", "line", "count", "tail call"};
291  lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
262  gethooktable(L);
292263  lua_pushthread(L);
293  if (lua_rawget(L, -2) == LUA_TFUNCTION) {  /* is there a hook function? */
294    lua_pushstring(L, hooknames[(int)ar->event]);  /* push event name */
264  lua_rawget(L, -2);
265  if (lua_isfunction(L, -1)) {
266    lua_pushstring(L, hooknames[(int)ar->event]);
295267    if (ar->currentline >= 0)
296      lua_pushinteger(L, ar->currentline);  /* push current line */
268      lua_pushinteger(L, ar->currentline);
297269    else lua_pushnil(L);
298270    lua_assert(lua_getinfo(L, "lS", ar));
299    lua_call(L, 2, 0);  /* call hook function */
271    lua_call(L, 2, 0);
300272  }
301273}
302274
303275
304/*
305** Convert a string mask (for 'sethook') into a bit mask
306*/
307276static int makemask (const char *smask, int count) {
308277  int mask = 0;
309278  if (strchr(smask, 'c')) mask |= LUA_MASKCALL;
r242959r242960
314283}
315284
316285
317/*
318** Convert a bit mask (for 'gethook') into a string mask
319*/
320286static char *unmakemask (int mask, char *smask) {
321287  int i = 0;
322288  if (mask & LUA_MASKCALL) smask[i++] = 'c';
r242959r242960
331297  int arg, mask, count;
332298  lua_Hook func;
333299  lua_State *L1 = getthread(L, &arg);
334  if (lua_isnoneornil(L, arg+1)) {  /* no hook? */
300  if (lua_isnoneornil(L, arg+1)) {
335301    lua_settop(L, arg+1);
336302    func = NULL; mask = 0; count = 0;  /* turn off hooks */
337303  }
338304  else {
339305    const char *smask = luaL_checkstring(L, arg+2);
340306    luaL_checktype(L, arg+1, LUA_TFUNCTION);
341    count = (int)luaL_optinteger(L, arg + 3, 0);
307    count = luaL_optint(L, arg+3, 0);
342308    func = hookf; mask = makemask(smask, count);
343309  }
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 */
310  if (gethooktable(L) == 0) {  /* creating hook table? */
348311    lua_pushstring(L, "k");
349312    lua_setfield(L, -2, "__mode");  /** hooktable.__mode = "k" */
350313    lua_pushvalue(L, -1);
351314    lua_setmetatable(L, -2);  /* setmetatable(hooktable) = hooktable */
352315  }
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);
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 */
357320  return 0;
358321}
359322
r242959r242960
364327  char buff[5];
365328  int mask = lua_gethookmask(L1);
366329  lua_Hook hook = lua_gethook(L1);
367  if (hook == NULL)  /* no hook? */
368    lua_pushnil(L);
369  else if (hook != hookf)  /* external hook? */
330  if (hook != NULL && hook != hookf)  /* external hook? */
370331    lua_pushliteral(L, "external hook");
371  else {  /* hook table must exist */
372    lua_rawgetp(L, LUA_REGISTRYINDEX, &HOOKKEY);
332  else {
333    gethooktable(L);
373334    lua_pushthread(L1); lua_xmove(L1, L, 1);
374    lua_rawget(L, -2);   /* 1st result = hooktable[L1] */
335    lua_rawget(L, -2);   /* get hook */
375336    lua_remove(L, -2);  /* remove hook table */
376337  }
377  lua_pushstring(L, unmakemask(mask, buff));  /* 2nd result = mask */
378  lua_pushinteger(L, lua_gethookcount(L1));  /* 3rd result = count */
338  lua_pushstring(L, unmakemask(mask, buff));
339  lua_pushinteger(L, lua_gethookcount(L1));
379340  return 3;
380341}
381342
r242959r242960
383344static int db_debug (lua_State *L) {
384345  for (;;) {
385346    char buffer[250];
386    lua_writestringerror("%s", "lua_debug> ");
347    luai_writestringerror("%s", "lua_debug> ");
387348    if (fgets(buffer, sizeof(buffer), stdin) == 0 ||
388349        strcmp(buffer, "cont\n") == 0)
389350      return 0;
390351    if (luaL_loadbuffer(L, buffer, strlen(buffer), "=(debug command)") ||
391352        lua_pcall(L, 0, 0, 0))
392      lua_writestringerror("%s\n", lua_tostring(L, -1));
353      luai_writestringerror("%s\n", lua_tostring(L, -1));
393354    lua_settop(L, 0);  /* remove eventual returns */
394355  }
395356}
r242959r242960
402363  if (msg == NULL && !lua_isnoneornil(L, arg + 1))  /* non-string 'msg'? */
403364    lua_pushvalue(L, arg + 1);  /* return it untouched */
404365  else {
405    int level = (int)luaL_optinteger(L, arg + 2, (L == L1) ? 1 : 0);
366    int level = luaL_optint(L, arg + 2, (L == L1) ? 1 : 0);
406367    luaL_traceback(L, L1, msg, level);
407368  }
408369  return 1;
trunk/3rdparty/lua/src/ldebug.c
r242959r242960
11/*
2** $Id: ldebug.c,v 2.110 2015/01/02 12:52:22 roberto Exp $
2** $Id: ldebug.c,v 2.90.1.3 2013/05/16 16:04:15 roberto Exp $
33** Debug Interface
44** See Copyright Notice in lua.h
55*/
66
7#define ldebug_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
138#include <stdarg.h>
149#include <stddef.h>
1510#include <string.h>
1611
12
13#define ldebug_c
14#define LUA_CORE
15
1716#include "lua.h"
1817
1918#include "lapi.h"
r242959r242960
5150/*
5251** this function can be called asynchronous (e.g. during a signal)
5352*/
54LUA_API void lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
53LUA_API int lua_sethook (lua_State *L, lua_Hook func, int mask, int count) {
5554  if (func == NULL || mask == 0) {  /* turn off hooks? */
5655    mask = 0;
5756    func = NULL;
r242959r242960
6261  L->basehookcount = count;
6362  resethookcount(L);
6463  L->hookmask = cast_byte(mask);
64  return 1;
6565}
6666
6767
r242959r242960
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 */
173  }
172  L->top--;  /* pop value */
174173  lua_unlock(L);
175174  return name;
176175}
r242959r242960
273272  if (*what == '>') {
274273    ci = NULL;
275274    func = L->top - 1;
276    api_check(ttisfunction(func), "function expected");
275    api_check(L, ttisfunction(func), "function expected");
277276    what++;  /* skip the '>' */
278277    L->top--;  /* pop function */
279278  }
r242959r242960
367366      case OP_JMP: {
368367        int b = GETARG_sBx(i);
369368        int dest = pc + 1 + b;
370        /* jump is forward and do not skip 'lastpc'? */
369        /* jump is forward and do not skip `lastpc'? */
371370        if (pc < dest && dest <= lastpc) {
372371          if (dest > jmptarget)
373372            jmptarget = dest;  /* update 'jmptarget' */
374373        }
375374        break;
376375      }
376      case OP_TEST: {
377        if (reg == a)  /* jumped code can change 'a' */
378          setreg = filterpc(pc, jmptarget);
379        break;
380      }
377381      default:
378382        if (testAMode(op) && reg == a)  /* any instruction that set A */
379383          setreg = filterpc(pc, jmptarget);
r242959r242960
439443
440444
441445static const char *getfuncname (lua_State *L, CallInfo *ci, const char **name) {
442  TMS tm = (TMS)0;  /* to avoid warnings */
446  TMS tm;
443447  Proto *p = ci_func(ci)->p;  /* calling function */
444448  int pc = currentpc(ci);  /* calling instruction index */
445449  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 */
r242959r242960
456456       return "for iterator";
457457    }
458458    /* all other instructions can call only through metamethods */
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    }
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;
472471    case OP_UNM: tm = TM_UNM; break;
473    case OP_BNOT: tm = TM_BNOT; break;
474472    case OP_LEN: tm = TM_LEN; break;
475    case OP_CONCAT: tm = TM_CONCAT; break;
476    case OP_EQ: tm = TM_EQ; break;
477473    case OP_LT: tm = TM_LT; break;
478474    case OP_LE: tm = TM_LE; break;
479    default: lua_assert(0);  /* other instructions cannot call a function */
475    case OP_CONCAT: tm = TM_CONCAT; break;
476    default:
477      return NULL;  /* else no useful name can be found */
480478  }
481479  *name = getstr(G(L)->tmname[tm]);
482480  return "metamethod";
r242959r242960
487485
488486
489487/*
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.
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)
493490*/
494491static int isinstack (CallInfo *ci, const TValue *o) {
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);
492  StkId p;
493  for (p = ci->u.l.base; p < ci->top; p++)
494    if (o == p) return 1;
495  return 0;
497496}
498497
499498
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*/
505499static const char *getupvalname (CallInfo *ci, const TValue *o,
506500                                 const char **name) {
507501  LClosure *c = ci_func(ci);
r242959r242960
516510}
517511
518512
519static const char *varinfo (lua_State *L, const TValue *o) {
520  const char *name = NULL;  /* to avoid warnings */
513l_noret luaG_typeerror (lua_State *L, const TValue *o, const char *op) {
521514  CallInfo *ci = L->ci;
515  const char *name = NULL;
516  const char *t = objtypename(o);
522517  const char *kind = NULL;
523518  if (isLua(ci)) {
524519    kind = getupvalname(ci, o, &name);  /* check whether 'o' is an upvalue */
r242959r242960
526521      kind = getobjname(ci_func(ci)->p, currentpc(ci),
527522                        cast_int(o - ci->u.l.base), &name);
528523  }
529  return (kind) ? luaO_pushfstring(L, " (%s '%s')", kind, name) : "";
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);
530529}
531530
532531
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;
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));
541535  luaG_typeerror(L, p1, "concatenate");
542536}
543537
544538
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);
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");
551544}
552545
553546
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
565547l_noret luaG_ordererror (lua_State *L, const TValue *p1, const TValue *p2) {
566548  const char *t1 = objtypename(p1);
567549  const char *t2 = objtypename(p2);
r242959r242960
591573l_noret luaG_errormsg (lua_State *L) {
592574  if (L->errfunc != 0) {  /* is there an error handling function? */
593575    StkId errfunc = restorestack(L, L->errfunc);
576    if (!ttisfunction(errfunc)) luaD_throw(L, LUA_ERRERR);
594577    setobjs2s(L, L->top, L->top - 1);  /* move argument */
595578    setobjs2s(L, L->top - 1, errfunc);  /* push function */
596    L->top++;  /* assume EXTRA_STACK */
579    L->top++;
597580    luaD_call(L, L->top - 2, 1, 0);  /* call it */
598581  }
599582  luaD_throw(L, LUA_ERRRUN);
r242959r242960
608591  luaG_errormsg(L);
609592}
610593
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
r242959r242960
11/*
2** $Id: ldebug.h,v 2.12 2014/11/10 14:46:05 roberto Exp $
2** $Id: ldebug.h,v 2.7.1.1 2013/04/12 18:48:47 roberto Exp $
33** Auxiliary functions from Debug Interface module
44** See Copyright Notice in lua.h
55*/
r242959r242960
1313
1414#define pcRel(pc, p)   (cast(int, (pc) - (p)->code) - 1)
1515
16#define getfuncline(f,pc)   (((f)->lineinfo) ? (f)->lineinfo[pc] : -1)
16#define getfuncline(f,pc)   (((f)->lineinfo) ? (f)->lineinfo[pc] : 0)
1717
1818#define resethookcount(L)   (L->hookcount = L->basehookcount)
1919
r242959r242960
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, 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,
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,
3228                                                 const TValue *p2);
3329LUAI_FUNC l_noret luaG_ordererror (lua_State *L, const TValue *p1,
3430                                                 const TValue *p2);
3531LUAI_FUNC l_noret luaG_runerror (lua_State *L, const char *fmt, ...);
3632LUAI_FUNC l_noret luaG_errormsg (lua_State *L);
37LUAI_FUNC void luaG_traceexec (lua_State *L);
3833
39
4034#endif
trunk/3rdparty/lua/src/ldo.c
r242959r242960
11/*
2** $Id: ldo.c,v 2.135 2014/11/11 17:13:39 roberto Exp $
2** $Id: ldo.c,v 2.108.1.3 2013/11/08 18:22:50 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
97
10#include "lprefix.h"
11
12
138#include <setjmp.h>
149#include <stdlib.h>
1510#include <string.h>
1611
12#define ldo_c
13#define LUA_CORE
14
1715#include "lua.h"
1816
1917#include "lapi.h"
r242959r242960
3533
3634
3735
38#define errorstatus(s)   ((s) > LUA_YIELD)
3936
40
4137/*
4238** {======================================================
4339** Error-recovery functions
r242959r242960
5046** C++ code, with _longjmp/_setjmp when asked to use them, and with
5147** longjmp/setjmp otherwise.
5248*/
53#if !defined(LUAI_THROW)            /* { */
49#if !defined(LUAI_THROW)
5450
55#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)   /* { */
56
51#if defined(__cplusplus) && !defined(LUA_USE_LONGJMP)
5752/* C++ exceptions */
5853#define LUAI_THROW(L,c)      throw(c)
5954#define LUAI_TRY(L,c,a) \
6055   try { a } catch(...) { if ((c)->status == 0) (c)->status = -1; }
6156#define luai_jmpbuf      int  /* dummy variable */
6257
63#elif defined(LUA_USE_POSIX)            /* }{ */
64
65/* in POSIX, try _longjmp/_setjmp (more efficient) */
58#elif defined(LUA_USE_ULONGJMP)
59/* in Unix, try _longjmp/_setjmp (more efficient) */
6660#define LUAI_THROW(L,c)      _longjmp((c)->b, 1)
6761#define LUAI_TRY(L,c,a)      if (_setjmp((c)->b) == 0) { a }
6862#define luai_jmpbuf      jmp_buf
6963
70#else                     /* }{ */
71
72/* ISO C handling with long jumps */
64#else
65/* default handling with long jumps */
7366#define LUAI_THROW(L,c)      longjmp((c)->b, 1)
7467#define LUAI_TRY(L,c,a)      if (setjmp((c)->b) == 0) { a }
7568#define luai_jmpbuf      jmp_buf
7669
77#endif                     /* } */
70#endif
7871
79#endif                     /* } */
72#endif
8073
8174
8275
r242959r242960
113106    LUAI_THROW(L, L->errorJmp);  /* jump to it */
114107  }
115108  else {  /* thread has no error handler */
116    global_State *g = G(L);
117109    L->status = cast_byte(errcode);  /* mark it as dead */
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 */
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 */
121113    }
122114    else {  /* no handler at all; abort */
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 */
115      if (G(L)->panic) {  /* panic function? */
127116        lua_unlock(L);
128        g->panic(L);  /* call panic function (last chance to jump out) */
117        G(L)->panic(L);  /* call it (last chance to jump out) */
129118      }
130119      abort();
131120    }
r242959r242960
152141
153142static void correctstack (lua_State *L, TValue *oldstack) {
154143  CallInfo *ci;
155  UpVal *up;
144  GCObject *up;
156145  L->top = (L->top - oldstack) + L->stack;
157  for (up = L->openupval; up != NULL; up = up->u.open.next)
158    up->v = (up->v - oldstack) + L->stack;
146  for (up = L->openupval; up != NULL; up = up->gch.next)
147    gco2uv(up)->v = (gco2uv(up)->v - oldstack) + L->stack;
159148  for (ci = L->ci; ci != NULL; ci = ci->previous) {
160149    ci->top = (ci->top - oldstack) + L->stack;
161150    ci->func = (ci->func - oldstack) + L->stack;
r242959r242960
217206  int inuse = stackinuse(L);
218207  int goodsize = inuse + (inuse / 8) + 2*EXTRA_STACK;
219208  if (goodsize > LUAI_MAXSTACK) goodsize = LUAI_MAXSTACK;
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? */
209  if (inuse > LUAI_MAXSTACK ||  /* handling stack overflow? */
225210      goodsize >= L->stacksize)  /* would grow instead of shrink? */
226211    condmovestack(L);  /* don't change stack (change only for debugging) */
227212  else
r242959r242960
286271}
287272
288273
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) {
274static StkId tryfuncTM (lua_State *L, StkId func) {
295275  const TValue *tm = luaT_gettmbyobj(L, func, TM_CALL);
296276  StkId p;
277  ptrdiff_t funcr = savestack(L, func);
297278  if (!ttisfunction(tm))
298279    luaG_typeerror(L, func, "call");
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 */
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 */
303284  setobj2s(L, func, tm);  /* tag method is the new function to be called */
285  return func;
304286}
305287
306288
r242959r242960
370352      return 0;
371353    }
372354    default: {  /* not a function */
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 */
355      func = tryfuncTM(L, func);  /* retry with 'function' tag method */
376356      return luaD_precall(L, func, nresults);  /* now it must be a function */
377357    }
378358  }
r242959r242960
425405}
426406
427407
428/*
429** Completes the execution of an interrupted C function, calling its
430** continuation function.
431*/
432static void finishCcall (lua_State *L, int status) {
408static void finishCcall (lua_State *L) {
433409  CallInfo *ci = L->ci;
434410  int n;
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);
411  lua_assert(ci->u.c.k != NULL);  /* must have a continuation */
412  lua_assert(L->nny == 0);
439413  if (ci->callstatus & CIST_YPCALL) {  /* was inside a pcall? */
440414    ci->callstatus &= ~CIST_YPCALL;  /* finish 'lua_pcall' */
441415    L->errfunc = ci->u.c.old_errfunc;
442416  }
443  /* finish 'lua_callk'/'lua_pcall'; CIST_YPCALL and 'errfunc' already
444     handled */
417  /* finish 'lua_callk'/'lua_pcall' */
445418  adjustresults(L, ci->nresults);
446419  /* 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;
447424  lua_unlock(L);
448  n = (*ci->u.c.k)(L, status, ci->u.c.ctx);
425  n = (*ci->u.c.k)(L);
449426  lua_lock(L);
450427  api_checknelems(L, n);
451428  /* finish 'luaD_precall' */
r242959r242960
453430}
454431
455432
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*/
464433static void unroll (lua_State *L, void *ud) {
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 */
434  UNUSED(ud);
435  for (;;) {
436    if (L->ci == &L->base_ci)  /* stack is empty? */
437      return;  /* coroutine finished normally */
468438    if (!isLua(L->ci))  /* C function? */
469      finishCcall(L, LUA_YIELD);  /* complete its execution */
439      finishCcall(L);
470440    else {  /* Lua function */
471441      luaV_finishOp(L);  /* finish interrupted instruction */
472442      luaV_execute(L);  /* execute down to higher C 'boundary' */
r242959r242960
476446
477447
478448/*
479** Try to find a suspended protected call (a "recover point") for the
480** given thread.
449** check whether thread has a suspended protected call
481450*/
482451static CallInfo *findpcall (lua_State *L) {
483452  CallInfo *ci;
r242959r242960
489458}
490459
491460
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*/
497461static int recover (lua_State *L, int status) {
498462  StkId oldtop;
499463  CallInfo *ci = findpcall(L);
r242959r242960
503467  luaF_close(L, oldtop);
504468  seterrorobj(L, status, oldtop);
505469  L->ci = ci;
506  L->allowhook = getoah(ci->callstatus);  /* restore original 'allowhook' */
470  L->allowhook = ci->u.c.old_allowhook;
507471  L->nny = 0;  /* should be zero to be yieldable */
508472  luaD_shrinkstack(L);
509473  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) */
510476  return 1;  /* continue running the coroutine */
511477}
512478
r242959r242960
525491
526492
527493/*
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.
494** do the work for 'lua_resume' in protected mode
533495*/
534496static void resume (lua_State *L, void *ud) {
535497  int nCcalls = L->nCcalls;
r242959r242960
547509  else if (L->status != LUA_YIELD)
548510    resume_error(L, "cannot resume dead coroutine", firstArg);
549511  else {  /* resuming from previous yield */
550    L->status = LUA_OK;  /* mark that it is running (again) */
512    L->status = LUA_OK;
551513    ci->func = restorestack(L, ci->extra);
552514    if (isLua(ci))  /* yielded inside a hook? */
553515      luaV_execute(L);  /* just continue running Lua code */
554516    else {  /* 'common' yield */
555      if (ci->u.c.k != NULL) {  /* does it have a continuation function? */
517      if (ci->u.c.k != NULL) {  /* does it have a continuation? */
556518        int n;
519        ci->u.c.status = LUA_YIELD;  /* 'default' status */
520        ci->callstatus |= CIST_YIELDED;
557521        lua_unlock(L);
558        n = (*ci->u.c.k)(L, LUA_YIELD, ci->u.c.ctx); /* call continuation */
522        n = (*ci->u.c.k)(L); /* call continuation */
559523        lua_lock(L);
560524        api_checknelems(L, n);
561525        firstArg = L->top - n;  /* yield results come from continuation */
562526      }
563527      luaD_poscall(L, firstArg);  /* finish 'luaD_precall' */
564528    }
565    unroll(L, NULL);  /* run continuation */
529    unroll(L, NULL);
566530  }
567531  lua_assert(nCcalls == L->nCcalls);
568532}
r242959r242960
570534
571535LUA_API int lua_resume (lua_State *L, lua_State *from, int nargs) {
572536  int status;
573  int oldnny = L->nny;  /* save "number of non-yieldable" calls */
537  int oldnny = L->nny;  /* save 'nny' */
574538  lua_lock(L);
575539  luai_userstateresume(L, nargs);
576540  L->nCcalls = (from) ? from->nCcalls + 1 : 1;
r242959r242960
579543  status = luaD_rawrunprotected(L, resume, L->top - nargs);
580544  if (status == -1)  /* error calling 'lua_resume'? */
581545    status = LUA_ERRRUN;
582  else {  /* continue running after recoverable errors */
583    while (errorstatus(status) && recover(L, status)) {
584      /* unroll continuation */
585      status = luaD_rawrunprotected(L, unroll, &status);
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      }
586556    }
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 */
557    lua_assert(status == L->status);
593558  }
594559  L->nny = oldnny;  /* restore 'nny' */
595560  L->nCcalls--;
r242959r242960
599564}
600565
601566
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) {
567LUA_API int lua_yieldk (lua_State *L, int nresults, int ctx, lua_CFunction k) {
609568  CallInfo *ci = L->ci;
610569  luai_userstateyield(L, nresults);
611570  lua_lock(L);
r242959r242960
619578  L->status = LUA_YIELD;
620579  ci->extra = savestack(L, ci->func);  /* save current 'func' */
621580  if (isLua(ci)) {  /* inside a hook? */
622    api_check(k == NULL, "hooks cannot continue after yielding");
581    api_check(L, k == NULL, "hooks cannot continue after yielding");
623582  }
624583  else {
625584    if ((ci->u.c.k = k) != NULL)  /* is there a continuation? */
r242959r242960
660619/*
661620** Execute a protected parser.
662621*/
663struct SParser {  /* data to 'f_parser' */
622struct SParser {  /* data to `f_parser' */
664623  ZIO *z;
665624  Mbuffer buff;  /* dynamic structure used by the scanner */
666625  Dyndata dyd;  /* dynamic structures used by the parser */
r242959r242960
672631static void checkmode (lua_State *L, const char *mode, const char *x) {
673632  if (mode && strchr(mode, x[0]) == NULL) {
674633    luaO_pushfstring(L,
675       "attempt to load a %s chunk (mode is '%s')", x, mode);
634       "attempt to load a %s chunk (mode is " LUA_QS ")", x, mode);
676635    luaD_throw(L, LUA_ERRSYNTAX);
677636  }
678637}
679638
680639
681640static void f_parser (lua_State *L, void *ud) {
682  LClosure *cl;
641  int i;
642  Closure *cl;
683643  struct SParser *p = cast(struct SParser *, ud);
684644  int c = zgetc(p->z);  /* read first character */
685645  if (c == LUA_SIGNATURE[0]) {
r242959r242960
690650    checkmode(L, p->mode, "text");
691651    cl = luaY_parser(L, p->z, &p->buff, &p->dyd, p->name, c);
692652  }
693  lua_assert(cl->nupvalues == cl->p->sizeupvalues);
694  luaF_initupvals(L, cl);
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  }
695659}
696660
697661
trunk/3rdparty/lua/src/ldo.h
r242959r242960
11/*
2** $Id: ldo.h,v 2.21 2014/10/25 11:50:46 roberto Exp $
2** $Id: ldo.h,v 2.20.1.1 2013/04/12 18:48:47 roberto Exp $
33** Stack and Call structure of Lua
44** See Copyright Notice in lua.h
55*/
r242959r242960
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
r242959r242960
11/*
2** $Id: ldump.c,v 2.34 2014/11/02 19:19:04 roberto Exp $
2** $Id: ldump.c,v 2.17.1.1 2013/04/12 18:48:47 roberto Exp $
33** save precompiled Lua chunks
44** See Copyright Notice in lua.h
55*/
66
7#include <stddef.h>
8
79#define ldump_c
810#define LUA_CORE
911
10#include "lprefix.h"
11
12
13#include <stddef.h>
14
1512#include "lua.h"
1613
1714#include "lobject.h"
1815#include "lstate.h"
1916#include "lundump.h"
2017
21
2218typedef struct {
23  lua_State *L;
24  lua_Writer writer;
25  void *data;
26  int strip;
27  int status;
19 lua_State* L;
20 lua_Writer writer;
21 void* data;
22 int strip;
23 int status;
2824} DumpState;
2925
26#define DumpMem(b,n,size,D)   DumpBlock(b,(n)*(size),D)
27#define DumpVar(x,D)      DumpMem(&x,1,sizeof(x),D)
3028
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  }
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 }
4637}
4738
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);
39static void DumpChar(int y, DumpState* D)
40{
41 char x=(char)y;
42 DumpVar(x,D);
5543}
5644
57
58static void DumpInt (int x, DumpState *D) {
59  DumpVar(x, D);
45static void DumpInt(int x, DumpState* D)
46{
47 DumpVar(x,D);
6048}
6149
62
63static void DumpNumber (lua_Number x, DumpState *D) {
64  DumpVar(x, D);
50static void DumpNumber(lua_Number x, DumpState* D)
51{
52 DumpVar(x,D);
6553}
6654
67
68static void DumpInteger (lua_Integer x, DumpState *D) {
69  DumpVar(x, D);
55static void DumpVector(const void* b, int n, size_t size, DumpState* D)
56{
57 DumpInt(n,D);
58 DumpMem(b,n,size,D);
7059}
7160
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  }
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 }
8674}
8775
76#define DumpCode(f,D)    DumpVector(f->code,f->sizecode,sizeof(Instruction),D)
8877
89static void DumpCode (const Proto *f, DumpState *D) {
90  DumpInt(f->sizecode, D);
91  DumpVector(f->code, f->sizecode, D);
92}
78static void DumpFunction(const Proto* f, DumpState* D);
9379
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    }
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);
123102  }
103 }
104 n=f->sizep;
105 DumpInt(n,D);
106 for (i=0; i<n; i++) DumpFunction(f->p[i],D);
124107}
125108
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);
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 }
133118}
134119
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  }
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);
143137}
144138
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);
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);
162150}
163151
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);
152static void DumpHeader(DumpState* D)
153{
154 lu_byte h[LUAC_HEADERSIZE];
155 luaU_header(h);
156 DumpBlock(h,LUAC_HEADERSIZE,D);
180157}
181158
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
198159/*
199160** dump Lua function as precompiled chunk
200161*/
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;
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;
213173}
214
trunk/3rdparty/lua/src/lfunc.c
r242959r242960
11/*
2** $Id: lfunc.c,v 2.45 2014/11/02 19:19:04 roberto Exp $
2** $Id: lfunc.c,v 2.30.1.1 2013/04/12 18:48:47 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
710#define lfunc_c
811#define LUA_CORE
912
10#include "lprefix.h"
11
12
13#include <stddef.h>
14
1513#include "lua.h"
1614
1715#include "lfunc.h"
r242959r242960
2220
2321
2422
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);
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);
2926  return c;
3027}
3128
3229
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;
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;
3935  return c;
4036}
4137
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  }
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;
5444}
5545
5646
5747UpVal *luaF_findupval (lua_State *L, StkId level) {
58  UpVal **pp = &L->openupval;
48  global_State *g = G(L);
49  GCObject **pp = &L->openupval;
5950  UpVal *p;
6051  UpVal *uv;
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;
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;
6762  }
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;
63  /* not found: create a new one */
64  uv = &luaC_newobj(L, LUA_TUPVAL, sizeof(UpVal), pp, 0)->uv;
7465  uv->v = level;  /* current value lives in the stack */
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  }
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);
7971  return uv;
8072}
8173
8274
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
8389void luaF_close (lua_State *L, StkId level) {
8490  UpVal *uv;
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 */
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 */
9098    else {
99      unlinkupval(uv);  /* remove upvalue from 'uvhead' list */
91100      setobj(L, &uv->u.value, uv->v);  /* move value to upvalue slot */
92101      uv->v = &uv->u.value;  /* now current value lives here */
93      luaC_upvalbarrier(L, uv);
102      gch(o)->next = g->allgc;  /* link upvalue into 'allgc' list */
103      g->allgc = o;
104      luaC_checkupvalcolor(g, uv);
94105    }
95106  }
96107}
97108
98109
99110Proto *luaF_newproto (lua_State *L) {
100  GCObject *o = luaC_newobj(L, LUA_TPROTO, sizeof(Proto));
101  Proto *f = gco2p(o);
111  Proto *f = &luaC_newobj(L, LUA_TPROTO, sizeof(Proto), NULL, 0)->p;
102112  f->k = NULL;
103113  f->sizek = 0;
104114  f->p = NULL;
r242959r242960
134144
135145
136146/*
137** Look for n-th local variable at line 'line' in function 'func'.
147** Look for n-th local variable at line `line' in function `func'.
138148** Returns NULL if not found.
139149*/
140150const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
trunk/3rdparty/lua/src/lfunc.h
r242959r242960
11/*
2** $Id: lfunc.h,v 2.14 2014/06/19 18:27:20 roberto Exp $
2** $Id: lfunc.h,v 2.8.1.1 2013/04/12 18:48:47 roberto Exp $
33** Auxiliary functions to manipulate prototypes and closures
44** See Copyright Notice in lua.h
55*/
r242959r242960
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
4321LUAI_FUNC Proto *luaF_newproto (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);
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);
4725LUAI_FUNC UpVal *luaF_findupval (lua_State *L, StkId level);
4826LUAI_FUNC void luaF_close (lua_State *L, StkId level);
4927LUAI_FUNC void luaF_freeproto (lua_State *L, Proto *f);
28LUAI_FUNC void luaF_freeupval (lua_State *L, UpVal *uv);
5029LUAI_FUNC const char *luaF_getlocalname (const Proto *func, int local_number,
5130                                         int pc);
5231
trunk/3rdparty/lua/src/lgc.c
r242959r242960
11/*
2** $Id: lgc.c,v 2.201 2014/12/20 13:58:15 roberto Exp $
2** $Id: lgc.c,v 2.140.1.2 2013/04/26 18:22:05 roberto Exp $
33** Garbage Collector
44** See Copyright Notice in lua.h
55*/
66
7#include <string.h>
8
79#define lgc_c
810#define LUA_CORE
911
10#include "lprefix.h"
11
12
13#include <string.h>
14
1512#include "lua.h"
1613
1714#include "ldebug.h"
r242959r242960
2623#include "ltm.h"
2724
2825
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)
3426
3527/*
3628** cost of sweeping one element (the size of a small object divided
r242959r242960
4133/* maximum number of elements to sweep in each single step */
4234#define GCSWEEPMAX   (cast_int((GCSTEPSIZE / GCSWEEPCOST) / 4))
4335
44/* cost of calling one finalizer */
45#define GCFINALIZECOST   GCSWEEPCOST
36/* maximum number of finalizers to call in each GC step */
37#define GCFINALIZENUM   4
4638
4739
4840/*
r242959r242960
6052
6153
6254/*
63** 'makewhite' erases all color bits then sets only the current white
64** bit
55** 'makewhite' erases all color bits plus the old bit and then
56** sets only the current white bit
6557*/
66#define maskcolors   (~(bitmask(BLACKBIT) | WHITEBITS))
58#define maskcolors   (~(bit2mask(BLACKBIT, OLDBIT) | WHITEBITS))
6759#define makewhite(g,x)   \
68 (x->marked = cast_byte((x->marked & maskcolors) | luaC_white(g)))
60 (gch(x)->marked = cast_byte((gch(x)->marked & maskcolors) | luaC_white(g)))
6961
70#define white2gray(x)   resetbits(x->marked, WHITEBITS)
71#define black2gray(x)   resetbit(x->marked, BLACKBIT)
62#define white2gray(x)   resetbits(gch(x)->marked, WHITEBITS)
63#define black2gray(x)   resetbit(gch(x)->marked, BLACKBIT)
7264
7365
74#define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x)))
66#define isfinalized(x)      testbit(gch(x)->marked, FINALIZEDBIT)
7567
7668#define checkdeadkey(n)   lua_assert(!ttisdeadkey(gkey(n)) || ttisnil(gval(n)))
7769
r242959r242960
8375#define markvalue(g,o) { checkconsistency(o); \
8476  if (valiswhite(o)) reallymarkobject(g,gcvalue(o)); }
8577
86#define markobject(g,t) \
87  { if ((t) && iswhite(t)) reallymarkobject(g, obj2gco(t)); }
78#define markobject(g,t) { if ((t) && iswhite(obj2gco(t))) \
79      reallymarkobject(g, obj2gco(t)); }
8880
8981static void reallymarkobject (global_State *g, GCObject *o);
9082
r242959r242960
10395
10496
10597/*
106** link collectable object 'o' into list pointed by 'p'
98** link table 'h' into list pointed by 'p'
10799*/
108#define linkgclist(o,p)   ((o)->gclist = (p), (p) = obj2gco(o))
100#define linktable(h,p)   ((h)->gclist = *(p), *(p) = obj2gco(h))
109101
110102
111103/*
r242959r242960
115107static void removeentry (Node *n) {
116108  lua_assert(ttisnil(gval(n)));
117109  if (valiswhite(gkey(n)))
118    setdeadvalue(wgkey(n));  /* unused and unmarked key; remove it */
110    setdeadvalue(gkey(n));  /* unused and unmarked key; remove it */
119111}
120112
121113
122114/*
123115** tells whether a key or value can be cleared from a weak
124116** table. Non-collectable objects are never removed from weak
125** tables. Strings behave as 'values', so are never removed too. for
117** tables. Strings behave as `values', so are never removed too. for
126118** other objects: if really collected, cannot keep them; for objects
127119** being finalized, keep them in keys, but not in values
128120*/
129121static int iscleared (global_State *g, const TValue *o) {
130122  if (!iscollectable(o)) return 0;
131123  else if (ttisstring(o)) {
132    markobject(g, tsvalue(o));  /* strings are 'values', so are never weak */
124    markobject(g, rawtsvalue(o));  /* strings are `values', so are never weak */
133125    return 0;
134126  }
135127  else return iswhite(gcvalue(o));
r242959r242960
138130
139131/*
140132** barrier that moves collector forward, that is, mark the white 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.)
133** being pointed by a black object.
144134*/
145135void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v) {
146136  global_State *g = G(L);
147137  lua_assert(isblack(o) && iswhite(v) && !isdead(g, v) && !isdead(g, o));
148  if (keepinvariant(g))  /* must keep invariant? */
138  lua_assert(g->gcstate != GCSpause);
139  lua_assert(gch(o)->tt != LUA_TTABLE);
140  if (keepinvariantout(g))  /* must keep invariant? */
149141    reallymarkobject(g, v);  /* restore invariant */
150142  else {  /* sweep phase */
151143    lua_assert(issweepphase(g));
r242959r242960
156148
157149/*
158150** barrier that moves collector backward, that is, mark the black object
159** pointing to a white object as gray again.
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.)
160154*/
161void luaC_barrierback_ (lua_State *L, Table *t) {
155void luaC_barrierback_ (lua_State *L, GCObject *o) {
162156  global_State *g = G(L);
163  lua_assert(isblack(t) && !isdead(g, t));
164  black2gray(t);  /* make table gray (again) */
165  linkgclist(t, g->grayagain);
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;
166161}
167162
168163
169164/*
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.
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.
174171*/
175void luaC_upvalbarrier_ (lua_State *L, UpVal *uv) {
172LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c) {
176173  global_State *g = G(L);
177  GCObject *o = gcvalue(uv->v);
178  lua_assert(!upisopen(uv));  /* ensured by macro luaC_upvalbarrier */
179  if (keepinvariant(g))
180    markobject(g, o);
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  }
181183}
182184
183185
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;
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  }
191204}
192205
193206
194207/*
195208** create a new collectable object (with given type and size) and link
196** it to 'allgc' list.
209** it to '*list'. 'offset' tells how many bytes to allocate before the
210** object itself (used only by states).
197211*/
198GCObject *luaC_newobj (lua_State *L, int tt, size_t sz) {
212GCObject *luaC_newobj (lua_State *L, int tt, size_t sz, GCObject **list,
213                       int offset) {
199214  global_State *g = G(L);
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;
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;
205223  return o;
206224}
207225
r242959r242960
223241** upvalues are already linked in 'headuv' list.)
224242*/
225243static void reallymarkobject (global_State *g, GCObject *o) {
226 reentry:
244  lu_mem size;
227245  white2gray(o);
228  switch (o->tt) {
246  switch (gch(o)->tt) {
229247    case LUA_TSHRSTR:
230248    case LUA_TLNGSTR: {
231      gray2black(o);
232      g->GCmemtrav += sizestring(gco2ts(o));
233      break;
249      size = sizestring(gco2ts(o));
250      break;  /* nothing else to mark; make it black */
234251    }
235252    case LUA_TUSERDATA: {
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      }
253      Table *mt = gco2u(o)->metatable;
254      markobject(g, mt);
255      markobject(g, gco2u(o)->env);
256      size = sizeudata(gco2u(o));
245257      break;
246258    }
247    case LUA_TLCL: {
248      linkgclist(gco2lcl(o), g->gray);
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);
249265      break;
250266    }
267    case LUA_TLCL: {
268      gco2lcl(o)->gclist = g->gray;
269      g->gray = o;
270      return;
271    }
251272    case LUA_TCCL: {
252      linkgclist(gco2ccl(o), g->gray);
253      break;
273      gco2ccl(o)->gclist = g->gray;
274      g->gray = o;
275      return;
254276    }
255277    case LUA_TTABLE: {
256      linkgclist(gco2t(o), g->gray);
257      break;
278      linktable(gco2t(o), &g->gray);
279      return;
258280    }
259281    case LUA_TTHREAD: {
260      linkgclist(gco2th(o), g->gray);
261      break;
282      gco2th(o)->gclist = g->gray;
283      g->gray = o;
284      return;
262285    }
263286    case LUA_TPROTO: {
264      linkgclist(gco2p(o), g->gray);
265      break;
287      gco2p(o)->gclist = g->gray;
288      g->gray = o;
289      return;
266290    }
267    default: lua_assert(0); break;
291    default: lua_assert(0); return;
268292  }
293  gray2black(o);
294  g->GCmemtrav += size;
269295}
270296
271297
r242959r242960
284310*/
285311static void markbeingfnz (global_State *g) {
286312  GCObject *o;
287  for (o = g->tobefnz; o != NULL; o = o->next)
288    markobject(g, o);
313  for (o = g->tobefnz; o != NULL; o = gch(o)->next) {
314    makewhite(g, o);
315    reallymarkobject(g, o);
316  }
289317}
290318
291319
292320/*
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.
321** mark all values stored in marked open upvalues. (See comment in
322** 'lstate.h'.)
297323*/
298324static void remarkupvals (global_State *g) {
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    }
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);
316329  }
317330}
318331
319332
320333/*
321** mark root set and reset all gray lists, to start a new collection
334** mark root set and reset all gray lists, to start a new
335** incremental (or full) collection
322336*/
323337static void restartcollection (global_State *g) {
324338  g->gray = g->grayagain = NULL;
r242959r242960
338352** =======================================================
339353*/
340354
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*/
347355static void traverseweakvalue (global_State *g, Table *h) {
348356  Node *n, *limit = gnodelast(h);
349  /* if there is array part, assume it may have white values (it is not
350     worth traversing it now just to check) */
357  /* if there is array part, assume it may have white values (do not
358     traverse it just to check) */
351359  int hasclears = (h->sizearray > 0);
352  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
360  for (n = gnode(h, 0); n < limit; n++) {
353361    checkdeadkey(n);
354362    if (ttisnil(gval(n)))  /* entry is empty? */
355363      removeentry(n);  /* remove it */
r242959r242960
360368        hasclears = 1;  /* table will have to be cleared */
361369    }
362370  }
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 */
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 */
367375}
368376
369377
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*/
380378static int traverseephemeron (global_State *g, Table *h) {
381379  int marked = 0;  /* true if an object is marked in this traversal */
382380  int hasclears = 0;  /* true if table has white keys */
383  int hasww = 0;  /* true if table has entry "white-key -> white-value" */
381  int prop = 0;  /* true if table has entry "white-key -> white-value" */
384382  Node *n, *limit = gnodelast(h);
385  unsigned int i;
386  /* traverse array part */
383  int i;
384  /* traverse array part (numeric keys are 'strong') */
387385  for (i = 0; i < h->sizearray; i++) {
388386    if (valiswhite(&h->array[i])) {
389387      marked = 1;
r242959r242960
398396    else if (iscleared(g, gkey(n))) {  /* key is not marked (yet)? */
399397      hasclears = 1;  /* table must be cleared */
400398      if (valiswhite(gval(n)))  /* value not marked yet? */
401        hasww = 1;  /* white-white entry */
399        prop = 1;  /* must propagate again */
402400    }
403401    else if (valiswhite(gval(n))) {  /* value not marked yet? */
404402      marked = 1;
405403      reallymarkobject(g, gcvalue(gval(n)));  /* mark it now */
406404    }
407405  }
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 */
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 */
415412  return marked;
416413}
417414
418415
419416static void traversestrongtable (global_State *g, Table *h) {
420417  Node *n, *limit = gnodelast(h);
421  unsigned int i;
418  int i;
422419  for (i = 0; i < h->sizearray; i++)  /* traverse array part */
423420    markvalue(g, &h->array[i]);
424421  for (n = gnode(h, 0); n < limit; n++) {  /* traverse hash part */
r242959r242960
442439      ((weakkey = strchr(svalue(mode), 'k')),
443440       (weakvalue = strchr(svalue(mode), 'v')),
444441       (weakkey || weakvalue))) {  /* is really weak? */
445    black2gray(h);  /* keep table gray */
442    black2gray(obj2gco(h));  /* keep table gray */
446443    if (!weakkey)  /* strong keys? */
447444      traverseweakvalue(g, h);
448445    else if (!weakvalue)  /* strong values? */
449446      traverseephemeron(g, h);
450447    else  /* all weak */
451      linkgclist(h, g->allweak);  /* nothing to traverse now */
448      linktable(h, &g->allweak);  /* nothing to traverse now */
452449  }
453450  else  /* not weak */
454451    traversestrongtable(g, h);
r242959r242960
459456
460457static int traverseproto (global_State *g, Proto *f) {
461458  int i;
462  if (f->cache && iswhite(f->cache))
459  if (f->cache && iswhite(obj2gco(f->cache)))
463460    f->cache = NULL;  /* allow cache to be collected */
464461  markobject(g, f->source);
465462  for (i = 0; i < f->sizek; i++)  /* mark literals */
r242959r242960
486483  return sizeCclosure(cl->nupvalues);
487484}
488485
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*/
495486static lu_mem traverseLclosure (global_State *g, LClosure *cl) {
496487  int i;
497488  markobject(g, cl->p);  /* mark its prototype */
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  }
489  for (i = 0; i < cl->nupvalues; i++)  /* mark its upvalues */
490    markobject(g, cl->upvals[i]);
507491  return sizeLclosure(cl->nupvalues);
508492}
509493
510494
511static lu_mem traversethread (global_State *g, lua_State *th) {
495static lu_mem traversestack (global_State *g, lua_State *th) {
496  int n = 0;
512497  StkId o = th->stack;
513498  if (o == NULL)
514499    return 1;  /* stack not completely built yet */
515  lua_assert(g->gcstate == GCSinsideatomic ||
516             th->openupval == NULL || isintwups(th));
517500  for (; o < th->top; o++)  /* mark live elements in the stack */
518501    markvalue(g, o);
519  if (g->gcstate == GCSinsideatomic) {  /* final traversal? */
502  if (g->gcstate == GCSatomic) {  /* final traversal? */
520503    StkId lim = th->stack + th->stacksize;  /* real end of stack */
521504    for (; o < lim; o++)  /* clear not-marked stack slice */
522505      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    }
528506  }
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);
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;
532514}
533515
534516
r242959r242960
541523  GCObject *o = g->gray;
542524  lua_assert(isgray(o));
543525  gray2black(o);
544  switch (o->tt) {
526  switch (gch(o)->tt) {
545527    case LUA_TTABLE: {
546528      Table *h = gco2t(o);
547529      g->gray = h->gclist;  /* remove from 'gray' list */
r242959r242960
563545    case LUA_TTHREAD: {
564546      lua_State *th = gco2th(o);
565547      g->gray = th->gclist;  /* remove from 'gray' list */
566      linkgclist(th, g->grayagain);  /* insert into 'grayagain' list */
548      th->gclist = g->grayagain;
549      g->grayagain = o;  /* insert into 'grayagain' list */
567550      black2gray(o);
568      size = traversethread(g, th);
551      size = traversestack(g, th);
569552      break;
570553    }
571554    case LUA_TPROTO: {
r242959r242960
585568}
586569
587570
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
588594static void convergeephemerons (global_State *g) {
589595  int changed;
590596  do {
591597    GCObject *w;
592598    GCObject *next = g->ephemeron;  /* get ephemeron list */
593    g->ephemeron = NULL;  /* tables may return to this list when traversed */
599    g->ephemeron = NULL;  /* tables will return to this list when traversed */
594600    changed = 0;
595601    while ((w = next) != NULL) {
596602      next = gco2t(w)->gclist;
r242959r242960
638644  for (; l != f; l = gco2t(l)->gclist) {
639645    Table *h = gco2t(l);
640646    Node *n, *limit = gnodelast(h);
641    unsigned int i;
647    int i;
642648    for (i = 0; i < h->sizearray; i++) {
643649      TValue *o = &h->array[i];
644650      if (iscleared(g, o))  /* value was collected? */
r242959r242960
654660}
655661
656662
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
676663static void freeobj (lua_State *L, GCObject *o) {
677  switch (o->tt) {
664  switch (gch(o)->tt) {
678665    case LUA_TPROTO: luaF_freeproto(L, gco2p(o)); break;
679666    case LUA_TLCL: {
680      freeLclosure(L, gco2lcl(o));
667      luaM_freemem(L, o, sizeLclosure(gco2lcl(o)->nupvalues));
681668      break;
682669    }
683670    case LUA_TCCL: {
684671      luaM_freemem(L, o, sizeCclosure(gco2ccl(o)->nupvalues));
685672      break;
686673    }
674    case LUA_TUPVAL: luaF_freeupval(L, gco2uv(o)); break;
687675    case LUA_TTABLE: luaH_free(L, gco2t(o)); break;
688676    case LUA_TTHREAD: luaE_freethread(L, gco2th(o)); break;
689677    case LUA_TUSERDATA: luaM_freemem(L, o, sizeudata(gco2u(o))); break;
690678    case LUA_TSHRSTR:
691      luaS_remove(L, gco2ts(o));  /* remove it from hash table */
679      G(L)->strt.nuse--;
692680      /* go through */
693681    case LUA_TLNGSTR: {
694682      luaM_freemem(L, o, sizestring(gco2ts(o)));
r242959r242960
704692
705693
706694/*
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/*
707709** sweep at most 'count' elements from a list of GCObjects erasing dead
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.
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.
712718*/
713719static GCObject **sweeplist (lua_State *L, GCObject **p, lu_mem count) {
714720  global_State *g = G(L);
715721  int ow = otherwhite(g);
716  int white = luaC_white(g);  /* current white */
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  }
717734  while (*p != NULL && count-- > 0) {
718735    GCObject *curr = *p;
719    int marked = curr->marked;
736    int marked = gch(curr)->marked;
720737    if (isdeadm(ow, marked)) {  /* is 'curr' dead? */
721      *p = curr->next;  /* remove 'curr' from list */
738      *p = gch(curr)->next;  /* remove 'curr' from list */
722739      freeobj(L, curr);  /* erase 'curr' */
723740    }
724    else {  /* change mark to 'white' */
725      curr->marked = cast_byte((marked & maskcolors) | white);
726      p = &curr->next;  /* go to next element */
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 */
727749    }
728750  }
729751  return (*p == NULL) ? NULL : p;
r242959r242960
734756** sweep a list until a live object (or end of list)
735757*/
736758static GCObject **sweeptolive (lua_State *L, GCObject **p, int *n) {
737  GCObject **old = p;
759  GCObject ** old = p;
738760  int i = 0;
739761  do {
740762    i++;
r242959r242960
753775** =======================================================
754776*/
755777
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;
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 */
762784    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 */
766785  }
767786}
768787
769788
770789static GCObject *udata2finalize (global_State *g) {
771790  GCObject *o = g->tobefnz;  /* get first element */
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 */
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 */
775794  g->allgc = o;
776  resetbit(o->marked, FINALIZEDBIT);  /* object is "normal" again */
777  if (issweepphase(g))
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? */
778798    makewhite(g, o);  /* "sweep" object */
779799  return o;
780800}
r242959r242960
819839
820840
821841/*
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/*
857842** move all unreachable objects (or 'all' objects) that need
858843** finalization from list 'finobj' to list 'tobefnz' (to be finalized)
859844*/
860static void separatetobefnz (global_State *g, int all) {
845static void separatetobefnz (lua_State *L, int all) {
846  global_State *g = G(L);
847  GCObject **p = &g->finobj;
861848  GCObject *curr;
862  GCObject **p = &g->finobj;
863  GCObject **lastnext = findlast(&g->tobefnz);
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;
864853  while ((curr = *p) != NULL) {  /* traverse all finalizable objects */
865    lua_assert(tofinalize(curr));
854    lua_assert(!isfinalized(curr));
855    lua_assert(testbit(gch(curr)->marked, SEPARATED));
866856    if (!(iswhite(curr) || all))  /* not being collected? */
867      p = &curr->next;  /* don't bother with it */
857      p = &gch(curr)->next;  /* don't bother with it */
868858    else {
869      *p = curr->next;  /* remove 'curr' from 'finobj' list */
870      curr->next = *lastnext;  /* link at the end of 'tobefnz' list */
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 */
871862      *lastnext = curr;
872      lastnext = &curr->next;
863      lastnext = &gch(curr)->next;
873864    }
874865  }
875866}
r242959r242960
881872*/
882873void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt) {
883874  global_State *g = G(L);
884  if (tofinalize(o) ||                 /* obj. is already marked... */
885      gfasttm(g, mt, TM_GC) == NULL)   /* or has no finalizer? */
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? */
886878    return;  /* nothing to be done */
887879  else {  /* move 'o' to 'finobj' list */
888880    GCObject **p;
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' */
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);
893885    }
894886    /* search for pointer pointing to 'o' */
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 */
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' */
898890    g->finobj = o;
899    l_setbit(o->marked, FINALIZEDBIT);  /* mark it as such */
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 */
900896  }
901897}
902898
903899/* }====================================================== */
904900
905901
906
907902/*
908903** {======================================================
909904** GC control
r242959r242960
912907
913908
914909/*
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).
910** set a reasonable "time" to wait before starting a new GC cycle;
911** cycle will start when memory use hits threshold
919912*/
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);
913static void setpause (global_State *g, l_mem estimate) {
914  l_mem debt, threshold;
915  estimate = estimate / PAUSEADJ;  /* adjust 'estimate' */
924916  threshold = (g->gcpause < MAX_LMEM / estimate)  /* overflow? */
925917            ? estimate * g->gcpause  /* no overflow */
926918            : MAX_LMEM;  /* overflow; truncate to maximum */
927  debt = gettotalbytes(g) - threshold;
919  debt = -cast(l_mem, threshold - gettotalbytes(g));
928920  luaE_setdebt(g, debt);
929921}
930922
931923
924#define sweepphases  \
925   (bitmask(GCSsweepstring) | bitmask(GCSsweepudata) | bitmask(GCSsweep))
926
927
932928/*
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.
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.
938934** Returns how many objects it swept.
939935*/
940936static int entersweep (lua_State *L) {
941937  global_State *g = G(L);
942938  int n = 0;
943  g->gcstate = GCSswpallgc;
944  lua_assert(g->sweepgc == NULL);
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);
945944  g->sweepgc = sweeptolive(L, &g->allgc, &n);
946945  return n;
947946}
948947
949948
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
950983void luaC_freeallobjects (lua_State *L) {
951984  global_State *g = G(L);
952  separatetobefnz(g, 1);  /* separate all objects with finalizers */
985  int i;
986  separatetobefnz(L, 1);  /* separate all objects with finalizers */
953987  lua_assert(g->finobj == NULL);
954988  callallpendingfinalizers(L, 0);
955  lua_assert(g->tobefnz == NULL);
956989  g->currentwhite = WHITEBITS; /* this "white" makes all objects look dead */
957990  g->gckind = KGC_NORMAL;
958  sweepwholelist(L, &g->finobj);
991  sweepwholelist(L, &g->finobj);  /* finalizers can create objs. in 'finobj' */
959992  sweepwholelist(L, &g->allgc);
960  sweepwholelist(L, &g->fixedgc);  /* collect fixed objects */
993  for (i = 0; i < g->strt.size; i++)  /* free all string lists */
994    sweepwholelist(L, &g->strt.hash[i]);
961995  lua_assert(g->strt.nuse == 0);
962996}
963997
964998
965999static l_mem atomic (lua_State *L) {
9661000  global_State *g = G(L);
967  l_mem work;
1001  l_mem work = -cast(l_mem, g->GCmemtrav);  /* start counting work */
9681002  GCObject *origweak, *origall;
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 */
1003  lua_assert(!iswhite(obj2gco(g->mainthread)));
9741004  markobject(g, L);  /* mark running thread */
9751005  /* registry and global metatables may be changed by API */
9761006  markvalue(g, &g->l_registry);
977  markmt(g);  /* mark global metatables */
1007  markmt(g);  /* mark basic metatables */
9781008  /* remark occasional upvalues of (maybe) dead threads */
9791009  remarkupvals(g);
9801010  propagateall(g);  /* propagate changes */
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 */
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 */
9851015  convergeephemerons(g);
9861016  /* at this point, all strongly accessible objects are marked. */
987  /* Clear values from weak tables, before checking finalizers */
1017  /* clear values from weak tables, before checking finalizers */
9881018  clearvalues(g, g->weak, NULL);
9891019  clearvalues(g, g->allweak, NULL);
9901020  origweak = g->weak; origall = g->allweak;
9911021  work += g->GCmemtrav;  /* stop counting (objects being finalized) */
992  separatetobefnz(g, 0);  /* separate objects to be finalized */
993  g->gcfinnum = 1;  /* there may be objects to be finalized */
1022  separatetobefnz(L, 0);  /* separate objects to be finalized */
9941023  markbeingfnz(g);  /* mark objects that will be finalized */
995  propagateall(g);  /* remark, to propagate 'resurrection' */
996  g->GCmemtrav = 0;  /* restart counting */
1024  propagateall(g);  /* remark, to propagate `preserveness' */
1025  work -= g->GCmemtrav;  /* restart counting */
9971026  convergeephemerons(g);
9981027  /* at this point, all resurrected objects are marked. */
9991028  /* remove dead objects from weak tables */
10001029  clearkeys(g, g->ephemeron, NULL);  /* clear keys from all ephemeron tables */
1001  clearkeys(g, g->allweak, NULL);  /* clear keys from all 'allweak' tables */
1030  clearkeys(g, g->allweak, NULL);  /* clear keys from all allweak tables */
10021031  /* clear values from resurrected weak tables */
10031032  clearvalues(g, g->weak, origweak);
10041033  clearvalues(g, g->allweak, origall);
r242959r242960
10081037}
10091038
10101039
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
10271040static lu_mem singlestep (lua_State *L) {
10281041  global_State *g = G(L);
10291042  switch (g->gcstate) {
10301043    case GCSpause: {
1044      /* start to count memory traversed */
10311045      g->GCmemtrav = g->strt.size * sizeof(GCObject*);
1046      lua_assert(!isgenerational(g));
10321047      restartcollection(g);
10331048      g->gcstate = GCSpropagate;
10341049      return g->GCmemtrav;
10351050    }
10361051    case GCSpropagate: {
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 */
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      }
10431067    }
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;
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;
10521076    }
1053    case GCSswpallgc: {  /* sweep "regular" objects */
1054      return sweepstep(L, g, GCSswpfinobj, &g->finobj);
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      }
10551086    }
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);
1087    case GCSsweep: {
1088      if (g->sweepgc) {
1089        g->sweepgc = sweeplist(L, g->sweepgc, GCSWEEPMAX);
1090        return GCSWEEPMAX*GCSWEEPCOST;
10721091      }
1073      else {  /* emergency mode or no more finalizers */
1092      else {
1093        /* sweep main thread */
1094        GCObject *mt = obj2gco(g->mainthread);
1095        sweeplist(L, &mt, 1);
1096        checkSizes(L);
10741097        g->gcstate = GCSpause;  /* finish collection */
1075        return 0;
1098        return GCSWEEPCOST;
10761099      }
10771100    }
10781101    default: lua_assert(0); return 0;
r242959r242960
10911114}
10921115
10931116
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) {
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);
10991141  l_mem debt = g->GCdebt;
11001142  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) */
11011145  debt = (debt / STEPMULADJ) + 1;
11021146  debt = (debt < MAX_LMEM / stepmul) ? debt * stepmul : MAX_LMEM;
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 */
1147  do {  /* always perform at least one single step */
1148    lu_mem work = singlestep(L);  /* do some work */
11181149    debt -= work;
11191150  } while (debt > -GCSTEPSIZE && g->gcstate != GCSpause);
11201151  if (g->gcstate == GCSpause)
1121    setpause(g);  /* pause until next cycle */
1152    setpause(g, g->GCestimate);  /* pause until next cycle */
11221153  else {
1123    debt = (debt / g->gcstepmul) * STEPMULADJ;  /* convert 'work units' to Kb */
1154    debt = (debt / stepmul) * STEPMULADJ;  /* convert 'work units' to Kb */
11241155    luaE_setdebt(g, debt);
1125    runafewfinalizers(L);
11261156  }
11271157}
11281158
11291159
11301160/*
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).
1161** performs a basic GC step
11381162*/
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*/
11391189void luaC_fullgc (lua_State *L, int isemergency) {
11401190  global_State *g = G(L);
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 */
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);
11451198  }
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  }
11461204  /* finish any pending sweep phase to start a new cycle */
11471205  luaC_runtilstate(L, bitmask(GCSpause));
11481206  luaC_runtilstate(L, ~bitmask(GCSpause));  /* start new collection */
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);
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);
11551216}
11561217
11571218/* }====================================================== */
trunk/3rdparty/lua/src/lgc.h
r242959r242960
11/*
2** $Id: lgc.h,v 2.86 2014/10/25 11:50:46 roberto Exp $
2** $Id: lgc.h,v 2.58.1.1 2013/04/12 18:48:47 roberto Exp $
33** Garbage Collector
44** See Copyright Notice in lua.h
55*/
r242959r242960
3838*/
3939#define GCSpropagate   0
4040#define GCSatomic   1
41#define GCSswpallgc   2
42#define GCSswpfinobj   3
43#define GCSswptobefnz   4
44#define GCSswpend   5
45#define GCScallfin   6
46#define GCSpause   7
41#define GCSsweepstring   2
42#define GCSsweepudata   3
43#define GCSsweep   4
44#define GCSpause   5
4745
4846
4947#define issweepphase(g)  \
50   (GCSswpallgc <= (g)->gcstate && (g)->gcstate <= GCSswpend)
48   (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep)
5149
50#define isgenerational(g)   ((g)->gckind == KGC_GEN)
5251
5352/*
54** macro to tell when main invariant (white objects cannot point to black
55** ones) must be kept. During a collection, the sweep
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
5655** phase may break the invariant, as objects turned white may point to
5756** still-black objects. The invariant is restored when sweep ends and
58** all objects are white again.
57** all objects are white again. During a generational collection, the
58** invariant must be kept all times.
5959*/
6060
61#define keepinvariant(g)   ((g)->gcstate <= GCSatomic)
61#define keepinvariant(g)   (isgenerational(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/*
6574** some useful bit tricks
6675*/
6776#define resetbits(x,m)      ((x) &= cast(lu_byte, ~(m)))
r242959r242960
7483#define testbit(x,b)      testbits(x, bitmask(b))
7584
7685
77/* Layout for bit use in 'marked' field: */
86/* Layout for bit use in `marked' field: */
7887#define WHITE0BIT   0  /* object is white (type 0) */
7988#define WHITE1BIT   1  /* object is white (type 1) */
8089#define BLACKBIT   2  /* object is black */
81#define FINALIZEDBIT   3  /* object has been marked for finalization */
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) */
8294/* bit 7 is currently used by tests (luaL_checkmemory) */
8395
8496#define WHITEBITS   bit2mask(WHITE0BIT, WHITE1BIT)
8597
8698
87#define iswhite(x)      testbits((x)->marked, WHITEBITS)
88#define isblack(x)      testbit((x)->marked, BLACKBIT)
99#define iswhite(x)      testbits((x)->gch.marked, WHITEBITS)
100#define isblack(x)      testbit((x)->gch.marked, BLACKBIT)
89101#define isgray(x)  /* neither white nor black */  \
90   (!testbits((x)->marked, WHITEBITS | bitmask(BLACKBIT)))
102   (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT)))
91103
92#define tofinalize(x)   testbit((x)->marked, FINALIZEDBIT)
104#define isold(x)   testbit((x)->gch.marked, OLDBIT)
93105
94#define otherwhite(g)   ((g)->currentwhite ^ WHITEBITS)
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)
95111#define isdeadm(ow,m)   (!(((m) ^ WHITEBITS) & (ow)))
96#define isdead(g,v)   isdeadm(otherwhite(g), (v)->marked)
112#define isdead(g,v)   isdeadm(otherwhite(g), (v)->gch.marked)
97113
98#define changewhite(x)   ((x)->marked ^= WHITEBITS)
99#define gray2black(x)   l_setbit((x)->marked, BLACKBIT)
114#define changewhite(x)   ((x)->gch.marked ^= WHITEBITS)
115#define gray2black(x)   l_setbit((x)->gch.marked, BLACKBIT)
100116
117#define valiswhite(x)   (iscollectable(x) && iswhite(gcvalue(x)))
118
101119#define luaC_white(g)   cast(lu_byte, (g)->currentwhite & WHITEBITS)
102120
103121
r242959r242960
106124#define luaC_checkGC(L)      luaC_condGC(L, luaC_step(L);)
107125
108126
109#define luaC_barrier(L,p,v) {  \
110   if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v)))  \
127#define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p)))  \
111128   luaC_barrier_(L,obj2gco(p),gcvalue(v)); }
112129
113#define luaC_barrierback(L,p,v) {  \
114   if (iscollectable(v) && isblack(p) && iswhite(gcvalue(v)))  \
130#define luaC_barrierback(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p)))  \
115131   luaC_barrierback_(L,p); }
116132
117#define luaC_objbarrier(L,p,o) {  \
118   if (isblack(p) && iswhite(o)) \
133#define luaC_objbarrier(L,p,o)  \
134   { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \
119135      luaC_barrier_(L,obj2gco(p),obj2gco(o)); }
120136
121#define luaC_upvalbarrier(L,uv) \
122  { if (iscollectable((uv)->v) && !upisopen(uv)) \
123         luaC_upvalbarrier_(L,uv); }
137#define luaC_objbarrierback(L,p,o)  \
138   { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) luaC_barrierback_(L,p); }
124139
125LUAI_FUNC void luaC_fix (lua_State *L, GCObject *o);
140#define luaC_barrierproto(L,p,c) \
141   { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); }
142
126143LUAI_FUNC void luaC_freeallobjects (lua_State *L);
127144LUAI_FUNC void luaC_step (lua_State *L);
145LUAI_FUNC void luaC_forcestep (lua_State *L);
128146LUAI_FUNC void luaC_runtilstate (lua_State *L, int statesmask);
129147LUAI_FUNC void luaC_fullgc (lua_State *L, int isemergency);
130LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz);
148LUAI_FUNC GCObject *luaC_newobj (lua_State *L, int tt, size_t sz,
149                                 GCObject **list, int offset);
131150LUAI_FUNC void luaC_barrier_ (lua_State *L, GCObject *o, GCObject *v);
132LUAI_FUNC void luaC_barrierback_ (lua_State *L, Table *o);
133LUAI_FUNC void luaC_upvalbarrier_ (lua_State *L, UpVal *uv);
151LUAI_FUNC void luaC_barrierback_ (lua_State *L, GCObject *o);
152LUAI_FUNC void luaC_barrierproto_ (lua_State *L, Proto *p, Closure *c);
134153LUAI_FUNC void luaC_checkfinalizer (lua_State *L, GCObject *o, Table *mt);
135LUAI_FUNC void luaC_upvdeccount (lua_State *L, UpVal *uv);
154LUAI_FUNC void luaC_checkupvalcolor (global_State *g, UpVal *uv);
155LUAI_FUNC void luaC_changemode (lua_State *L, int mode);
136156
137
138157#endif
trunk/3rdparty/lua/src/linit.c
r242959r242960
11/*
2** $Id: linit.c,v 1.38 2015/01/05 13:48:33 roberto Exp $
2** $Id: linit.c,v 1.32.1.1 2013/04/12 18:48:47 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
118/*
129** If you embed Lua in your program and need to open the standard
1310** libraries, call luaL_openlibs in your program. If you need a
1411** different set of libraries, copy this file to your project and edit
1512** 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
2513*/
2614
27#include "lprefix.h"
2815
16#define linit_c
17#define LUA_LIB
2918
30#include <stddef.h>
31
3219#include "lua.h"
3320
3421#include "lualib.h"
r242959r242960
4734  {LUA_IOLIBNAME, luaopen_io},
4835  {LUA_OSLIBNAME, luaopen_os},
4936  {LUA_STRLIBNAME, luaopen_string},
37  {LUA_BITLIBNAME, luaopen_bit32},
5038  {LUA_MATHLIBNAME, luaopen_math},
51  {LUA_UTF8LIBNAME, luaopen_utf8},
5239  {LUA_DBLIBNAME, luaopen_debug},
53#if defined(LUA_COMPAT_BITLIB)
54  {LUA_BITLIBNAME, luaopen_bit32},
55#endif
5640  {NULL, NULL}
5741};
5842
5943
44/*
45** these libs are preloaded and must be required before used
46*/
47static const luaL_Reg preloadedlibs[] = {
48  {NULL, NULL}
49};
50
51
6052LUALIB_API void luaL_openlibs (lua_State *L) {
6153  const luaL_Reg *lib;
62  /* "require" functions from 'loadedlibs' and set results to global table */
54  /* call open functions from 'loadedlibs' and set results to global table */
6355  for (lib = loadedlibs; lib->func; lib++) {
6456    luaL_requiref(L, lib->name, lib->func, 1);
6557    lua_pop(L, 1);  /* remove lib */
6658  }
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 */
6766}
6867
trunk/3rdparty/lua/src/liolib.c
r242959r242960
11/*
2** $Id: liolib.c,v 2.142 2015/01/02 12:50:28 roberto Exp $
2** $Id: liolib.c,v 2.112.1.1 2013/04/12 18:48:47 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
97
10#include "lprefix.h"
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
1116
1217
13#include <ctype.h>
1418#include <errno.h>
15#include <locale.h>
1619#include <stdio.h>
1720#include <stdlib.h>
1821#include <string.h>
1922
23#define liolib_c
24#define LUA_LIB
25
2026#include "lua.h"
2127
2228#include "lauxlib.h"
2329#include "lualib.h"
2430
2531
26#if !defined(l_checkmode)
32#if !defined(lua_checkmode)
2733
2834/*
2935** Check whether 'mode' matches '[rwa]%+?b?'.
3036** Change this macro to accept other modes for 'fopen' besides
3137** the standard ones.
3238*/
33#define l_checkmode(mode) \
39#define lua_checkmode(mode) \
3440   (*mode != '\0' && strchr("rwa", *(mode++)) != NULL &&   \
3541   (*mode != '+' || ++mode) &&  /* skip if char is '+' */   \
3642   (*mode != 'b' || ++mode) &&  /* skip if char is 'b' */   \
r242959r242960
4046
4147/*
4248** {======================================================
43** l_popen spawns a new process connected to the current
49** lua_popen spawns a new process connected to the current
4450** one through the file streams.
4551** =======================================================
4652*/
4753
48#if !defined(l_popen)      /* { */
54#if !defined(lua_popen)   /* { */
4955
50#if defined(LUA_USE_POSIX)   /* { */
56#if defined(LUA_USE_POPEN)   /* { */
5157
52#define l_popen(L,c,m)      (fflush(NULL), popen(c,m))
53#define l_pclose(L,file)   (pclose(file))
58#define lua_popen(L,c,m)   ((void)L, fflush(NULL), popen(c,m))
59#define lua_pclose(L,file)   ((void)L, pclose(file))
5460
55#elif defined(LUA_USE_WINDOWS)   /* }{ */
61#elif defined(LUA_WIN)      /* }{ */
5662
57#define l_popen(L,c,m)      (_popen(c,m))
58#define l_pclose(L,file)   (_pclose(file))
63#define lua_popen(L,c,m)      ((void)L, _popen(c,m))
64#define lua_pclose(L,file)      ((void)L, _pclose(file))
5965
66
6067#else            /* }{ */
6168
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)
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)
6872
69#endif            /* } */
7073
7174#endif            /* } */
7275
76#endif         /* } */
77
7378/* }====================================================== */
7479
7580
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
9181/*
9282** {======================================================
93** l_fseek: configuration for longer offsets
83** lua_fseek: configuration for longer offsets
9484** =======================================================
9585*/
9686
97#if !defined(l_fseek)      /* { */
87#if !defined(lua_fseek)   && !defined(LUA_ANSI)   /* { */
9888
9989#if defined(LUA_USE_POSIX)   /* { */
10090
101#include <sys/types.h>
102
10391#define l_fseek(f,o,w)      fseeko(f,o,w)
10492#define l_ftell(f)      ftello(f)
10593#define l_seeknum      off_t
10694
107#elif defined(LUA_USE_WINDOWS) && !defined(_CRTIMP_TYPEINFO) \
95#elif defined(LUA_WIN) && !defined(_CRTIMP_TYPEINFO) \
10896   && defined(_MSC_VER) && (_MSC_VER >= 1400)   /* }{ */
109
11097/* Windows (but not DDK) and Visual C++ 2005 or higher */
98
11199#define l_fseek(f,o,w)      _fseeki64(f,o,w)
112100#define l_ftell(f)      _ftelli64(f)
113101#define l_seeknum      __int64
114102
115#else            /* }{ */
103#endif   /* } */
116104
117/* ISO C definitions */
105#endif         /* } */
106
107
108#if !defined(l_fseek)      /* default definitions */
118109#define l_fseek(f,o,w)      fseek(f,o,w)
119110#define l_ftell(f)      ftell(f)
120111#define l_seeknum      long
112#endif
121113
122#endif            /* } */
123
124#endif            /* } */
125
126114/* }====================================================== */
127115
128116
129117#define IO_PREFIX   "_IO_"
130#define IOPREF_LEN   (sizeof(IO_PREFIX)/sizeof(char) - 1)
131118#define IO_INPUT   (IO_PREFIX "input")
132119#define IO_OUTPUT   (IO_PREFIX "output")
133120
r242959r242960
174161
175162
176163/*
177** When creating file handles, always creates a 'closed' file handle
164** When creating file handles, always creates a `closed' file handle
178165** before opening the actual file; so, if there is a memory error, the
179166** file is not left opened.
180167*/
r242959r242960
186173}
187174
188175
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*/
194176static int aux_close (lua_State *L) {
195177  LStream *p = tolstream(L);
196  volatile lua_CFunction cf = p->closef;
178  lua_CFunction cf = p->closef;
197179  p->closef = NULL;  /* mark stream as closed */
198180  return (*cf)(L);  /* close it */
199181}
r242959r242960
237219  LStream *p = newfile(L);
238220  p->f = fopen(fname, mode);
239221  if (p->f == NULL)
240    luaL_error(L, "cannot open file '%s' (%s)", fname, strerror(errno));
222    luaL_error(L, "cannot open file " LUA_QS " (%s)", fname, strerror(errno));
241223}
242224
243225
r242959r242960
246228  const char *mode = luaL_optstring(L, 2, "r");
247229  LStream *p = newfile(L);
248230  const char *md = mode;  /* to traverse/check mode */
249  luaL_argcheck(L, l_checkmode(md), 2, "invalid mode");
231  luaL_argcheck(L, lua_checkmode(md), 2, "invalid mode");
250232  p->f = fopen(filename, mode);
251233  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
252234}
r242959r242960
257239*/
258240static int io_pclose (lua_State *L) {
259241  LStream *p = tolstream(L);
260  return luaL_execresult(L, l_pclose(L, p->f));
242  return luaL_execresult(L, lua_pclose(L, p->f));
261243}
262244
263245
r242959r242960
265247  const char *filename = luaL_checkstring(L, 1);
266248  const char *mode = luaL_optstring(L, 2, "r");
267249  LStream *p = newprefile(L);
268  p->f = l_popen(L, filename, mode);
250  p->f = lua_popen(L, filename, mode);
269251  p->closef = &io_pclose;
270252  return (p->f == NULL) ? luaL_fileresult(L, 0, filename) : 1;
271253}
r242959r242960
283265  lua_getfield(L, LUA_REGISTRYINDEX, findex);
284266  p = (LStream *)lua_touserdata(L, -1);
285267  if (isclosed(p))
286    luaL_error(L, "standard %s file is closed", findex + IOPREF_LEN);
268    luaL_error(L, "standard %s file is closed", findex + strlen(IO_PREFIX));
287269  return p->f;
288270}
289271
r242959r242960
319301
320302
321303static void aux_lines (lua_State *L, int toclose) {
304  int i;
322305  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 */
323309  lua_pushinteger(L, n);  /* number of arguments to read */
324310  lua_pushboolean(L, toclose);  /* close/not close file when finished */
325  lua_rotate(L, 2, 2);  /* move 'n' and 'toclose' to their positions */
311  for (i = 1; i <= n; i++) lua_pushvalue(L, i + 1);  /* copy arguments */
326312  lua_pushcclosure(L, io_readline, 3 + n);
327313}
328314
r242959r242960
361347*/
362348
363349
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 */
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);
387354    return 1;
388355  }
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 */
356  else {
451357   lua_pushnil(L);  /* "result" to be removed */
452358   return 0;  /* read fails */
453359  }
r242959r242960
456362
457363static int test_eof (lua_State *L, FILE *f) {
458364  int c = getc(f);
459  ungetc(c, f);  /* no-op when c == EOF */
365  ungetc(c, f);
460366  lua_pushlstring(L, NULL, 0);
461367  return (c != EOF);
462368}
r242959r242960
464370
465371static int read_line (lua_State *L, FILE *f, int chop) {
466372  luaL_Buffer b;
467  int c = '\0';
468373  luaL_buffinit(L, &b);
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);
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    }
477389  }
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);
483390}
484391
485392
393#define MAX_SIZE_T   (~(size_t)0)
394
486395static void read_all (lua_State *L, FILE *f) {
487  size_t nr;
396  size_t rlen = LUAL_BUFFERSIZE;  /* how much to read in each cycle */
488397  luaL_Buffer b;
489398  luaL_buffinit(L, &b);
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);
399  for (;;) {
400    char *p = luaL_prepbuffsize(&b, rlen);
401    size_t nr = fread(p, sizeof(char), rlen, f);
493402    luaL_addsize(&b, nr);
494  } while (nr == LUAL_BUFFERSIZE);
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  }
495407  luaL_pushresult(&b);  /* close buffer */
496408}
497409
r242959r242960
523435    success = 1;
524436    for (n = first; nargs-- && success; n++) {
525437      if (lua_type(L, n) == LUA_TNUMBER) {
526        size_t l = (size_t)luaL_checkinteger(L, n);
438        size_t l = (size_t)lua_tointeger(L, n);
527439        success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
528440      }
529441      else {
530        const char *p = luaL_checkstring(L, n);
531        if (*p == '*') p++;  /* skip optional '*' (for compatibility) */
532        switch (*p) {
442        const char *p = lua_tostring(L, n);
443        luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
444        switch (p[1]) {
533445          case 'n':  /* number */
534446            success = read_number(L, f);
535447            break;
r242959r242960
576488  if (isclosed(p))  /* file is already closed? */
577489    return luaL_error(L, "file is already closed");
578490  lua_settop(L , 1);
579  luaL_checkstack(L, n, "too many arguments");
580491  for (i = 1; i <= n; i++)  /* push arguments to 'g_read' */
581492    lua_pushvalue(L, lua_upvalueindex(3 + i));
582493  n = g_read(L, p->f, 2);  /* 'n' is number of results */
583494  lua_assert(n > 0);  /* should return at least a nil */
584  if (lua_toboolean(L, -n))  /* read at least one value? */
495  if (!lua_isnil(L, -n))  /* read at least one value? */
585496    return n;  /* return them */
586497  else {  /* first result is nil: EOF or error */
587498    if (n > 1) {  /* is there error information? */
r242959r242960
606517  for (; nargs--; arg++) {
607518    if (lua_type(L, arg) == LUA_TNUMBER) {
608519      /* optimization: could be done exactly as for strings */
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);
520      status = status &&
521          fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
613522    }
614523    else {
615524      size_t l;
r242959r242960
639548  static const char *const modenames[] = {"set", "cur", "end", NULL};
640549  FILE *f = tofile(L);
641550  int op = luaL_checkoption(L, 2, "cur", modenames);
642  lua_Integer p3 = luaL_optinteger(L, 3, 0);
551  lua_Number p3 = luaL_optnumber(L, 3, 0);
643552  l_seeknum offset = (l_seeknum)p3;
644  luaL_argcheck(L, (lua_Integer)offset == p3, 3,
553  luaL_argcheck(L, (lua_Number)offset == p3, 3,
645554                  "not an integer in proper range");
646555  op = l_fseek(f, offset, mode[op]);
647556  if (op)
648557    return luaL_fileresult(L, 0, NULL);  /* error */
649558  else {
650    lua_pushinteger(L, (lua_Integer)l_ftell(f));
559    lua_pushnumber(L, (lua_Number)(1.0 * l_ftell(f)));
651560    return 1;
652561  }
653562}
r242959r242960
659568  FILE *f = tofile(L);
660569  int op = luaL_checkoption(L, 2, NULL, modenames);
661570  lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
662  int res = setvbuf(f, NULL, mode[op], (size_t)sz);
571  int res = setvbuf(f, NULL, mode[op], sz);
663572  return luaL_fileresult(L, res == 0, NULL);
664573}
665574
trunk/3rdparty/lua/src/llex.c
r242959r242960
11/*
2** $Id: llex.c,v 2.89 2014/11/14 16:06:09 roberto Exp $
2** $Id: llex.c,v 2.63.1.2 2013/08/30 15:49:41 roberto Exp $
33** Lexical Analyzer
44** See Copyright Notice in lua.h
55*/
66
7#define llex_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
138#include <locale.h>
149#include <string.h>
1510
11#define llex_c
12#define LUA_CORE
13
1614#include "lua.h"
1715
1816#include "lctype.h"
1917#include "ldo.h"
20#include "lgc.h"
2118#include "llex.h"
2219#include "lobject.h"
2320#include "lparser.h"
r242959r242960
4138    "end", "false", "for", "function", "goto", "if",
4239    "in", "local", "nil", "not", "or", "repeat",
4340    "return", "then", "true", "until", "while",
44    "//", "..", "...", "==", ">=", "<=", "~=",
45    "<<", ">>", "::", "<eof>",
46    "<number>", "<integer>", "<name>", "<string>"
41    "..", "...", "==", ">=", "<=", "~=", "::", "<eof>",
42    "<number>", "<name>", "<string>"
4743};
4844
4945
r242959r242960
5753  Mbuffer *b = ls->buff;
5854  if (luaZ_bufflen(b) + 1 > luaZ_sizebuffer(b)) {
5955    size_t newsize;
60    if (luaZ_sizebuffer(b) >= MAX_SIZE/2)
56    if (luaZ_sizebuffer(b) >= MAX_SIZET/2)
6157      lexerror(ls, "lexical element too long", 0);
6258    newsize = luaZ_sizebuffer(b) * 2;
6359    luaZ_resizebuffer(ls->L, b, newsize);
r242959r242960
6864
6965void luaX_init (lua_State *L) {
7066  int i;
71  TString *e = luaS_new(L, LUA_ENV);  /* create env name */
72  luaC_fix(L, obj2gco(e));  /* never collect this name */
7367  for (i=0; i<NUM_RESERVED; i++) {
7468    TString *ts = luaS_new(L, luaX_tokens[i]);
75    luaC_fix(L, obj2gco(ts));  /* reserved words are never collected */
76    ts->extra = cast_byte(i+1);  /* reserved word */
69    luaS_fix(ts);  /* reserved words are never collected */
70    ts->tsv.extra = cast_byte(i+1);  /* reserved word */
7771  }
7872}
7973
8074
8175const char *luaX_token2str (LexState *ls, int token) {
8276  if (token < FIRST_RESERVED) {  /* single-byte symbols? */
83    lua_assert(token == cast_uchar(token));
84    return luaO_pushfstring(ls->L, "'%c'", token);
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);
8580  }
8681  else {
8782    const char *s = luaX_tokens[token - FIRST_RESERVED];
8883    if (token < TK_EOS)  /* fixed format (symbols and reserved words)? */
89      return luaO_pushfstring(ls->L, "'%s'", s);
84      return luaO_pushfstring(ls->L, LUA_QS, s);
9085    else  /* names, strings, and numerals */
9186      return s;
9287  }
r242959r242960
9590
9691static const char *txtToken (LexState *ls, int token) {
9792  switch (token) {
98    case TK_NAME: case TK_STRING:
99    case TK_FLT: case TK_INT:
93    case TK_NAME:
94    case TK_STRING:
95    case TK_NUMBER:
10096      save(ls, '\0');
101      return luaO_pushfstring(ls->L, "'%s'", luaZ_buffer(ls->buff));
97      return luaO_pushfstring(ls->L, LUA_QS, luaZ_buffer(ls->buff));
10298    default:
10399      return luaX_token2str(ls, token);
104100  }
r242959r242960
121117
122118
123119/*
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)
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)
127123*/
128124TString *luaX_newstring (LexState *ls, const char *str, size_t l) {
129125  lua_State *L = ls->L;
130  TValue *o;  /* entry for 'str' */
126  TValue *o;  /* entry for `str' */
131127  TString *ts = luaS_newlstr(L, str, l);  /* create new string */
132128  setsvalue2s(L, L->top++, ts);  /* temporarily anchor it in stack */
133  o = luaH_set(L, ls->h, L->top - 1);
134  if (ttisnil(o)) {  /* not in use yet? */
129  o = luaH_set(L, ls->fs->h, L->top - 1);
130  if (ttisnil(o)) {  /* not in use yet? (see 'addK') */
135131    /* boolean value does not need GC barrier;
136132       table has no metatable, so it does not need to invalidate cache */
137133    setbvalue(o, 1);  /* t[string] = true */
138134    luaC_checkGC(L);
139135  }
140136  else {  /* string already present */
141    ts = tsvalue(keyfromval(o));  /* re-use value previously stored */
137    ts = rawtsvalue(keyfromval(o));  /* re-use value previously stored */
142138  }
143139  L->top--;  /* remove string from stack */
144140  return ts;
r242959r242960
152148static void inclinenumber (LexState *ls) {
153149  int old = ls->current;
154150  lua_assert(currIsNewline(ls));
155  next(ls);  /* skip '\n' or '\r' */
151  next(ls);  /* skip `\n' or `\r' */
156152  if (currIsNewline(ls) && ls->current != old)
157    next(ls);  /* skip '\n\r' or '\r\n' */
153    next(ls);  /* skip `\n\r' or `\r\n' */
158154  if (++ls->linenumber >= MAX_INT)
159    lexerror(ls, "chunk has too many lines", 0);
155    luaX_syntaxerror(ls, "chunk has too many lines");
160156}
161157
162158
163159void luaX_setinput (lua_State *L, LexState *ls, ZIO *z, TString *source,
164160                    int firstchar) {
165  ls->t.token = 0;
166161  ls->decpoint = '.';
167162  ls->L = L;
168163  ls->current = firstchar;
r242959r242960
172167  ls->linenumber = 1;
173168  ls->lastline = 1;
174169  ls->source = source;
175  ls->envn = luaS_new(L, LUA_ENV);  /* get env name */
170  ls->envn = luaS_new(L, LUA_ENV);  /* create env name */
171  luaS_fix(ls->envn);  /* never collect this name */
176172  luaZ_resizebuffer(ls->L, ls->buff, LUA_MINBUFFER);  /* initialize buffer */
177173}
178174
r242959r242960
185181*/
186182
187183
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}
195184
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;
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;
208190}
209191
210192
r242959r242960
212194** change all characters 'from' in buffer to 'to'
213195*/
214196static void buffreplace (LexState *ls, char from, char 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  }
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;
221201}
222202
223203
224#if !defined(l_getlocaledecpoint)
225#define l_getlocaledecpoint()   (localeconv()->decimal_point[0])
204#if !defined(getlocaledecpoint)
205#define getlocaledecpoint()   (localeconv()->decimal_point[0])
226206#endif
227207
228208
229#define buff2num(b,o)   (luaO_str2num(luaZ_buffer(b), o) != 0)
209#define buff2d(b,e)   luaO_str2d(luaZ_buffer(b), luaZ_bufflen(b) - 1, e)
230210
231211/*
232212** in case of format error, try to change decimal point separator to
233213** the one defined in the current locale and check again
234214*/
235static void trydecpoint (LexState *ls, TValue *o) {
215static void trydecpoint (LexState *ls, SemInfo *seminfo) {
236216  char old = ls->decpoint;
237  ls->decpoint = l_getlocaledecpoint();
217  ls->decpoint = getlocaledecpoint();
238218  buffreplace(ls, old, ls->decpoint);  /* try new decimal separator */
239  if (!buff2num(ls->buff, o)) {
219  if (!buff2d(ls->buff, &seminfo->r)) {
240220    /* format error with correct decimal point: no more options */
241221    buffreplace(ls, ls->decpoint, '.');  /* undo change (for error message) */
242    lexerror(ls, "malformed number", TK_FLT);
222    lexerror(ls, "malformed number", TK_NUMBER);
243223  }
244224}
245225
246226
247227/* LUA_NUMBER */
248228/*
249** this function is quite liberal in what it accepts, as 'luaO_str2num'
229** this function is quite liberal in what it accepts, as 'luaO_str2d'
250230** will reject ill-formed numerals.
251231*/
252static int read_numeral (LexState *ls, SemInfo *seminfo) {
253  TValue obj;
232static void read_numeral (LexState *ls, SemInfo *seminfo) {
254233  const char *expo = "Ee";
255234  int first = ls->current;
256235  lua_assert(lisdigit(ls->current));
257236  save_and_next(ls);
258  if (first == '0' && check_next2(ls, "xX"))  /* hexadecimal? */
237  if (first == '0' && check_next(ls, "Xx"))  /* hexadecimal? */
259238    expo = "Pp";
260239  for (;;) {
261    if (check_next2(ls, expo))  /* exponent part? */
262      check_next2(ls, "-+");  /* optional exponent sign */
263    if (lisxdigit(ls->current))
240    if (check_next(ls, expo))  /* exponent part? */
241      check_next(ls, "+-");  /* optional exponent sign */
242    if (lisxdigit(ls->current) || ls->current == '.')
264243      save_and_next(ls);
265    else if (ls->current == '.')
266      save_and_next(ls);
267    else break;
244    else  break;
268245  }
269246  save(ls, '\0');
270247  buffreplace(ls, '.', ls->decpoint);  /* follow locale for decimal point */
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  }
248  if (!buff2d(ls->buff, &seminfo->r))  /* format error? */
249    trydecpoint(ls, seminfo); /* try to update decimal point separator */
282250}
283251
284252
r242959r242960
300268
301269
302270static void read_long_string (LexState *ls, SemInfo *seminfo, int sep) {
303  int line = ls->linenumber;  /* initial line (for error message) */
304  save_and_next(ls);  /* skip 2nd '[' */
271  save_and_next(ls);  /* skip 2nd `[' */
305272  if (currIsNewline(ls))  /* string starts with a newline? */
306273    inclinenumber(ls);  /* skip it */
307274  for (;;) {
308275    switch (ls->current) {
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);
276      case EOZ:
277        lexerror(ls, (seminfo) ? "unfinished long string" :
278                                 "unfinished long comment", TK_EOS);
314279        break;  /* to avoid warnings */
315      }
316280      case ']': {
317281        if (skip_sep(ls) == sep) {
318          save_and_next(ls);  /* skip 2nd ']' */
282          save_and_next(ls);  /* skip 2nd `]' */
319283          goto endloop;
320284        }
321285        break;
r242959r242960
338302}
339303
340304
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  }
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);
347312}
348313
349314
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
357315static int readhexaesc (LexState *ls) {
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");
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]);
375324  }
376  esccheck(ls, ls->current == '}', "missing '}'");
377  next(ls);  /* skip '}' */
378  luaZ_buffremove(ls->buff, i);  /* remove saved chars from buffer */
379325  return r;
380326}
381327
382328
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
391329static int readdecesc (LexState *ls) {
392  int i;
330  int c[3], i;
393331  int r = 0;  /* result accumulator */
394332  for (i = 0; i < 3 && lisdigit(ls->current); i++) {  /* read up to 3 digits */
395    r = 10*r + ls->current - '0';
396    save_and_next(ls);
333    c[i] = ls->current;
334    r = 10*r + c[i] - '0';
335    next(ls);
397336  }
398  esccheck(ls, r <= UCHAR_MAX, "decimal escape too large");
399  luaZ_buffremove(ls->buff, i);  /* remove read digits from buffer */
337  if (r > UCHAR_MAX)
338    escerror(ls, c, i, "decimal escape too large");
400339  return r;
401340}
402341
r242959r242960
414353        break;  /* to avoid warnings */
415354      case '\\': {  /* escape sequences */
416355        int c;  /* final character to be saved */
417        save_and_next(ls);  /* keep '\\' for error messages */
356        next(ls);  /* do not save the `\' */
418357        switch (ls->current) {
419358          case 'a': c = '\a'; goto read_save;
420359          case 'b': c = '\b'; goto read_save;
r242959r242960
424363          case 't': c = '\t'; goto read_save;
425364          case 'v': c = '\v'; goto read_save;
426365          case 'x': c = readhexaesc(ls); goto read_save;
427          case 'u': utf8esc(ls);  goto no_save;
428366          case '\n': case '\r':
429367            inclinenumber(ls); c = '\n'; goto only_save;
430368          case '\\': case '\"': case '\'':
431369            c = ls->current; goto read_save;
432370          case EOZ: goto no_save;  /* will raise an error next loop */
433371          case 'z': {  /* zap following span of spaces */
434            luaZ_buffremove(ls->buff, 1);  /* remove '\\' */
435372            next(ls);  /* skip the 'z' */
436373            while (lisspace(ls->current)) {
437374              if (currIsNewline(ls)) inclinenumber(ls);
r242959r242960
440377            goto no_save;
441378          }
442379          default: {
443            esccheck(ls, lisdigit(ls->current), "invalid escape sequence");
444            c = readdecesc(ls);  /* digital escape '\ddd' */
380            if (!lisdigit(ls->current))
381              escerror(ls, &ls->current, 1, "invalid escape sequence");
382            /* digital escape \ddd */
383            c = readdecesc(ls);
445384            goto only_save;
446385          }
447386        }
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 */
387       read_save: next(ls);  /* read next character */
388       only_save: save(ls, c);  /* save 'c' */
455389       no_save: break;
456390      }
457391      default:
r242959r242960
483417        next(ls);
484418        if (ls->current == '[') {  /* long comment? */
485419          int sep = skip_sep(ls);
486          luaZ_resetbuffer(ls->buff);  /* 'skip_sep' may dirty the buffer */
420          luaZ_resetbuffer(ls->buff);  /* `skip_sep' may dirty the buffer */
487421          if (sep >= 0) {
488422            read_long_string(ls, NULL, sep);  /* skip long comment */
489423            luaZ_resetbuffer(ls->buff);  /* previous call may dirty the buff. */
r242959r242960
506440      }
507441      case '=': {
508442        next(ls);
509        if (check_next1(ls, '=')) return TK_EQ;
510        else return '=';
443        if (ls->current != '=') return '=';
444        else { next(ls); return TK_EQ; }
511445      }
512446      case '<': {
513447        next(ls);
514        if (check_next1(ls, '=')) return TK_LE;
515        else if (check_next1(ls, '<')) return TK_SHL;
516        else return '<';
448        if (ls->current != '=') return '<';
449        else { next(ls); return TK_LE; }
517450      }
518451      case '>': {
519452        next(ls);
520        if (check_next1(ls, '=')) return TK_GE;
521        else if (check_next1(ls, '>')) return TK_SHR;
522        else return '>';
453        if (ls->current != '=') return '>';
454        else { next(ls); return TK_GE; }
523455      }
524      case '/': {
525        next(ls);
526        if (check_next1(ls, '/')) return TK_IDIV;
527        else return '/';
528      }
529456      case '~': {
530457        next(ls);
531        if (check_next1(ls, '=')) return TK_NE;
532        else return '~';
458        if (ls->current != '=') return '~';
459        else { next(ls); return TK_NE; }
533460      }
534461      case ':': {
535462        next(ls);
536        if (check_next1(ls, ':')) return TK_DBCOLON;
537        else return ':';
463        if (ls->current != ':') return ':';
464        else { next(ls); return TK_DBCOLON; }
538465      }
539466      case '"': case '\'': {  /* short literal strings */
540467        read_string(ls, ls->current, seminfo);
r242959r242960
542469      }
543470      case '.': {  /* '.', '..', '...', or number */
544471        save_and_next(ls);
545        if (check_next1(ls, '.')) {
546          if (check_next1(ls, '.'))
472        if (check_next(ls, ".")) {
473          if (check_next(ls, "."))
547474            return TK_DOTS;   /* '...' */
548475          else return TK_CONCAT;   /* '..' */
549476        }
550477        else if (!lisdigit(ls->current)) return '.';
551        else return read_numeral(ls, seminfo);
478        /* else go through */
552479      }
553480      case '0': case '1': case '2': case '3': case '4':
554481      case '5': case '6': case '7': case '8': case '9': {
555        return read_numeral(ls, seminfo);
482        read_numeral(ls, seminfo);
483        return TK_NUMBER;
556484      }
557485      case EOZ: {
558486        return TK_EOS;
r242959r242960
567495                                  luaZ_bufflen(ls->buff));
568496          seminfo->ts = ts;
569497          if (isreserved(ts))  /* reserved word? */
570            return ts->extra - 1 + FIRST_RESERVED;
498            return ts->tsv.extra - 1 + FIRST_RESERVED;
571499          else {
572500            return TK_NAME;
573501          }
trunk/3rdparty/lua/src/llex.h
r242959r242960
11/*
2** $Id: llex.h,v 1.78 2014/10/29 15:38:24 roberto Exp $
2** $Id: llex.h,v 1.72.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lexical Analyzer
44** See Copyright Notice in lua.h
55*/
r242959r242960
1414#define FIRST_RESERVED   257
1515
1616
17#if !defined(LUA_ENV)
18#define LUA_ENV      "_ENV"
19#endif
2017
21
2218/*
2319* WARNING: if you change the order of this enumeration,
2420* grep "ORDER RESERVED"
r242959r242960
3026  TK_GOTO, TK_IF, TK_IN, TK_LOCAL, TK_NIL, TK_NOT, TK_OR, TK_REPEAT,
3127  TK_RETURN, TK_THEN, TK_TRUE, TK_UNTIL, TK_WHILE,
3228  /* other terminal symbols */
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
29  TK_CONCAT, TK_DOTS, TK_EQ, TK_GE, TK_LE, TK_NE, TK_DBCOLON, TK_EOS,
30  TK_NUMBER, TK_NAME, TK_STRING
3731};
3832
3933/* number of reserved words */
r242959r242960
4236
4337typedef union {
4438  lua_Number r;
45  lua_Integer i;
4639  TString *ts;
4740} SemInfo;  /* semantics information */
4841
r242959r242960
5851typedef struct LexState {
5952  int current;  /* current character (charint) */
6053  int linenumber;  /* input line counter */
61  int lastline;  /* line of last token 'consumed' */
54  int lastline;  /* line of last token `consumed' */
6255  Token t;  /* current token */
6356  Token lookahead;  /* look ahead token */
6457  struct FuncState *fs;  /* current function (parser) */
6558  struct lua_State *L;
6659  ZIO *z;  /* input stream */
6760  Mbuffer *buff;  /* buffer for tokens */
68  Table *h;  /* to avoid collection/reuse strings */
6961  struct Dyndata *dyd;  /* dynamic structures used by the parser */
7062  TString *source;  /* current source name */
7163  TString *envn;  /* environment variable name */
trunk/3rdparty/lua/src/llimits.h
r242959r242960
11/*
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
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
44** See Copyright Notice in lua.h
55*/
66
r242959r242960
1414
1515#include "lua.h"
1616
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? */
17
18typedef unsigned LUA_INT32 lu_int32;
19
2320typedef LUAI_UMEM lu_mem;
21
2422typedef 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            /* } */
3223
3324
34/* chars used as small naturals (so that 'char' is reserved for characters) */
25
26/* chars used as small naturals (so that `char' is reserved for characters) */
3527typedef unsigned char lu_byte;
3628
3729
38/* maximum value for size_t */
39#define MAX_SIZET   ((size_t)(~(size_t)0))
30#define MAX_SIZET   ((size_t)(~(size_t)0)-2)
4031
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))
32#define MAX_LUMEM   ((lu_mem)(~(lu_mem)0)-2)
4433
34#define MAX_LMEM   ((l_mem) ((MAX_LUMEM >> 1) - 2))
4535
46#define MAX_LUMEM   ((lu_mem)(~(lu_mem)0))
4736
48#define MAX_LMEM   ((l_mem)(MAX_LUMEM >> 1))
37#define MAX_INT (INT_MAX-2)  /* maximum value of an int (-2 for safety) */
4938
50
51#define MAX_INT      INT_MAX  /* maximum value of an int */
52
53
5439/*
55** conversion of pointer to integer:
40** conversion of pointer to integer
5641** this is for hashing only; there is no problem if the integer
5742** cannot hold the whole pointer value
5843*/
59#define point2int(p)   ((unsigned int)((size_t)(p) & UINT_MAX))
44#define IntPoint(p)  ((unsigned int)(lu_mem)(p))
6045
6146
6247
6348/* type to ensure maximum alignment */
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;
49#if !defined(LUAI_USER_ALIGNMENT_T)
50#define LUAI_USER_ALIGNMENT_T   union { double u; void *s; long l; }
6851#endif
6952
53typedef LUAI_USER_ALIGNMENT_T L_Umaxalign;
7054
7155
72/* types of 'usual argument conversions' for lua_Number and lua_Integer */
56/* result of a `usual argument conversion' over lua_Number */
7357typedef LUAI_UACNUMBER l_uacNumber;
74typedef LUAI_UACINT l_uacInt;
7558
7659
7760/* internal assertions for in-house debugging */
r242959r242960
8871/*
8972** assertion for checking API calls
9073*/
74#if !defined(luai_apicheck)
75
9176#if defined(LUA_USE_APICHECK)
9277#include <assert.h>
93#define luai_apicheck(e)   assert(e)
78#define luai_apicheck(L,e)   assert(e)
9479#else
95#define luai_apicheck(e)   lua_assert(e)
80#define luai_apicheck(L,e)   lua_assert(e)
9681#endif
9782
83#endif
9884
99#define api_check(e,msg)   luai_apicheck((e) && msg)
85#define api_check(l,e,msg)   luai_apicheck(l,(e) && msg)
10086
10187
10288#if !defined(UNUSED)
r242959r242960
10692
10793#define cast(t, exp)   ((t)(exp))
10894
109#define cast_void(i)   cast(void, (i))
11095#define cast_byte(i)   cast(lu_byte, (i))
11196#define cast_num(i)   cast(lua_Number, (i))
11297#define cast_int(i)   cast(int, (i))
11398#define cast_uchar(i)   cast(unsigned char, (i))
11499
115100
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
121101/*
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/*
132102** non-return type
133103*/
134104#if defined(__GNUC__)
135105#define l_noret      void __attribute__((noreturn))
136#elif defined(_MSC_VER) && _MSC_VER >= 1200
106#elif defined(_MSC_VER)
137107#define l_noret      void __declspec(noreturn)
138108#else
139109#define l_noret      void
r242959r242960
157127
158128
159129/*
160** type for virtual-machine instructions;
130** type for virtual-machine instructions
161131** must be an unsigned with (at least) 4 bytes (see details in lopcodes.h)
162132*/
163#if LUAI_BITSINT >= 32
164typedef unsigned int Instruction;
165#else
166typedef unsigned long Instruction;
167#endif
133typedef lu_int32 Instruction;
168134
169135
170136
137/* maximum stack for a Lua function */
138#define MAXSTACK   250
171139
140
141
172142/* minimum size for the string table (must be power of 2) */
173143#if !defined(MINSTRTABSIZE)
174#define MINSTRTABSIZE   64   /* minimum size for "predefined" strings */
144#define MINSTRTABSIZE   32
175145#endif
176146
177147
r242959r242960
182152
183153
184154#if !defined(lua_lock)
185#define lua_lock(L)   ((void) 0)
186#define lua_unlock(L)   ((void) 0)
155#define lua_lock(L)     ((void) 0)
156#define lua_unlock(L)   ((void) 0)
187157#endif
188158
189159#if !defined(luai_threadyield)
190#define luai_threadyield(L)   {lua_unlock(L); lua_lock(L);}
160#define luai_threadyield(L)     {lua_unlock(L); lua_lock(L);}
191161#endif
192162
193163
r242959r242960
213183#endif
214184
215185#if !defined(luai_userstateresume)
216#define luai_userstateresume(L,n)   ((void)L)
186#define luai_userstateresume(L,n)       ((void)L)
217187#endif
218188
219189#if !defined(luai_userstateyield)
220#define luai_userstateyield(L,n)   ((void)L)
190#define luai_userstateyield(L,n)        ((void)L)
221191#endif
222192
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*/
223202
203#if defined(MS_ASMTRICK) || defined(LUA_MSASMTRICK)   /* { */
204/* trick with Microsoft assembler for X86 */
224205
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
225292/*
226293** macro to control inclusion of some hard tests on stack reallocation
227294*/
trunk/3rdparty/lua/src/lmathlib.c
r242959r242960
11/*
2** $Id: lmathlib.c,v 1.114 2014/12/27 20:32:26 roberto Exp $
2** $Id: lmathlib.c,v 1.83.1.1 2013/04/12 18:48:47 roberto Exp $
33** Standard mathematical library
44** See Copyright Notice in lua.h
55*/
66
7#define lmathlib_c
8#define LUA_LIB
97
10#include "lprefix.h"
11
12
138#include <stdlib.h>
149#include <math.h>
1510
11#define lmathlib_c
12#define LUA_LIB
13
1614#include "lua.h"
1715
1816#include "lauxlib.h"
r242959r242960
2018
2119
2220#undef PI
23#define PI   (l_mathop(3.141592653589793238462643383279502884))
21#define PI   ((lua_Number)(3.1415926535897932384626433832795))
22#define RADIANS_PER_DEGREE   ((lua_Number)(PI/180.0))
2423
2524
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            /* } */
3725
38
3926static int math_abs (lua_State *L) {
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)));
27  lua_pushnumber(L, l_mathop(fabs)(luaL_checknumber(L, 1)));
4728  return 1;
4829}
4930
r242959r242960
5233  return 1;
5334}
5435
36static int math_sinh (lua_State *L) {
37  lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
38  return 1;
39}
40
5541static int math_cos (lua_State *L) {
5642  lua_pushnumber(L, l_mathop(cos)(luaL_checknumber(L, 1)));
5743  return 1;
5844}
5945
46static int math_cosh (lua_State *L) {
47  lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
48  return 1;
49}
50
6051static int math_tan (lua_State *L) {
6152  lua_pushnumber(L, l_mathop(tan)(luaL_checknumber(L, 1)));
6253  return 1;
6354}
6455
56static int math_tanh (lua_State *L) {
57  lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
58  return 1;
59}
60
6561static int math_asin (lua_State *L) {
6662  lua_pushnumber(L, l_mathop(asin)(luaL_checknumber(L, 1)));
6763  return 1;
r242959r242960
7369}
7470
7571static int math_atan (lua_State *L) {
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));
72  lua_pushnumber(L, l_mathop(atan)(luaL_checknumber(L, 1)));
7973  return 1;
8074}
8175
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  }
76static int math_atan2 (lua_State *L) {
77  lua_pushnumber(L, l_mathop(atan2)(luaL_checknumber(L, 1),
78                                luaL_checknumber(L, 2)));
9279  return 1;
9380}
9481
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 */
82static int math_ceil (lua_State *L) {
83  lua_pushnumber(L, l_mathop(ceil)(luaL_checknumber(L, 1)));
84  return 1;
10285}
10386
104
10587static int math_floor (lua_State *L) {
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  }
88  lua_pushnumber(L, l_mathop(floor)(luaL_checknumber(L, 1)));
11289  return 1;
11390}
11491
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
12792static int math_fmod (lua_State *L) {
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)));
93  lua_pushnumber(L, l_mathop(fmod)(luaL_checknumber(L, 1),
94                               luaL_checknumber(L, 2)));
14095  return 1;
14196}
14297
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*/
14998static int math_modf (lua_State *L) {
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  }
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);
162103  return 2;
163104}
164105
165
166106static int math_sqrt (lua_State *L) {
167107  lua_pushnumber(L, l_mathop(sqrt)(luaL_checknumber(L, 1)));
168108  return 1;
169109}
170110
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);
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));
176115  return 1;
177116}
178117
r242959r242960
183122    res = l_mathop(log)(x);
184123  else {
185124    lua_Number base = luaL_checknumber(L, 2);
186    if (base == 10.0) res = l_mathop(log10)(x);
125    if (base == (lua_Number)10.0) res = l_mathop(log10)(x);
187126    else res = l_mathop(log)(x)/l_mathop(log)(base);
188127  }
189128  lua_pushnumber(L, res);
190129  return 1;
191130}
192131
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
193139static int math_exp (lua_State *L) {
194140  lua_pushnumber(L, l_mathop(exp)(luaL_checknumber(L, 1)));
195141  return 1;
196142}
197143
198144static int math_deg (lua_State *L) {
199  lua_pushnumber(L, luaL_checknumber(L, 1) * (l_mathop(180.0) / PI));
145  lua_pushnumber(L, luaL_checknumber(L, 1)/RADIANS_PER_DEGREE);
200146  return 1;
201147}
202148
203149static int math_rad (lua_State *L) {
204  lua_pushnumber(L, luaL_checknumber(L, 1) * (PI / l_mathop(180.0)));
150  lua_pushnumber(L, luaL_checknumber(L, 1)*RADIANS_PER_DEGREE);
205151  return 1;
206152}
207153
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}
208160
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
209170static int math_min (lua_State *L) {
210171  int n = lua_gettop(L);  /* number of arguments */
211  int imin = 1;  /* index of current minimum value */
172  lua_Number dmin = luaL_checknumber(L, 1);
212173  int i;
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;
174  for (i=2; i<=n; i++) {
175    lua_Number d = luaL_checknumber(L, i);
176    if (d < dmin)
177      dmin = d;
217178  }
218  lua_pushvalue(L, imin);
179  lua_pushnumber(L, dmin);
219180  return 1;
220181}
221182
222183
223184static int math_max (lua_State *L) {
224185  int n = lua_gettop(L);  /* number of arguments */
225  int imax = 1;  /* index of current maximum value */
186  lua_Number dmax = luaL_checknumber(L, 1);
226187  int i;
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;
188  for (i=2; i<=n; i++) {
189    lua_Number d = luaL_checknumber(L, i);
190    if (d > dmax)
191      dmax = d;
231192  }
232  lua_pushvalue(L, imax);
193  lua_pushnumber(L, dmax);
233194  return 1;
234195}
235196
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*/
197
241198static int math_random (lua_State *L) {
242  lua_Integer low, up;
243  double r = (double)(1.0 * l_rand()) * (1.0 / ((double)L_RANDMAX + 1.0));
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;
244202  switch (lua_gettop(L)) {  /* check number of arguments */
245203    case 0: {  /* no arguments */
246      lua_pushnumber(L, (lua_Number)r);  /* Number between 0 and 1 */
247      return 1;
204      lua_pushnumber(L, r);  /* Number between 0 and 1 */
205      break;
248206    }
249207    case 1: {  /* only upper limit */
250      low = 1;
251      up = luaL_checkinteger(L, 1);
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] */
252211      break;
253212    }
254213    case 2: {  /* lower and upper limits */
255      low = luaL_checkinteger(L, 1);
256      up = luaL_checkinteger(L, 2);
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] */
257218      break;
258219    }
259220    default: return luaL_error(L, "wrong number of arguments");
260221  }
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);
267222  return 1;
268223}
269224
270225
271226static int math_randomseed (lua_State *L) {
272  lua_Number seed = (lua_Number)luaL_checknumber(L, 1);
273  l_srand((unsigned int)seed);
227  srand(luaL_checkunsigned(L, 1));
274228  (void)rand(); /* discard first value to avoid undesirable correlations */
275229  return 0;
276230}
277231
278232
279static int math_type (lua_State *L) {
280  if (lua_type(L, 1) == LUA_TNUMBER) {
281      if (lua_isinteger(L, 1))
282        lua_pushliteral(L, "integer");
283      else
284        lua_pushliteral(L, "float");
285  }
286  else {
287    luaL_checkany(L, 1);
288    lua_pushnil(L);
289  }
290  return 1;
291}
292
293
294/*
295** {==================================================================
296** Deprecated functions (for compatibility only)
297** ===================================================================
298*/
299#if defined(LUA_COMPAT_MATHLIB)
300
301static int math_cosh (lua_State *L) {
302  lua_pushnumber(L, l_mathop(cosh)(luaL_checknumber(L, 1)));
303  return 1;
304}
305
306static int math_sinh (lua_State *L) {
307  lua_pushnumber(L, l_mathop(sinh)(luaL_checknumber(L, 1)));
308  return 1;
309}
310
311static int math_tanh (lua_State *L) {
312  lua_pushnumber(L, l_mathop(tanh)(luaL_checknumber(L, 1)));
313  return 1;
314}
315
316static int math_pow (lua_State *L) {
317  lua_Number x = luaL_checknumber(L, 1);
318  lua_Number y = luaL_checknumber(L, 2);
319  lua_pushnumber(L, l_mathop(pow)(x, y));
320  return 1;
321}
322
323static int math_frexp (lua_State *L) {
324  int e;
325  lua_pushnumber(L, l_mathop(frexp)(luaL_checknumber(L, 1), &e));
326  lua_pushinteger(L, e);
327  return 2;
328}
329
330static int math_ldexp (lua_State *L) {
331  lua_Number x = luaL_checknumber(L, 1);
332  int ep = (int)luaL_checkinteger(L, 2);
333  lua_pushnumber(L, l_mathop(ldexp)(x, ep));
334  return 1;
335}
336
337static int math_log10 (lua_State *L) {
338  lua_pushnumber(L, l_mathop(log10)(luaL_checknumber(L, 1)));
339  return 1;
340}
341
342#endif
343/* }================================================================== */
344
345
346
347233static const luaL_Reg mathlib[] = {
348234  {"abs",   math_abs},
349235  {"acos",  math_acos},
350236  {"asin",  math_asin},
237  {"atan2", math_atan2},
351238  {"atan",  math_atan},
352239  {"ceil",  math_ceil},
240  {"cosh",   math_cosh},
353241  {"cos",   math_cos},
354242  {"deg",   math_deg},
355243  {"exp",   math_exp},
356  {"tointeger", math_toint},
357244  {"floor", math_floor},
358245  {"fmod",   math_fmod},
359  {"ult",   math_ult},
246  {"frexp", math_frexp},
247  {"ldexp", math_ldexp},
248#if defined(LUA_COMPAT_LOG10)
249  {"log10", math_log10},
250#endif
360251  {"log",   math_log},
361252  {"max",   math_max},
362253  {"min",   math_min},
363254  {"modf",   math_modf},
255  {"pow",   math_pow},
364256  {"rad",   math_rad},
365257  {"random",     math_random},
366258  {"randomseed", math_randomseed},
259  {"sinh",   math_sinh},
367260  {"sin",   math_sin},
368261  {"sqrt",  math_sqrt},
369  {"tan",   math_tan},
370  {"type", math_type},
371#if defined(LUA_COMPAT_MATHLIB)
372  {"atan2", math_atan},
373  {"cosh",   math_cosh},
374  {"sinh",   math_sinh},
375262  {"tanh",   math_tanh},
376  {"pow",   math_pow},
377  {"frexp", math_frexp},
378  {"ldexp", math_ldexp},
379  {"log10", math_log10},
380#endif
381  /* placeholders */
382  {"pi", NULL},
383  {"huge", NULL},
384  {"maxinteger", NULL},
385  {"mininteger", NULL},
263  {"tan",   math_tan},
386264  {NULL, NULL}
387265};
388266
r242959r242960
394272  luaL_newlib(L, mathlib);
395273  lua_pushnumber(L, PI);
396274  lua_setfield(L, -2, "pi");
397  lua_pushnumber(L, (lua_Number)HUGE_VAL);
275  lua_pushnumber(L, HUGE_VAL);
398276  lua_setfield(L, -2, "huge");
399  lua_pushinteger(L, LUA_MAXINTEGER);
400  lua_setfield(L, -2, "maxinteger");
401  lua_pushinteger(L, LUA_MININTEGER);
402  lua_setfield(L, -2, "mininteger");
403277  return 1;
404278}
405279
trunk/3rdparty/lua/src/lmem.c
r242959r242960
11/*
2** $Id: lmem.c,v 1.89 2014/11/02 19:33:33 roberto Exp $
2** $Id: lmem.c,v 1.84.1.1 2013/04/12 18:48:47 roberto Exp $
33** Interface to Memory Manager
44** See Copyright Notice in lua.h
55*/
66
7
8#include <stddef.h>
9
710#define lmem_c
811#define LUA_CORE
912
10#include "lprefix.h"
11
12
13#include <stddef.h>
14
1513#include "lua.h"
1614
1715#include "ldebug.h"
r242959r242960
2624/*
2725** About the realloc function:
2826** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
29** ('osize' is the old size, 'nsize' is the new size)
27** (`osize' is the old size, `nsize' is the new size)
3028**
31** * frealloc(ud, NULL, x, s) creates a new block of size 's' (no
29** * frealloc(ud, NULL, x, s) creates a new block of size `s' (no
3230** matter 'x').
3331**
34** * frealloc(ud, p, x, 0) frees the block 'p'
32** * frealloc(ud, p, x, 0) frees the block `p'
3533** (in this specific case, frealloc must return NULL);
3634** particularly, frealloc(ud, NULL, 0, 0) does nothing
37** (which is equivalent to free(NULL) in ISO C)
35** (which is equivalent to free(NULL) in ANSI C)
3836**
3937** frealloc returns NULL if it cannot create or reallocate the area
4038** (any reallocation to an equal or smaller size cannot fail!)
r242959r242960
8583#endif
8684  newblock = (*g->frealloc)(g->ud, block, osize, nsize);
8785  if (newblock == NULL && nsize > 0) {
88    api_check( nsize > realosize,
86    api_check(L, nsize > realosize,
8987                 "realloc cannot fail when shrinking a block");
90    luaC_fullgc(L, 1);  /* try to free some memory... */
91    newblock = (*g->frealloc)(g->ud, block, osize, nsize);  /* try again */
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    }
9292    if (newblock == NULL)
9393      luaD_throw(L, LUA_ERRMEM);
9494  }
trunk/3rdparty/lua/src/lmem.h
r242959r242960
11/*
2** $Id: lmem.h,v 1.43 2014/12/19 17:26:14 roberto Exp $
2** $Id: lmem.h,v 1.40.1.1 2013/04/12 18:48:47 roberto Exp $
33** Interface to Memory Manager
44** See Copyright Notice in lua.h
55*/
r242959r242960
1515
1616
1717/*
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.)
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".
2923*/
3024#define luaM_reallocv(L,b,on,n,e) \
31  (((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \
32      ? luaM_toobig(L) : cast_void(0)) , \
25  (cast(void, \
26     (cast(size_t, (n)+1) > MAX_SIZET/(e)) ? (luaM_toobig(L), 0) : 0), \
3327   luaM_realloc_(L, (b), (on)*(e), (n)*(e)))
3428
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
4129#define luaM_freemem(L, b, s)   luaM_realloc_(L, (b), (s), 0)
4230#define luaM_free(L, b)      luaM_realloc_(L, (b), sizeof(*(b)), 0)
43#define luaM_freearray(L, b, n)   luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0)
31#define luaM_freearray(L, b, n)   luaM_reallocv(L, (b), n, 0, sizeof((b)[0]))
4432
4533#define luaM_malloc(L,s)   luaM_realloc_(L, NULL, 0, (s))
4634#define luaM_new(L,t)      cast(t *, luaM_malloc(L, sizeof(t)))
trunk/3rdparty/lua/src/loadlib.c
r242959r242960
11/*
2** $Id: loadlib.c,v 1.124 2015/01/05 13:51:39 roberto Exp $
2** $Id: loadlib.c,v 1.111.1.1 2013/04/12 18:48:47 roberto Exp $
33** Dynamic library loader for Lua
44** See Copyright Notice in lua.h
55**
r242959r242960
88** systems.
99*/
1010
11#define loadlib_c
12#define LUA_LIB
1311
14#include "lprefix.h"
12/*
13** if needed, includes windows header before everything else
14*/
15#if defined(_WIN32)
16#include <windows.h>
17#endif
1518
1619
1720#include <stdlib.h>
1821#include <string.h>
1922
23
24#define loadlib_c
25#define LUA_LIB
26
2027#include "lua.h"
2128
2229#include "lauxlib.h"
r242959r242960
2431
2532
2633/*
27** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
34** LUA_PATH and LUA_CPATH are the names of the environment
2835** variables that Lua check to set its paths.
2936*/
30#if !defined(LUA_PATH_VAR)
31#define LUA_PATH_VAR   "LUA_PATH"
37#if !defined(LUA_PATH)
38#define LUA_PATH   "LUA_PATH"
3239#endif
3340
34#if !defined(LUA_CPATH_VAR)
35#define LUA_CPATH_VAR   "LUA_CPATH"
41#if !defined(LUA_CPATH)
42#define LUA_CPATH   "LUA_CPATH"
3643#endif
3744
3845#define LUA_PATHSUFFIX      "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
3946
40#define LUA_PATHVARVERSION      LUA_PATH_VAR LUA_PATHSUFFIX
41#define LUA_CPATHVARVERSION      LUA_CPATH_VAR LUA_PATHSUFFIX
47#define LUA_PATHVERSION      LUA_PATH LUA_PATHSUFFIX
48#define LUA_CPATHVERSION   LUA_CPATH LUA_PATHSUFFIX
4249
4350/*
4451** LUA_PATH_SEP is the character that separates templates in a path.
r242959r242960
8592#define LUA_OFSEP   "_"
8693
8794
88/*
89** unique key for table in the registry that keeps handles
90** for all loaded C libraries
91*/
92static const int CLIBS = 0;
95/* table (in the registry) that keeps handles for all loaded C libraries */
96#define CLIBS      "_CLIBS"
9397
9498#define LIB_FAIL   "open"
9599
100
101/* error codes for ll_loadfunc */
102#define ERRLIB      1
103#define ERRFUNC      2
104
96105#define setprogdir(L)      ((void)0)
97106
98107
99108/*
100109** system-dependent functions
101110*/
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);
102114
103/*
104** unload library 'lib'
105*/
106static void lsys_unloadlib (void *lib);
107115
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);
115116
117#if defined(LUA_USE_DLOPEN)
116118/*
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/*
128119** {========================================================================
129120** This is an implementation of loadlib based on the dlfcn interface.
130121** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
r242959r242960
135126
136127#include <dlfcn.h>
137128
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) {
129static void ll_unloadlib (void *lib) {
151130  dlclose(lib);
152131}
153132
154133
155static void *lsys_load (lua_State *L, const char *path, int seeglb) {
134static void *ll_load (lua_State *L, const char *path, int seeglb) {
156135  void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
157136  if (lib == NULL) lua_pushstring(L, dlerror());
158137  return lib;
159138}
160139
161140
162static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
163  lua_CFunction f = cast_func(dlsym(lib, sym));
141static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
142  lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
164143  if (f == NULL) lua_pushstring(L, dlerror());
165144  return f;
166145}
r242959r242960
169148
170149
171150
172#elif defined(LUA_DL_DLL)   /* }{ */
151#elif defined(LUA_DL_DLL)
173152/*
174153** {======================================================================
175154** This is an implementation of loadlib for Windows using native functions.
176155** =======================================================================
177156*/
178157
179#include <windows.h>
180
181158#undef setprogdir
182159
183160/*
r242959r242960
213190    lua_pushfstring(L, "system error %d\n", error);
214191}
215192
216static void lsys_unloadlib (void *lib) {
193static void ll_unloadlib (void *lib) {
217194  FreeLibrary((HMODULE)lib);
218195}
219196
220197
221static void *lsys_load (lua_State *L, const char *path, int seeglb) {
198static void *ll_load (lua_State *L, const char *path, int seeglb) {
222199  HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
223200  (void)(seeglb);  /* not used: symbols are 'global' by default */
224201  if (lib == NULL) pusherror(L);
r242959r242960
226203}
227204
228205
229static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
206static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
230207  lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym);
231208  if (f == NULL) pusherror(L);
232209  return f;
r242959r242960
235212/* }====================================================== */
236213
237214
238#else            /* }{ */
215#else
239216/*
240217** {======================================================
241218** Fallback for other systems
r242959r242960
249226#define DLMSG   "dynamic libraries not enabled; check your Lua installation"
250227
251228
252static void lsys_unloadlib (void *lib) {
229static void ll_unloadlib (void *lib) {
253230  (void)(lib);  /* not used */
254231}
255232
256233
257static void *lsys_load (lua_State *L, const char *path, int seeglb) {
234static void *ll_load (lua_State *L, const char *path, int seeglb) {
258235  (void)(path); (void)(seeglb);  /* not used */
259236  lua_pushliteral(L, DLMSG);
260237  return NULL;
261238}
262239
263240
264static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
241static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
265242  (void)(lib); (void)(sym);  /* not used */
266243  lua_pushliteral(L, DLMSG);
267244  return NULL;
268245}
269246
270247/* }====================================================== */
271#endif            /* } */
248#endif
272249
273250
274/*
275** return registry.CLIBS[path]
276*/
277static void *checkclib (lua_State *L, const char *path) {
251static void *ll_checkclib (lua_State *L, const char *path) {
278252  void *plib;
279  lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
253  lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
280254  lua_getfield(L, -1, path);
281255  plib = lua_touserdata(L, -1);  /* plib = CLIBS[path] */
282256  lua_pop(L, 2);  /* pop CLIBS table and 'plib' */
r242959r242960
284258}
285259
286260
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);
261static void ll_addtoclib (lua_State *L, const char *path, void *plib) {
262  lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
293263  lua_pushlightuserdata(L, plib);
294264  lua_pushvalue(L, -1);
295265  lua_setfield(L, -3, path);  /* CLIBS[path] = plib */
r242959r242960
299269
300270
301271/*
302** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
272** __gc tag method for CLIBS table: calls 'll_unloadlib' for all lib
303273** handles in list CLIBS
304274*/
305275static int gctm (lua_State *L) {
306  lua_Integer n = luaL_len(L, 1);
276  int n = luaL_len(L, 1);
307277  for (; n >= 1; n--) {  /* for each handle, in reverse order */
308278    lua_rawgeti(L, 1, n);  /* get handle CLIBS[n] */
309    lsys_unloadlib(lua_touserdata(L, -1));
279    ll_unloadlib(lua_touserdata(L, -1));
310280    lua_pop(L, 1);  /* pop handle */
311281  }
312282  return 0;
313283}
314284
315285
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 */
286static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
287  void *reg = ll_checkclib(L, path);  /* check loaded C libraries */
334288  if (reg == NULL) {  /* must load library? */
335    reg = lsys_load(L, path, *sym == '*');  /* global symbols if 'sym'=='*' */
289    reg = ll_load(L, path, *sym == '*');
336290    if (reg == NULL) return ERRLIB;  /* unable to load library */
337    addtoclib(L, path, reg);
291    ll_addtoclib(L, path, reg);
338292  }
339293  if (*sym == '*') {  /* loading only library (no function)? */
340294    lua_pushboolean(L, 1);  /* return 'true' */
341295    return 0;  /* no errors */
342296  }
343297  else {
344    lua_CFunction f = lsys_sym(L, reg, sym);
298    lua_CFunction f = ll_sym(L, reg, sym);
345299    if (f == NULL)
346300      return ERRFUNC;  /* unable to find function */
347301    lua_pushcfunction(L, f);  /* else create new function */
r242959r242960
353307static int ll_loadlib (lua_State *L) {
354308  const char *path = luaL_checkstring(L, 1);
355309  const char *init = luaL_checkstring(L, 2);
356  int stat = lookforfunc(L, path, init);
310  int stat = ll_loadfunc(L, path, init);
357311  if (stat == 0)  /* no errors? */
358312    return 1;  /* return the loaded function */
359313  else {  /* error; error message is on stack top */
r242959r242960
406360    lua_remove(L, -2);  /* remove path template */
407361    if (readable(filename))  /* does file exist and is readable? */
408362      return filename;  /* return that file name */
409    lua_pushfstring(L, "\n\tno file '%s'", filename);
363    lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
410364    lua_remove(L, -2);  /* remove file name */
411365    luaL_addvalue(&msg);  /* concatenate error msg. entry */
412366  }
r242959r242960
436390  lua_getfield(L, lua_upvalueindex(1), pname);
437391  path = lua_tostring(L, -1);
438392  if (path == NULL)
439    luaL_error(L, "'package.%s' must be a string", pname);
393    luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
440394  return searchpath(L, name, path, ".", dirsep);
441395}
442396
r242959r242960
447401    return 2;  /* return open function and file name */
448402  }
449403  else
450    return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
404    return luaL_error(L, "error loading module " LUA_QS
405                         " from file " LUA_QS ":\n\t%s",
451406                          lua_tostring(L, 1), filename, lua_tostring(L, -1));
452407}
453408
r242959r242960
461416}
462417
463418
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*/
472419static int loadfunc (lua_State *L, const char *filename, const char *modname) {
473  const char *openfunc;
420  const char *funcname;
474421  const char *mark;
475422  modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
476423  mark = strchr(modname, *LUA_IGMARK);
477424  if (mark) {
478425    int stat;
479    openfunc = lua_pushlstring(L, modname, mark - modname);
480    openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
481    stat = lookforfunc(L, filename, openfunc);
426    funcname = lua_pushlstring(L, modname, mark - modname);
427    funcname = lua_pushfstring(L, LUA_POF"%s", funcname);
428    stat = ll_loadfunc(L, filename, funcname);
482429    if (stat != ERRFUNC) return stat;
483430    modname = mark + 1;  /* else go ahead and try old-style name */
484431  }
485  openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
486  return lookforfunc(L, filename, openfunc);
432  funcname = lua_pushfstring(L, LUA_POF"%s", modname);
433  return ll_loadfunc(L, filename, funcname);
487434}
488435
489436
r242959r242960
508455    if (stat != ERRFUNC)
509456      return checkload(L, 0, filename);  /* real error */
510457    else {  /* open function not found */
511      lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename);
458      lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
459                         name, filename);
512460      return 1;
513461    }
514462  }
r242959r242960
520468static int searcher_preload (lua_State *L) {
521469  const char *name = luaL_checkstring(L, 1);
522470  lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
523  if (lua_getfield(L, -1, name) == LUA_TNIL)  /* not found? */
471  lua_getfield(L, -1, name);
472  if (lua_isnil(L, -1))  /* not found? */
524473    lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
525474  return 1;
526475}
r242959r242960
530479  int i;
531480  luaL_Buffer msg;  /* to build error message */
532481  luaL_buffinit(L, &msg);
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");
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");
536485  /*  iterate over available searchers to find a loader */
537486  for (i = 1; ; i++) {
538    if (lua_rawgeti(L, 3, i) == LUA_TNIL) {  /* no more searchers? */
487    lua_rawgeti(L, 3, i);  /* get a searcher */
488    if (lua_isnil(L, -1)) {  /* no more searchers? */
539489      lua_pop(L, 1);  /* remove nil */
540490      luaL_pushresult(&msg);  /* create error message */
541      luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
491      luaL_error(L, "module " LUA_QS " not found:%s",
492                    name, lua_tostring(L, -1));
542493    }
543494    lua_pushstring(L, name);
544495    lua_call(L, 1, 2);  /* call it */
r242959r242960
569520  lua_call(L, 2, 1);  /* run loader to load module */
570521  if (!lua_isnil(L, -1))  /* non-nil return? */
571522    lua_setfield(L, 2, name);  /* _LOADED[name] = returned value */
572  if (lua_getfield(L, 2, name) == LUA_TNIL) {   /* module set no value? */
523  lua_getfield(L, 2, name);
524  if (lua_isnil(L, -1)) {   /* module did not set a value? */
573525    lua_pushboolean(L, 1);  /* use true as result */
574526    lua_pushvalue(L, -1);  /* extra copy to be returned */
575527    lua_setfield(L, 2, name);  /* _LOADED[name] = true */
r242959r242960
596548  if (lua_getstack(L, 1, &ar) == 0 ||
597549      lua_getinfo(L, "f", &ar) == 0 ||  /* get calling function */
598550      lua_iscfunction(L, -1))
599    luaL_error(L, "'module' not called from a Lua function");
551    luaL_error(L, LUA_QL("module") " not called from a Lua function");
600552  lua_pushvalue(L, -2);  /* copy new environment table to top */
601553  lua_setupvalue(L, -2, 1);
602554  lua_pop(L, 1);  /* remove function */
r242959r242960
635587  int lastarg = lua_gettop(L);  /* last parameter */
636588  luaL_pushmodule(L, modname, 1);  /* get/create module table */
637589  /* check whether table already has a _NAME field */
638  if (lua_getfield(L, -1, "_NAME") != LUA_TNIL)
639    lua_pop(L, 1);  /* table is an initialized module */
590  lua_getfield(L, -1, "_NAME");
591  if (!lua_isnil(L, -1))  /* is table an initialized module? */
592    lua_pop(L, 1);
640593  else {  /* no; initialize it */
641594    lua_pop(L, 1);
642595    modinit(L, modname);
r242959r242960
706659#if defined(LUA_COMPAT_MODULE)
707660  {"seeall", ll_seeall},
708661#endif
709  /* placeholders */
710  {"preload", NULL},
711  {"cpath", NULL},
712  {"path", NULL},
713  {"searchers", NULL},
714  {"loaded", NULL},
715662  {NULL, NULL}
716663};
717664
r242959r242960
737684    lua_pushcclosure(L, searchers[i], 1);
738685    lua_rawseti(L, -2, i+1);
739686  }
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' */
745687}
746688
747689
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 */
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 */
755694  lua_pushcfunction(L, gctm);
756695  lua_setfield(L, -2, "__gc");  /* set finalizer for CLIBS table */
757696  lua_setmetatable(L, -2);
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 */
697  /* create `package' table */
698  luaL_newlib(L, pk_funcs);
765699  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' */
766705  /* set field 'path' */
767  setpath(L, "path", LUA_PATHVARVERSION, LUA_PATH_VAR, LUA_PATH_DEFAULT);
706  setpath(L, "path", LUA_PATHVERSION, LUA_PATH, LUA_PATH_DEFAULT);
768707  /* set field 'cpath' */
769  setpath(L, "cpath", LUA_CPATHVARVERSION, LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
708  setpath(L, "cpath", LUA_CPATHVERSION, LUA_CPATH, LUA_CPATH_DEFAULT);
770709  /* store config information */
771710  lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
772711                     LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
773712  lua_setfield(L, -2, "config");
774  /* set field 'loaded' */
713  /* set field `loaded' */
775714  luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
776715  lua_setfield(L, -2, "loaded");
777  /* set field 'preload' */
716  /* set field `preload' */
778717  luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
779718  lua_setfield(L, -2, "preload");
780719  lua_pushglobaltable(L);
trunk/3rdparty/lua/src/lobject.c
r242959r242960
11/*
2** $Id: lobject.c,v 2.101 2014/12/26 14:43:45 roberto Exp $
2** $Id: lobject.c,v 2.58.1.1 2013/04/12 18:48:47 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
137#include <stdarg.h>
148#include <stdio.h>
159#include <stdlib.h>
1610#include <string.h>
1711
12#define lobject_c
13#define LUA_CORE
14
1815#include "lua.h"
1916
2017#include "lctype.h"
r242959r242960
7370}
7471
7572
76static lua_Integer intarith (lua_State *L, int op, lua_Integer v1,
77                                                   lua_Integer v2) {
73lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) {
7874  switch (op) {
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);
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);
9182    default: lua_assert(0); return 0;
9283  }
9384}
9485
9586
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
15687int luaO_hexavalue (int c) {
15788  if (lisdigit(c)) return c - '0';
15889  else return ltolower(c) - 'a' + 10;
15990}
16091
16192
93#if !defined(lua_strx2number)
94
95#include <math.h>
96
97
16298static int isneg (const char **s) {
16399  if (**s == '-') { (*s)++; return 1; }
164100  else if (**s == '+') (*s)++;
r242959r242960
166102}
167103
168104
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}
169112
170/*
171** {==================================================================
172** Lua's implementation for 'lua_strx2number'
173** ===================================================================
174*/
175#if !defined(lua_strx2number)
176113
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
183114/*
184115** convert an hexadecimal numeric string to a number, following
185116** C99 specification for 'strtod'
186117*/
187118static lua_Number lua_strx2number (const char *s, char **endptr) {
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 */
119  lua_Number r = 0.0;
120  int e = 0, i = 0;
121  int neg = 0;  /* 1 if number is negative */
194122  *endptr = cast(char *, s);  /* nothing is valid yet */
195123  while (lisspace(cast_uchar(*s))) s++;  /* skip initial spaces */
196124  neg = isneg(&s);  /* check signal */
197125  if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X')))  /* check '0x' */
198126    return 0.0;  /* invalid format (no '0x') */
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 */
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 */
213132  }
214  if (nosigdig + sigdig == 0)  /* no digits? */
215    return 0.0;  /* invalid format */
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 */
216136  *endptr = cast(char *, s);  /* valid up to here */
217  e *= 4;  /* each digit multiplies/divides value by 2^4 */
218137  if (*s == 'p' || *s == 'P') {  /* exponent part? */
219    int exp1 = 0;  /* exponent value */
220    int neg1;  /* exponent signal */
138    int exp1 = 0;
139    int neg1;
221140    s++;  /* skip 'p' */
222141    neg1 = isneg(&s);  /* signal */
223142    if (!lisdigit(cast_uchar(*s)))
224      return 0.0;  /* invalid; must have at least one digit */
143      goto ret;  /* must have at least one digit */
225144    while (lisdigit(cast_uchar(*s)))  /* read exponent */
226145      exp1 = exp1 * 10 + *(s++) - '0';
227146    if (neg1) exp1 = -exp1;
228147    e += exp1;
229    *endptr = cast(char *, s);  /* valid up to here */
230148  }
149  *endptr = cast(char *, s);  /* valid up to here */
150 ret:
231151  if (neg) r = -r;
232152  return l_mathop(ldexp)(r, e);
233153}
234154
235155#endif
236/* }====================================================== */
237156
238157
239static const char *l_str2d (const char *s, lua_Number *result) {
158int luaO_str2d (const char *s, size_t len, lua_Number *result) {
240159  char *endptr;
241160  if (strpbrk(s, "nN"))  /* reject 'inf' and 'nan' */
242    return NULL;
243  else if (strpbrk(s, "xX"))  /* hex? */
161    return 0;
162  else if (strpbrk(s, "xX"))  /* hexa? */
244163    *result = lua_strx2number(s, &endptr);
245164  else
246165    *result = lua_str2number(s, &endptr);
247166  if (endptr == s) return 0;  /* nothing recognized */
248167  while (lisspace(cast_uchar(*endptr))) endptr++;
249  return (*endptr == '\0' ? endptr : NULL);  /* OK if no trailing characters */
168  return (endptr == s + len);  /* OK if no trailing characters */
250169}
251170
252171
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}
280172
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
341173static void pushstr (lua_State *L, const char *str, size_t l) {
342174  setsvalue2s(L, L->top++, luaS_newlstr(L, str, l));
343175}
344176
345177
346/* this function handles only '%d', '%c', '%f', '%p', and '%s'
347   conventional formats, plus Lua-specific '%I' and '%U' */
178/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
348179const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
349180  int n = 0;
350181  for (;;) {
r242959r242960
360191        break;
361192      }
362193      case 'c': {
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));
194        char buff;
195        buff = cast(char, va_arg(argp, int));
196        pushstr(L, &buff, 1);
368197        break;
369198      }
370199      case 'd': {
371        setivalue(L->top++, va_arg(argp, int));
372        luaO_tostring(L, L->top - 1);
200        setnvalue(L->top++, cast_num(va_arg(argp, int)));
373201        break;
374202      }
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      }
380203      case 'f': {
381        setfltvalue(L->top++, cast_num(va_arg(argp, l_uacNumber)));
382        luaO_tostring(L, L->top - 1);
204        setnvalue(L->top++, cast_num(va_arg(argp, l_uacNumber)));
383205        break;
384206      }
385207      case 'p': {
386        char buff[4*sizeof(void *) + 8]; /* should be enough space for a '%p' */
208        char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
387209        int l = sprintf(buff, "%p", va_arg(argp, void *));
388210        pushstr(L, buff, l);
389211        break;
390212      }
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      }
397213      case '%': {
398214        pushstr(L, "%", 1);
399215        break;
400216      }
401217      default: {
402        luaG_runerror(L, "invalid option '%%%c' to 'lua_pushfstring'",
403                         *(e + 1));
218        luaG_runerror(L,
219            "invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"),
220            *(e + 1));
404221      }
405222    }
406223    n += 2;
trunk/3rdparty/lua/src/lobject.h
r242959r242960
11/*
2** $Id: lobject.h,v 2.106 2015/01/05 13:52:37 roberto Exp $
2** $Id: lobject.h,v 2.71.1.1 2013/04/12 18:48:47 roberto Exp $
33** Type definitions for Lua objects
44** See Copyright Notice in lua.h
55*/
r242959r242960
2020** Extra tags for non-values
2121*/
2222#define LUA_TPROTO   LUA_NUMTAGS
23#define LUA_TDEADKEY   (LUA_NUMTAGS+1)
23#define LUA_TUPVAL   (LUA_NUMTAGS+1)
24#define LUA_TDEADKEY   (LUA_NUMTAGS+2)
2425
2526/*
2627** number of all possible tags (including LUA_TNONE but excluding DEADKEY)
2728*/
28#define LUA_TOTALTAGS   (LUA_TPROTO + 2)
29#define LUA_TOTALTAGS   (LUA_TUPVAL+2)
2930
3031
3132/*
r242959r242960
5657#define LUA_TLNGSTR   (LUA_TSTRING | (1 << 4))  /* long strings */
5758
5859
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
6460/* Bit mark for collectable types */
6561#define BIT_ISCOLLECTABLE   (1 << 6)
6662
r242959r242960
6965
7066
7167/*
72** Common type for all collectable objects
68** Union of all collectable objects
7369*/
74typedef struct GCObject GCObject;
70typedef union GCObject GCObject;
7571
7672
7773/*
r242959r242960
8278
8379
8480/*
85** Common type has only the common header
81** Common header in struct form
8682*/
87struct GCObject {
83typedef struct GCheader {
8884  CommonHeader;
89};
85} GCheader;
9086
9187
9288
r242959r242960
9692typedef union Value Value;
9793
9894
95#define numfield   lua_Number n;    /* numbers */
9996
10097
98
10199/*
102100** Tagged Values. This is the basic representation of values in Lua,
103101** an actual value plus a tag with its type.
r242959r242960
113111
114112
115113#define val_(o)      ((o)->value_)
114#define num_(o)      (val_(o).n)
116115
117116
118117/* raw type tag of a TValue */
r242959r242960
125124#define ttype(o)   (rttype(o) & 0x3F)
126125
127126/* type tag of a TValue with no variants (bits 0-3) */
128#define ttnov(o)   (novariant(rttype(o)))
127#define ttypenv(o)   (novariant(rttype(o)))
129128
130129
131130/* Macros to test type */
132131#define checktag(o,t)      (rttype(o) == (t))
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)
132#define checktype(o,t)      (ttypenv(o) == (t))
133#define ttisnumber(o)      checktag((o), LUA_TNUMBER)
137134#define ttisnil(o)      checktag((o), LUA_TNIL)
138135#define ttisboolean(o)      checktag((o), LUA_TBOOLEAN)
139136#define ttislightuserdata(o)   checktag((o), LUA_TLIGHTUSERDATA)
r242959r242960
146143#define ttisCclosure(o)      checktag((o), ctb(LUA_TCCL))
147144#define ttisLclosure(o)      checktag((o), ctb(LUA_TLCL))
148145#define ttislcf(o)      checktag((o), LUA_TLCF)
149#define ttisfulluserdata(o)   checktag((o), ctb(LUA_TUSERDATA))
146#define ttisuserdata(o)      checktag((o), ctb(LUA_TUSERDATA))
150147#define ttisthread(o)      checktag((o), ctb(LUA_TTHREAD))
151148#define ttisdeadkey(o)      checktag((o), LUA_TDEADKEY)
152149
150#define ttisequal(o1,o2)   (rttype(o1) == rttype(o2))
153151
154152/* Macros to access values */
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)))
153#define nvalue(o)   check_exp(ttisnumber(o), num_(o))
159154#define gcvalue(o)   check_exp(iscollectable(o), val_(o).gc)
160155#define pvalue(o)   check_exp(ttislightuserdata(o), val_(o).p)
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))
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)
166163#define fvalue(o)   check_exp(ttislcf(o), val_(o).f)
167#define hvalue(o)   check_exp(ttistable(o), gco2t(val_(o).gc))
164#define hvalue(o)   check_exp(ttistable(o), &val_(o).gc->h)
168165#define bvalue(o)   check_exp(ttisboolean(o), val_(o).b)
169#define thvalue(o)   check_exp(ttisthread(o), gco2th(val_(o).gc))
166#define thvalue(o)   check_exp(ttisthread(o), &val_(o).gc->th)
170167/* a dead value may get the 'gc' field, but cannot access its contents */
171168#define deadvalue(o)   check_exp(ttisdeadkey(o), cast(void *, val_(o).gc))
172169
r242959r242960
177174
178175
179176/* Macros for internal tests */
180#define righttt(obj)      (ttype(obj) == gcvalue(obj)->tt)
177#define righttt(obj)      (ttype(obj) == gcvalue(obj)->gch.tt)
181178
182179#define checkliveness(g,obj) \
183180   lua_longassert(!iscollectable(obj) || \
r242959r242960
187184/* Macros to set values */
188185#define settt_(o,t)   ((o)->tt_=(t))
189186
190#define setfltvalue(obj,x) \
191  { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_TNUMFLT); }
187#define setnvalue(obj,x) \
188  { TValue *io=(obj); num_(io)=(x); settt_(io, LUA_TNUMBER); }
192189
193#define setivalue(obj,x) \
194  { TValue *io=(obj); val_(io).i=(x); settt_(io, LUA_TNUMINT); }
195
196190#define setnilvalue(obj) settt_(obj, LUA_TNIL)
197191
198192#define setfvalue(obj,x) \
r242959r242960
205199  { TValue *io=(obj); val_(io).b=(x); settt_(io, LUA_TBOOLEAN); }
206200
207201#define setgcovalue(L,obj,x) \
208  { TValue *io = (obj); GCObject *i_g=(x); \
209    val_(io).gc = i_g; settt_(io, ctb(i_g->tt)); }
202  { TValue *io=(obj); GCObject *i_g=(x); \
203    val_(io).gc=i_g; settt_(io, ctb(gch(i_g)->tt)); }
210204
211205#define setsvalue(L,obj,x) \
212  { TValue *io = (obj); TString *x_ = (x); \
213    val_(io).gc = obj2gco(x_); settt_(io, ctb(x_->tt)); \
206  { TValue *io=(obj); \
207    TString *x_ = (x); \
208    val_(io).gc=cast(GCObject *, x_); settt_(io, ctb(x_->tsv.tt)); \
214209    checkliveness(G(L),io); }
215210
216211#define setuvalue(L,obj,x) \
217  { TValue *io = (obj); Udata *x_ = (x); \
218    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TUSERDATA)); \
212  { TValue *io=(obj); \
213    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TUSERDATA)); \
219214    checkliveness(G(L),io); }
220215
221216#define setthvalue(L,obj,x) \
222  { TValue *io = (obj); lua_State *x_ = (x); \
223    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTHREAD)); \
217  { TValue *io=(obj); \
218    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTHREAD)); \
224219    checkliveness(G(L),io); }
225220
226221#define setclLvalue(L,obj,x) \
227  { TValue *io = (obj); LClosure *x_ = (x); \
228    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TLCL)); \
222  { TValue *io=(obj); \
223    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TLCL)); \
229224    checkliveness(G(L),io); }
230225
231226#define setclCvalue(L,obj,x) \
232  { TValue *io = (obj); CClosure *x_ = (x); \
233    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TCCL)); \
227  { TValue *io=(obj); \
228    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TCCL)); \
234229    checkliveness(G(L),io); }
235230
236231#define sethvalue(L,obj,x) \
237  { TValue *io = (obj); Table *x_ = (x); \
238    val_(io).gc = obj2gco(x_); settt_(io, ctb(LUA_TTABLE)); \
232  { TValue *io=(obj); \
233    val_(io).gc=cast(GCObject *, (x)); settt_(io, ctb(LUA_TTABLE)); \
239234    checkliveness(G(L),io); }
240235
241236#define setdeadvalue(obj)   settt_(obj, LUA_TDEADKEY)
r242959r242960
243238
244239
245240#define setobj(L,obj1,obj2) \
246   { TValue *io1=(obj1); *io1 = *(obj2); \
247     (void)L; checkliveness(G(L),io1); }
241   { const TValue *io2=(obj2); TValue *io1=(obj1); \
242     io1->value_ = io2->value_; io1->tt_ = io2->tt_; \
243     checkliveness(G(L),io1); }
248244
249245
250246/*
r242959r242960
267263#define setsvalue2n   setsvalue
268264
269265
266/* check whether a number is valid (useful only for NaN trick) */
267#define luai_checknum(L,o,c)   { /* empty */ }
270268
271269
272270/*
273271** {======================================================
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** {======================================================
274383** types and prototypes
275384** =======================================================
276385*/
r242959r242960
281390  void *p;         /* light userdata */
282391  int b;           /* booleans */
283392  lua_CFunction f; /* light C functions */
284  lua_Integer i;   /* integer numbers */
285  lua_Number n;    /* float numbers */
393  numfield         /* numbers */
286394};
287395
288396
r242959r242960
298406
299407/*
300408** Header for string value; string bytes follow the end of this structure
301** (aligned according to 'UTString'; see next).
302409*/
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 */
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;
309418} TString;
310419
311420
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;
421/* get the actual string (array of bytes) from a TString */
422#define getstr(ts)   cast(const char *, (ts) + 1)
319423
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
329424/* get the actual string (array of bytes) from a Lua value */
330#define svalue(o)       getstr(tsvalue(o))
425#define svalue(o)       getstr(rawtsvalue(o))
331426
332427
333428/*
334429** Header for userdata; memory area follows the end of this structure
335** (aligned according to 'UUdata'; see next).
336430*/
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 */
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;
343439} Udata;
344440
345441
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;
353442
354
355443/*
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/*
375444** Description of an upvalue for function prototypes
376445*/
377446typedef struct Upvaldesc {
r242959r242960
397466*/
398467typedef struct Proto {
399468  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;
411469  TValue *k;  /* constants used by the function */
412470  Instruction *code;
413471  struct Proto **p;  /* functions defined inside the function */
414472  int *lineinfo;  /* map from opcodes to source lines (debug information) */
415473  LocVar *locvars;  /* information about local variables (debug information) */
416474  Upvaldesc *upvalues;  /* upvalue information */
417  struct LClosure *cache;  /* last created closure with this prototype */
475  union Closure *cache;  /* last created closure with this prototype */
418476  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;
419485  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 */
420489} Proto;
421490
422491
r242959r242960
424493/*
425494** Lua Upvalues
426495*/
427typedef struct UpVal UpVal;
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;
428507
429508
430509/*
r242959r242960
466545typedef union TKey {
467546  struct {
468547    TValuefields;
469    int next;  /* for chaining (offset for next node) */
548    struct Node *next;  /* for chaining */
470549  } nk;
471550  TValue tvk;
472551} TKey;
473552
474553
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
482554typedef struct Node {
483555  TValue i_val;
484556  TKey i_key;
r242959r242960
488560typedef struct Table {
489561  CommonHeader;
490562  lu_byte flags;  /* 1<<p means tagmethod(p) is not present */
491  lu_byte lsizenode;  /* log2 of size of 'node' array */
492  unsigned int sizearray;  /* size of 'array' array */
563  lu_byte lsizenode;  /* log2 of size of `node' array */
564  struct Table *metatable;
493565  TValue *array;  /* array part */
494566  Node *node;
495567  Node *lastfree;  /* any free position is before this position */
496  struct Table *metatable;
497568  GCObject *gclist;
569  int sizearray;  /* size of `array' array */
498570} Table;
499571
500572
501573
502574/*
503** 'module' operation for hashing (size is always a power of 2)
575** `module' operation for hashing (size is always a power of 2)
504576*/
505577#define lmod(s,size) \
506578   (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1)))))
r242959r242960
518590
519591LUAI_DDEC const TValue luaO_nilobject_;
520592
521/* size of buffer for 'luaO_utf8esc' function */
522#define UTF8BUFFSZ   8
523593
524594LUAI_FUNC int luaO_int2fb (unsigned int x);
525595LUAI_FUNC int luaO_fb2int (int x);
526LUAI_FUNC int luaO_utf8esc (char *buff, unsigned long x);
527596LUAI_FUNC int luaO_ceillog2 (unsigned int x);
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);
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);
531599LUAI_FUNC int luaO_hexavalue (int c);
532LUAI_FUNC void luaO_tostring (lua_State *L, StkId obj);
533600LUAI_FUNC const char *luaO_pushvfstring (lua_State *L, const char *fmt,
534601                                                       va_list argp);
535602LUAI_FUNC const char *luaO_pushfstring (lua_State *L, const char *fmt, ...);
trunk/3rdparty/lua/src/lopcodes.c
r242959r242960
11/*
2** $Id: lopcodes.c,v 1.55 2015/01/05 13:48:33 roberto Exp $
2** $Id: lopcodes.c,v 1.49.1.1 2013/04/12 18:48:47 roberto Exp $
33** Opcodes for Lua virtual machine
44** See Copyright Notice in lua.h
55*/
66
7
78#define lopcodes_c
89#define LUA_CORE
910
10#include "lprefix.h"
1111
12
13#include <stddef.h>
14
1512#include "lopcodes.h"
1613
1714
r242959r242960
3431  "ADD",
3532  "SUB",
3633  "MUL",
34  "DIV",
3735  "MOD",
3836  "POW",
39  "DIV",
40  "IDIV",
41  "BAND",
42  "BOR",
43  "BXOR",
44  "SHL",
45  "SHR",
4637  "UNM",
47  "BNOT",
4838  "NOT",
4939  "LEN",
5040  "CONCAT",
r242959r242960
8979 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_ADD */
9080 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_SUB */
9181 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_MUL */
82 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_DIV */
9283 ,opmode(0, 1, OpArgK, OpArgK, iABC)      /* OP_MOD */
9384 ,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 */
10185 ,opmode(0, 1, OpArgR, OpArgN, iABC)      /* OP_UNM */
102 ,opmode(0, 1, OpArgR, OpArgN, iABC)      /* OP_BNOT */
10386 ,opmode(0, 1, OpArgR, OpArgN, iABC)      /* OP_NOT */
10487 ,opmode(0, 1, OpArgR, OpArgN, iABC)      /* OP_LEN */
10588 ,opmode(0, 1, OpArgR, OpArgR, iABC)      /* OP_CONCAT */
trunk/3rdparty/lua/src/lopcodes.h
r242959r242960
11/*
2** $Id: lopcodes.h,v 1.148 2014/10/25 11:50:46 roberto Exp $
2** $Id: lopcodes.h,v 1.142.1.1 2013/04/12 18:48:47 roberto Exp $
33** Opcodes for Lua virtual machine
44** See Copyright Notice in lua.h
55*/
r242959r242960
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
r242959r242960
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
r242959r242960
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/*
r242959r242960
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)            */
190191OP_MOD,/*   A B C   R(A) := RK(B) % RK(C)            */
191192OP_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)            */
199193OP_UNM,/*   A B   R(A) := -R(B)               */
200OP_BNOT,/*   A B   R(A) := ~R(B)               */
201194OP_NOT,/*   A B   R(A) := not R(B)            */
202195OP_LEN,/*   A B   R(A) := length of R(B)            */
203196
204197OP_CONCAT,/*   A B C   R(A) := R(B).. ... ..R(C)         */
205198
206OP_JMP,/*   A sBx   pc+=sBx; if (A) close all upvalues >= R(A - 1)   */
199OP_JMP,/*   A sBx   pc+=sBx; if (A) close all upvalues >= R(A) + 1   */
207200OP_EQ,/*   A B C   if ((RK(B) == RK(C)) ~= A) then pc++      */
208201OP_LT,/*   A B C   if ((RK(B) <  RK(C)) ~= A) then pc++      */
209202OP_LE,/*   A B C   if ((RK(B) <= RK(C)) ~= A) then pc++      */
r242959r242960
238231
239232/*===========================================================================
240233  Notes:
241  (*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then 'top' is
234  (*) In OP_CALL, if (B == 0) then B = top. If (C == 0), then `top' is
242235  set to last_result+1, so next open instruction (OP_CALL, OP_RETURN,
243  OP_SETLIST) may use 'top'.
236  OP_SETLIST) may use `top'.
244237
245238  (*) In OP_VARARG, if (B == 0) then use actual number of varargs and
246239  set top (like in OP_CALL with C == 0).
247240
248  (*) In OP_RETURN, if (B == 0) then return up to 'top'.
241  (*) In OP_RETURN, if (B == 0) then return up to `top'.
249242
250  (*) In OP_SETLIST, if (B == 0) then B = 'top'; if (C == 0) then next
243  (*) In OP_SETLIST, if (B == 0) then B = `top'; if (C == 0) then next
251244  'instruction' is EXTRAARG(real C).
252245
253246  (*) In OP_LOADKX, the next 'instruction' is always EXTRAARG.
r242959r242960
255248  (*) For comparisons, A specifies what condition the test should accept
256249  (true or false).
257250
258  (*) All 'skips' (pc++) assume that next instruction is a jump.
251  (*) All `skips' (pc++) assume that next instruction is a jump.
259252
260253===========================================================================*/
261254
trunk/3rdparty/lua/src/loslib.c
r242959r242960
11/*
2** $Id: loslib.c,v 1.54 2014/12/26 14:46:07 roberto Exp $
2** $Id: loslib.c,v 1.40.1.1 2013/04/12 18:48:47 roberto Exp $
33** Standard Operating System library
44** See Copyright Notice in lua.h
55*/
66
7#define loslib_c
8#define LUA_LIB
97
10#include "lprefix.h"
11
12
138#include <errno.h>
149#include <locale.h>
1510#include <stdlib.h>
1611#include <string.h>
1712#include <time.h>
1813
14#define loslib_c
15#define LUA_LIB
16
1917#include "lua.h"
2018
2119#include "lauxlib.h"
2220#include "lualib.h"
2321
2422
25#if !defined(LUA_STRFTIMEOPTIONS)   /* { */
2623/*
2724** list of valid conversion specifiers for the 'strftime' function
2825*/
26#if !defined(LUA_STRFTIMEOPTIONS)
2927
30#if defined(LUA_USE_C89)
28#if !defined(LUA_USE_POSIX)
3129#define LUA_STRFTIMEOPTIONS   { "aAbBcdHIjmMpSUwWxXyYz%", "" }
32#else  /* C99 specification */
30#else
3331#define LUA_STRFTIMEOPTIONS \
34   { "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "", \
35     "E", "cCxXyY",  \
32   { "aAbBcCdDeFgGhHIjmMnprRStTuUVwWxXyYzZ%", "" \
33     "", "E", "cCxXyY",  \
3634     "O", "deHImMSuUVwWy" }
3735#endif
3836
39#endif               /* } */
37#endif
4038
4139
4240
43#if !defined(l_time_t)      /* { */
4441/*
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/*
5742** By default, Lua uses tmpnam except when POSIX is available, where it
5843** uses mkstemp.
5944*/
60
61#if defined(LUA_USE_POSIX)   /* { */
62
45#if defined(LUA_USE_MKSTEMP)
6346#include <unistd.h>
64
6547#define LUA_TMPNAMBUFSIZE   32
66
67#if !defined(LUA_TMPNAMTEMPLATE)
68#define LUA_TMPNAMTEMPLATE   "/tmp/lua_XXXXXX"
69#endif
70
7148#define lua_tmpnam(b,e) { \
72        strcpy(b, LUA_TMPNAMTEMPLATE); \
49        strcpy(b, "/tmp/lua_XXXXXX"); \
7350        e = mkstemp(b); \
7451        if (e != -1) close(e); \
7552        e = (e == -1); }
7653
77#else            /* }{ */
54#elif !defined(lua_tmpnam)
7855
79/* ISO C definitions */
8056#define LUA_TMPNAMBUFSIZE   L_tmpnam
8157#define lua_tmpnam(b,e)      { e = (tmpnam(b) == NULL); }
8258
83#endif            /* } */
59#endif
8460
85#endif            /* } */
8661
87
88
89#if !defined(l_gmtime)      /* { */
9062/*
9163** By default, Lua uses gmtime/localtime, except when POSIX is available,
9264** where it uses gmtime_r/localtime_r
9365*/
66#if defined(LUA_USE_GMTIME_R)
9467
95#if defined(LUA_USE_POSIX)   /* { */
96
9768#define l_gmtime(t,r)      gmtime_r(t,r)
9869#define l_localtime(t,r)   localtime_r(t,r)
9970
100#else            /* }{ */
71#elif !defined(l_gmtime)
10172
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))
73#define l_gmtime(t,r)      ((void)r, gmtime(t))
74#define l_localtime(t,r)     ((void)r, localtime(t))
10575
106#endif            /* } */
76#endif
10777
108#endif            /* } */
10978
11079
111
11280static int os_execute (lua_State *L) {
11381  const char *cmd = luaL_optstring(L, 1, NULL);
11482  int stat = system(cmd);
r242959r242960
152120
153121
154122static int os_clock (lua_State *L) {
155  lua_pushnumber(L, ((lua_Number)(int)clock())/(lua_Number)CLOCKS_PER_SEC);
123  lua_pushnumber(L, ((lua_Number)(1.0*clock()))/(lua_Number)CLOCKS_PER_SEC);
156124  return 1;
157125}
158126
r242959r242960
179147
180148static int getboolfield (lua_State *L, const char *key) {
181149  int res;
182  res = (lua_getfield(L, -1, key) == LUA_TNIL) ? -1 : lua_toboolean(L, -1);
150  lua_getfield(L, -1, key);
151  res = lua_isnil(L, -1) ? -1 : lua_toboolean(L, -1);
183152  lua_pop(L, 1);
184153  return res;
185154}
r242959r242960
191160  res = (int)lua_tointegerx(L, -1, &isnum);
192161  if (!isnum) {
193162    if (d < 0)
194      return luaL_error(L, "field '%s' missing in date table", key);
163      return luaL_error(L, "field " LUA_QS " missing in date table", key);
195164    res = d;
196165  }
197166  lua_pop(L, 1);
r242959r242960
225194
226195static int os_date (lua_State *L) {
227196  const char *s = luaL_optstring(L, 1, "%c");
228  time_t t = luaL_opt(L, l_checktime, 2, time(NULL));
197  time_t t = luaL_opt(L, luaL_checknumber, 2, time(NULL));
229198  struct tm tmr, *stm;
230199  if (*s == '!') {  /* UTC? */
231200    stm = l_gmtime(&t, &tmr);
232    s++;  /* skip '!' */
201    s++;  /* skip `!' */
233202  }
234203  else
235204    stm = l_localtime(&t, &tmr);
r242959r242960
286255    ts.tm_isdst = getboolfield(L, "isdst");
287256    t = mktime(&ts);
288257  }
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))
258  if (t == (time_t)(-1))
292259    lua_pushnil(L);
293260  else
294    l_pushtime(L, t);
261    lua_pushnumber(L, (lua_Number)t);
295262  return 1;
296263}
297264
298265
299266static int os_difftime (lua_State *L) {
300  double res = difftime((l_checktime(L, 1)), (l_checktime(L, 2)));
301  lua_pushnumber(L, (lua_Number)res);
267  lua_pushnumber(L, difftime((luaL_checknumber(L, 1)),
268                             (luaL_optnumber(L, 2, 0))));
302269  return 1;
303270}
304271
r242959r242960
322289  if (lua_isboolean(L, 1))
323290    status = (lua_toboolean(L, 1) ? EXIT_SUCCESS : EXIT_FAILURE);
324291  else
325    status = (int)luaL_optinteger(L, 1, EXIT_SUCCESS);
292    status = luaL_optint(L, 1, EXIT_SUCCESS);
326293  if (lua_toboolean(L, 2))
327294    lua_close(L);
328295  if (L) exit(status);  /* 'if' to avoid warnings for unreachable 'return' */
trunk/3rdparty/lua/src/lparser.c
r242959r242960
11/*
2** $Id: lparser.c,v 2.147 2014/12/27 20:31:43 roberto Exp $
2** $Id: lparser.c,v 2.130.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lua Parser
44** See Copyright Notice in lua.h
55*/
66
7#define lparser_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
138#include <string.h>
149
10#define lparser_c
11#define LUA_CORE
12
1513#include "lua.h"
1614
1715#include "lcode.h"
r242959r242960
3735#define hasmultret(k)      ((k) == VCALL || (k) == VVARARG)
3836
3937
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))
4338
44
4539/*
4640** nodes for block list (list of active blocks)
4741*/
4842typedef struct BlockCnt {
4943  struct BlockCnt *previous;  /* chain */
50  int firstlabel;  /* index of first label in this block */
51  int firstgoto;  /* index of first pending goto in this block */
44  short firstlabel;  /* index of first label in this block */
45  short firstgoto;  /* index of first pending goto in this block */
5246  lu_byte nactvar;  /* # active locals outside the block */
5347  lu_byte upval;  /* true if some variable in the block is an upvalue */
54  lu_byte isloop;  /* true if 'block' is a loop */
48  lu_byte isloop;  /* true if `block' is a loop */
5549} BlockCnt;
5650
5751
r242959r242960
6357static void expr (LexState *ls, expdesc *v);
6458
6559
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
6670/* semantic error */
6771static l_noret semerror (LexState *ls, const char *msg) {
68  ls->t.token = 0;  /* remove "near <token>" from final message */
72  ls->t.token = 0;  /* remove 'near to' from final message */
6973  luaX_syntaxerror(ls, msg);
7074}
7175
r242959r242960
218222  int i;
219223  Upvaldesc *up = fs->f->upvalues;
220224  for (i = 0; i < fs->nups; i++) {
221    if (eqstr(up[i].name, name)) return i;
225    if (luaS_eqstr(up[i].name, name)) return i;
222226  }
223227  return -1;  /* not found */
224228}
r242959r242960
242246static int searchvar (FuncState *fs, TString *n) {
243247  int i;
244248  for (i = cast_int(fs->nactvar) - 1; i >= 0; i--) {
245    if (eqstr(n, getlocvar(fs, i)->varname))
249    if (luaS_eqstr(n, getlocvar(fs, i)->varname))
246250      return i;
247251  }
248252  return -1;  /* not found */
r242959r242960
338342  FuncState *fs = ls->fs;
339343  Labellist *gl = &ls->dyd->gt;
340344  Labeldesc *gt = &gl->arr[g];
341  lua_assert(eqstr(gt->name, label->name));
345  lua_assert(luaS_eqstr(gt->name, label->name));
342346  if (gt->nactvar < label->nactvar) {
343347    TString *vname = getlocvar(fs, gt->nactvar)->varname;
344348    const char *msg = luaO_pushfstring(ls->L,
345      "<goto %s> at line %d jumps into the scope of local '%s'",
349      "<goto %s> at line %d jumps into the scope of local " LUA_QS,
346350      getstr(gt->name), gt->line, getstr(vname));
347351    semerror(ls, msg);
348352  }
r242959r242960
365369  /* check labels in current block for a match */
366370  for (i = bl->firstlabel; i < dyd->label.n; i++) {
367371    Labeldesc *lb = &dyd->label.arr[i];
368    if (eqstr(lb->name, gt->name)) {  /* correct label? */
372    if (luaS_eqstr(lb->name, gt->name)) {  /* correct label? */
369373      if (gt->nactvar > lb->nactvar &&
370374          (bl->upval || dyd->label.n > bl->firstlabel))
371375        luaK_patchclose(ls->fs, gt->pc, lb->nactvar);
r242959r242960
386390  l->arr[n].line = line;
387391  l->arr[n].nactvar = ls->fs->nactvar;
388392  l->arr[n].pc = pc;
389  l->n = n + 1;
393  l->n++;
390394  return n;
391395}
392396
r242959r242960
399403  Labellist *gl = &ls->dyd->gt;
400404  int i = ls->fs->bl->firstgoto;
401405  while (i < gl->n) {
402    if (eqstr(gl->arr[i].name, lb->name))
406    if (luaS_eqstr(gl->arr[i].name, lb->name))
403407      closegoto(ls, i, lb);
404408    else
405409      i++;
r242959r242960
408412
409413
410414/*
411** export pending gotos to outer level, to check them against
415** "export" pending gotos to outer level, to check them against
412416** outer labels; if the block being exited has upvalues, and
413417** the goto exits the scope of any variable (which can be the
414418** upvalue), close those variables being exited.
r242959r242960
444448
445449
446450/*
447** create a label named 'break' to resolve break statements
451** create a label named "break" to resolve break statements
448452*/
449453static void breaklabel (LexState *ls) {
450454  TString *n = luaS_new(ls->L, "break");
r242959r242960
459463static l_noret undefgoto (LexState *ls, Labeldesc *gt) {
460464  const char *msg = isreserved(gt->name)
461465                    ? "<%s> at line %d not inside a loop"
462                    : "no visible label '%s' for <goto> at line %d";
466                    : "no visible label " LUA_QS " for <goto> at line %d";
463467  msg = luaO_pushfstring(ls->L, msg, getstr(gt->name), gt->line);
464468  semerror(ls, msg);
465469}
r242959r242960
521525
522526
523527static void open_func (LexState *ls, FuncState *fs, BlockCnt *bl) {
528  lua_State *L = ls->L;
524529  Proto *f;
525530  fs->prev = ls->fs;  /* linked list of funcstates */
526531  fs->ls = ls;
r242959r242960
539544  f = fs->f;
540545  f->source = ls->source;
541546  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);
542551  enterblock(fs, bl, 0);
543552}
544553
r242959r242960
563572  f->sizeupvalues = fs->nups;
564573  lua_assert(fs->bl == NULL);
565574  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 */
566578  luaC_checkGC(L);
567579}
568580
r242959r242960
576588/*
577589** check whether current token is in the follow set of a block.
578590** 'until' closes syntactical blocks, but do not close scope,
579** so it is handled in separate.
591** so it handled in separate.
580592*/
581593static int block_follow (LexState *ls, int withuntil) {
582594  switch (ls->t.token) {
r242959r242960
590602
591603
592604static void statlist (LexState *ls) {
593  /* statlist -> { stat [';'] } */
605  /* statlist -> { stat [`;'] } */
594606  while (!block_follow(ls, 1)) {
595607    if (ls->t.token == TK_RETURN) {
596608      statement(ls);
r242959r242960
631643struct ConsControl {
632644  expdesc v;  /* last list item read */
633645  expdesc *t;  /* table descriptor */
634  int nh;  /* total number of 'record' elements */
646  int nh;  /* total number of `record' elements */
635647  int na;  /* total number of array elements */
636648  int tostore;  /* number of array elements pending to be stored */
637649};
638650
639651
640652static void recfield (LexState *ls, struct ConsControl *cc) {
641  /* recfield -> (NAME | '['exp1']') = exp1 */
653  /* recfield -> (NAME | `['exp1`]') = exp1 */
642654  FuncState *fs = ls->fs;
643655  int reg = ls->fs->freereg;
644656  expdesc key, val;
r242959r242960
745757
746758
747759static void parlist (LexState *ls) {
748  /* parlist -> [ param { ',' param } ] */
760  /* parlist -> [ param { `,' param } ] */
749761  FuncState *fs = ls->fs;
750762  Proto *f = fs->f;
751763  int nparams = 0;
752764  f->is_vararg = 0;
753  if (ls->t.token != ')') {  /* is 'parlist' not empty? */
765  if (ls->t.token != ')') {  /* is `parlist' not empty? */
754766    do {
755767      switch (ls->t.token) {
756768        case TK_NAME: {  /* param -> NAME */
r242959r242960
758770          nparams++;
759771          break;
760772        }
761        case TK_DOTS: {  /* param -> '...' */
773        case TK_DOTS: {  /* param -> `...' */
762774          luaX_next(ls);
763775          f->is_vararg = 1;
764776          break;
765777        }
766        default: luaX_syntaxerror(ls, "<name> or '...' expected");
778        default: luaX_syntaxerror(ls, "<name> or " LUA_QL("...") " expected");
767779      }
768780    } while (!f->is_vararg && testnext(ls, ','));
769781  }
r242959r242960
774786
775787
776788static void body (LexState *ls, expdesc *e, int ismethod, int line) {
777  /* body ->  '(' parlist ')' block END */
789  /* body ->  `(' parlist `)' block END */
778790  FuncState new_fs;
779791  BlockCnt bl;
780792  new_fs.f = addprototype(ls);
r242959r242960
796808
797809
798810static int explist (LexState *ls, expdesc *v) {
799  /* explist -> expr { ',' expr } */
811  /* explist -> expr { `,' expr } */
800812  int n = 1;  /* at least one expression */
801813  expr(ls, v);
802814  while (testnext(ls, ',')) {
r242959r242960
813825  expdesc args;
814826  int base, nparams;
815827  switch (ls->t.token) {
816    case '(': {  /* funcargs -> '(' [ explist ] ')' */
828    case '(': {  /* funcargs -> `(' [ explist ] `)' */
817829      luaX_next(ls);
818830      if (ls->t.token == ')')  /* arg list is empty? */
819831        args.k = VVOID;
r242959r242960
830842    }
831843    case TK_STRING: {  /* funcargs -> STRING */
832844      codestring(ls, &args, ls->t.seminfo.ts);
833      luaX_next(ls);  /* must use 'seminfo' before 'next' */
845      luaX_next(ls);  /* must use `seminfo' before `next' */
834846      break;
835847    }
836848    default: {
r242959r242960
896908        fieldsel(ls, v);
897909        break;
898910      }
899      case '[': {  /* '[' exp1 ']' */
911      case '[': {  /* `[' exp1 `]' */
900912        expdesc key;
901913        luaK_exp2anyregup(fs, v);
902914        yindex(ls, &key);
903915        luaK_indexed(fs, v, &key);
904916        break;
905917      }
906      case ':': {  /* ':' NAME funcargs */
918      case ':': {  /* `:' NAME funcargs */
907919        expdesc key;
908920        luaX_next(ls);
909921        checkname(ls, &key);
r242959r242960
923935
924936
925937static void simpleexp (LexState *ls, expdesc *v) {
926  /* simpleexp -> FLT | INT | STRING | NIL | TRUE | FALSE | ... |
938  /* simpleexp -> NUMBER | STRING | NIL | TRUE | FALSE | ... |
927939                  constructor | FUNCTION body | suffixedexp */
928940  switch (ls->t.token) {
929    case TK_FLT: {
930      init_exp(v, VKFLT, 0);
941    case TK_NUMBER: {
942      init_exp(v, VKNUM, 0);
931943      v->u.nval = ls->t.seminfo.r;
932944      break;
933945    }
934    case TK_INT: {
935      init_exp(v, VKINT, 0);
936      v->u.ival = ls->t.seminfo.i;
937      break;
938    }
939946    case TK_STRING: {
940947      codestring(ls, v, ls->t.seminfo.ts);
941948      break;
r242959r242960
955962    case TK_DOTS: {  /* vararg */
956963      FuncState *fs = ls->fs;
957964      check_condition(ls, fs->f->is_vararg,
958                      "cannot use '...' outside a vararg function");
965                      "cannot use " LUA_QL("...") " outside a vararg function");
959966      init_exp(v, VVARARG, luaK_codeABC(fs, OP_VARARG, 0, 1, 0));
960967      break;
961968    }
r242959r242960
981988  switch (op) {
982989    case TK_NOT: return OPR_NOT;
983990    case '-': return OPR_MINUS;
984    case '~': return OPR_BNOT;
985991    case '#': return OPR_LEN;
986992    default: return OPR_NOUNOPR;
987993  }
r242959r242960
993999    case '+': return OPR_ADD;
9941000    case '-': return OPR_SUB;
9951001    case '*': return OPR_MUL;
1002    case '/': return OPR_DIV;
9961003    case '%': return OPR_MOD;
9971004    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;
r242959r242960
10201020  lu_byte left;  /* left priority for each binary operator */
10211021  lu_byte right; /* right priority */
10221022} priority[] = {  /* ORDER OPR */
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 */
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 */
10331028};
10341029
1035#define UNARY_PRIORITY   12  /* priority for unary operators */
1030#define UNARY_PRIORITY   8  /* priority for unary operators */
10361031
10371032
10381033/*
10391034** subexpr -> (simpleexp | unop subexpr) { binop subexpr }
1040** where 'binop' is any binary operator with a priority higher than 'limit'
1035** where `binop' is any binary operator with a priority higher than `limit'
10411036*/
10421037static BinOpr subexpr (LexState *ls, expdesc *v, int limit) {
10431038  BinOpr op;
r242959r242960
10511046    luaK_prefix(ls->fs, uop, v, line);
10521047  }
10531048  else simpleexp(ls, v);
1054  /* expand while operators have priorities higher than 'limit' */
1049  /* expand while operators have priorities higher than `limit' */
10551050  op = getbinopr(ls->t.token);
10561051  while (op != OPR_NOBINOPR && priority[op].left > limit) {
10571052    expdesc v2;
r242959r242960
11511146                    "C levels");
11521147    assignment(ls, &nv, nvars+1);
11531148  }
1154  else {  /* assignment -> '=' explist */
1149  else {  /* assignment -> `=' explist */
11551150    int nexps;
11561151    checknext(ls, '=');
11571152    nexps = explist(ls, &e);
r242959r242960
11751170  /* cond -> exp */
11761171  expdesc v;
11771172  expr(ls, &v);  /* read condition */
1178  if (v.k == VNIL) v.k = VFALSE;  /* 'falses' are all equal here */
1173  if (v.k == VNIL) v.k = VFALSE;  /* `falses' are all equal here */
11791174  luaK_goiftrue(ls->fs, &v);
11801175  return v.f;
11811176}
r242959r242960
12001195static void checkrepeated (FuncState *fs, Labellist *ll, TString *label) {
12011196  int i;
12021197  for (i = fs->bl->firstlabel; i < ll->n; i++) {
1203    if (eqstr(label, ll->arr[i].name)) {
1198    if (luaS_eqstr(label, ll->arr[i].name)) {
12041199      const char *msg = luaO_pushfstring(fs->ls->L,
1205                          "label '%s' already defined on line %d",
1200                          "label " LUA_QS " already defined on line %d",
12061201                          getstr(label), ll->arr[i].line);
12071202      semerror(fs->ls, msg);
12081203    }
r242959r242960
13261321  if (testnext(ls, ','))
13271322    exp1(ls);  /* optional step */
13281323  else {  /* default step = 1 */
1329    luaK_codek(fs, fs->freereg, luaK_intK(fs, 1));
1324    luaK_codek(fs, fs->freereg, luaK_numberK(fs, 1));
13301325    luaK_reserveregs(fs, 1);
13311326  }
13321327  forbody(ls, base, line, 1, 1);
r242959r242960
13641359  TString *varname;
13651360  BlockCnt bl;
13661361  enterblock(fs, &bl, 1);  /* scope for loop and control variables */
1367  luaX_next(ls);  /* skip 'for' */
1362  luaX_next(ls);  /* skip `for' */
13681363  varname = str_checkname(ls);  /* first variable name */
13691364  switch (ls->t.token) {
13701365    case '=': fornum(ls, varname, line); break;
13711366    case ',': case TK_IN: forlist(ls, varname); break;
1372    default: luaX_syntaxerror(ls, "'=' or 'in' expected");
1367    default: luaX_syntaxerror(ls, LUA_QL("=") " or " LUA_QL("in") " expected");
13731368  }
13741369  check_match(ls, TK_END, TK_FOR, line);
1375  leaveblock(fs);  /* loop scope ('break' jumps to this point) */
1370  leaveblock(fs);  /* loop scope (`break' jumps to this point) */
13761371}
13771372
13781373
r242959r242960
14021397    enterblock(fs, &bl, 0);
14031398    jf = v.f;
14041399  }
1405  statlist(ls);  /* 'then' part */
1400  statlist(ls);  /* `then' part */
14061401  leaveblock(fs);
14071402  if (ls->t.token == TK_ELSE ||
14081403      ls->t.token == TK_ELSEIF)  /* followed by 'else'/'elseif'? */
r242959r242960
14191414  while (ls->t.token == TK_ELSEIF)
14201415    test_then_block(ls, &escapelist);  /* ELSEIF cond THEN block */
14211416  if (testnext(ls, TK_ELSE))
1422    block(ls);  /* 'else' part */
1417    block(ls);  /* `else' part */
14231418  check_match(ls, TK_END, TK_IF, line);
14241419  luaK_patchtohere(fs, escapelist);  /* patch escape list to 'if' end */
14251420}
r242959r242960
14371432
14381433
14391434static void localstat (LexState *ls) {
1440  /* stat -> LOCAL NAME {',' NAME} ['=' explist] */
1435  /* stat -> LOCAL NAME {`,' NAME} [`=' explist] */
14411436  int nvars = 0;
14421437  int nexps;
14431438  expdesc e;
r242959r242960
14571452
14581453
14591454static int funcname (LexState *ls, expdesc *v) {
1460  /* funcname -> NAME {fieldsel} [':' NAME] */
1455  /* funcname -> NAME {fieldsel} [`:' NAME] */
14611456  int ismethod = 0;
14621457  singlevar(ls, v);
14631458  while (ls->t.token == '.')
r242959r242960
14781473  ismethod = funcname(ls, &v);
14791474  body(ls, &b, ismethod, line);
14801475  luaK_storevar(ls->fs, &v, &b);
1481  luaK_fixline(ls->fs, line);  /* definition "happens" in the first line */
1476  luaK_fixline(ls->fs, line);  /* definition `happens' in the first line */
14821477}
14831478
14841479
r242959r242960
15201515      if (nret == 1)  /* only one single value? */
15211516        first = luaK_exp2anyreg(fs, &e);
15221517      else {
1523        luaK_exp2nextreg(fs, &e);  /* values must go to the stack */
1524        first = fs->nactvar;  /* return all active values */
1518        luaK_exp2nextreg(fs, &e);  /* values must go to the `stack' */
1519        first = fs->nactvar;  /* return all `active' values */
15251520        lua_assert(nret == fs->freereg - first);
15261521      }
15271522    }
r242959r242960
16201615}
16211616
16221617
1623LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1624                       Dyndata *dyd, const char *name, int firstchar) {
1618Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
1619                      Dyndata *dyd, const char *name, int firstchar) {
16251620  LexState lexstate;
16261621  FuncState funcstate;
1627  LClosure *cl = luaF_newLclosure(L, 1);  /* create main closure */
1628  setclLvalue(L, L->top, cl);  /* anchor it (to avoid being collected) */
1622  Closure *cl = luaF_newLclosure(L, 1);  /* create main closure */
1623  /* anchor closure (to avoid being collected) */
1624  setclLvalue(L, L->top, cl);
16291625  incr_top(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);
1626  funcstate.f = cl->l.p = luaF_newproto(L);
16341627  funcstate.f->source = luaS_new(L, name);  /* create and anchor TString */
1635  lua_assert(iswhite(funcstate.f));  /* do not need barrier here */
16361628  lexstate.buff = buff;
16371629  lexstate.dyd = dyd;
16381630  dyd->actvar.n = dyd->gt.n = dyd->label.n = 0;
r242959r242960
16411633  lua_assert(!funcstate.prev && funcstate.nups == 1 && !lexstate.fs);
16421634  /* all scopes should be correctly finished */
16431635  lua_assert(dyd->actvar.n == 0 && dyd->gt.n == 0 && dyd->label.n == 0);
1644  L->top--;  /* remove scanner's table */
1645  return cl;  /* closure is on the stack, too */
1636  return cl;  /* it's on the stack too */
16461637}
16471638
trunk/3rdparty/lua/src/lparser.h
r242959r242960
11/*
2** $Id: lparser.h,v 1.74 2014/10/25 11:50:46 roberto Exp $
2** $Id: lparser.h,v 1.70.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lua Parser
44** See Copyright Notice in lua.h
55*/
r242959r242960
2121  VNIL,
2222  VTRUE,
2323  VFALSE,
24  VK,      /* info = index of constant in 'k' */
25  VKFLT,   /* nval = numerical float value */
26  VKINT,   /* nval = numerical integer value */
24  VK,      /* info = index of constant in `k' */
25  VKNUM,   /* nval = numerical value */
2726  VNONRELOC,   /* info = result register */
2827  VLOCAL,   /* info = local register */
2928  VUPVAL,       /* info = index of upvalue in 'upvalues' */
r242959r242960
4746      lu_byte vt;  /* whether 't' is register (VLOCAL) or upvalue (VUPVAL) */
4847    } ind;
4948    int info;  /* for generic use */
50    lua_Number nval;  /* for VKFLT */
51    lua_Integer ival;    /* for VKINT */
49    lua_Number nval;  /* for VKNUM */
5250  } u;
53  int t;  /* patch list of 'exit when true' */
54  int f;  /* patch list of 'exit when false' */
51  int t;  /* patch list of `exit when true' */
52  int f;  /* patch list of `exit when false' */
5553} expdesc;
5654
5755
r242959r242960
9795/* state needed to generate code for a given function */
9896typedef struct FuncState {
9997  Proto *f;  /* current function header */
98  Table *h;  /* table to find (and reuse) elements in `k' */
10099  struct FuncState *prev;  /* enclosing function */
101100  struct LexState *ls;  /* lexical state */
102101  struct BlockCnt *bl;  /* chain of current blocks */
103  int pc;  /* next position to code (equivalent to 'ncode') */
102  int pc;  /* next position to code (equivalent to `ncode') */
104103  int lasttarget;   /* 'label' of last 'jump label' */
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' */
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' */
108107  int firstlocal;  /* index of first local var (in Dyndata array) */
109108  short nlocvars;  /* number of elements in 'f->locvars' */
110109  lu_byte nactvar;  /* number of active local variables */
r242959r242960
113112} FuncState;
114113
115114
116LUAI_FUNC LClosure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
117                                 Dyndata *dyd, const char *name, int firstchar);
115LUAI_FUNC Closure *luaY_parser (lua_State *L, ZIO *z, Mbuffer *buff,
116                                Dyndata *dyd, const char *name, int firstchar);
118117
119118
120119#endif
trunk/3rdparty/lua/src/lprefix.h
r242959r242960
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
r242959r242960
11/*
2** $Id: lstate.c,v 2.127 2014/11/02 19:33:33 roberto Exp $
2** $Id: lstate.c,v 2.99.1.2 2013/11/08 17:45:31 roberto Exp $
33** Global State
44** See Copyright Notice in lua.h
55*/
66
7#define lstate_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
138#include <stddef.h>
149#include <string.h>
1510
11#define lstate_c
12#define LUA_CORE
13
1614#include "lua.h"
1715
1816#include "lapi.h"
r242959r242960
3230#define LUAI_GCPAUSE   200  /* 200% */
3331#endif
3432
33#if !defined(LUAI_GCMAJOR)
34#define LUAI_GCMAJOR   200  /* 200% */
35#endif
36
3537#if !defined(LUAI_GCMUL)
3638#define LUAI_GCMUL   200 /* GC runs 'twice the speed' of memory allocation */
3739#endif
r242959r242960
5557** thread state + extra space
5658*/
5759typedef struct LX {
58  lu_byte extra_[LUA_EXTRASPACE];
60#if defined(LUAI_EXTRASPACE)
61  char buff[LUAI_EXTRASPACE];
62#endif
5963  lua_State l;
6064} LX;
6165
r242959r242960
7478
7579
7680/*
77** Compute an initial seed as random as possible. Rely on Address Space
78** Layout Randomization (if present) to increase randomness..
81** Compute an initial seed as random as possible. In ANSI, rely on
82** Address Space Layout Randomization (if present) to increase
83** randomness..
7984*/
8085#define addbuff(b,p,e) \
8186  { size_t t = cast(size_t, e); \
r242959r242960
114119}
115120
116121
117/*
118** free all CallInfo structures not in use by a thread
119*/
120122void luaE_freeCI (lua_State *L) {
121123  CallInfo *ci = L->ci;
122124  CallInfo *next = ci->next;
r242959r242960
128130}
129131
130132
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
147133static void stack_init (lua_State *L1, lua_State *L) {
148134  int i; CallInfo *ci;
149135  /* initialize stack array */
r242959r242960
177163** Create registry table and its predefined values
178164*/
179165static void init_registry (lua_State *L, global_State *g) {
180  TValue temp;
166  TValue mt;
181167  /* create registry */
182168  Table *registry = luaH_new(L);
183169  sethvalue(L, &g->l_registry, registry);
184170  luaH_resize(L, registry, LUA_RIDX_LAST, 0);
185171  /* registry[LUA_RIDX_MAINTHREAD] = L */
186  setthvalue(L, &temp, L);  /* temp = L */
187  luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &temp);
172  setthvalue(L, &mt, L);
173  luaH_setint(L, registry, LUA_RIDX_MAINTHREAD, &mt);
188174  /* registry[LUA_RIDX_GLOBALS] = table of globals */
189  sethvalue(L, &temp, luaH_new(L));  /* temp = new table (global table) */
190  luaH_setint(L, registry, LUA_RIDX_GLOBALS, &temp);
175  sethvalue(L, &mt, luaH_new(L));
176  luaH_setint(L, registry, LUA_RIDX_GLOBALS, &mt);
191177}
192178
193179
194180/*
195** open parts of the state that may cause memory-allocation errors.
196** ('g->version' != NULL flags that the state was completely build)
181** open parts of the state that may cause memory-allocation errors
197182*/
198183static void f_luaopen (lua_State *L, void *ud) {
199184  global_State *g = G(L);
r242959r242960
205190  luaX_init(L);
206191  /* pre-create memory-error message */
207192  g->memerrmsg = luaS_newliteral(L, MEMERRMSG);
208  luaC_fix(L, obj2gco(g->memerrmsg));  /* it should never be collected */
193  luaS_fix(g->memerrmsg);  /* it should never be collected */
209194  g->gcrunning = 1;  /* allow gc */
210195  g->version = lua_version(NULL);
211196  luai_userstateopen(L);
r242959r242960
213198
214199
215200/*
216** preinitialize a thread with consistent values without allocating
201** preinitialize a state with consistent values without allocating
217202** any memory (to avoid errors)
218203*/
219static void preinit_thread (lua_State *L, global_State *g) {
204static void preinit_state (lua_State *L, global_State *g) {
220205  G(L) = g;
221206  L->stack = NULL;
222207  L->ci = NULL;
223208  L->stacksize = 0;
224  L->twups = L;  /* thread has no upvalues */
225209  L->errorJmp = NULL;
226210  L->nCcalls = 0;
227211  L->hook = NULL;
r242959r242960
251235
252236
253237LUA_API lua_State *lua_newthread (lua_State *L) {
254  global_State *g = G(L);
255238  lua_State *L1;
256239  lua_lock(L);
257240  luaC_checkGC(L);
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 */
241  L1 = &luaC_newobj(L, LUA_TTHREAD, sizeof(LX), NULL, offsetof(LX, l))->th;
266242  setthvalue(L, L->top, L1);
267243  api_incr_top(L);
268  preinit_thread(L1, g);
244  preinit_state(L1, G(L));
269245  L1->hookmask = L->hookmask;
270246  L1->basehookcount = L->basehookcount;
271247  L1->hook = L->hook;
272248  resethookcount(L1);
273  /* initialize L1 extra space */
274  memcpy(lua_getextraspace(L1), lua_getextraspace(g->mainthread),
275         LUA_EXTRASPACE);
276249  luai_userstatethread(L, L1);
277250  stack_init(L1, L);  /* init stack */
278251  lua_unlock(L);
r242959r242960
300273  g = &l->g;
301274  L->next = NULL;
302275  L->tt = LUA_TTHREAD;
303  g->currentwhite = bitmask(WHITE0BIT);
276  g->currentwhite = bit2mask(WHITE0BIT, FIXEDBIT);
304277  L->marked = luaC_white(g);
305  preinit_thread(L, g);
278  g->gckind = KGC_NORMAL;
279  preinit_state(L, g);
306280  g->frealloc = f;
307281  g->ud = ud;
308282  g->mainthread = L;
309283  g->seed = makeseed(L);
284  g->uvhead.u.l.prev = &g->uvhead;
285  g->uvhead.u.l.next = &g->uvhead;
310286  g->gcrunning = 0;  /* no GC while building state */
311287  g->GCestimate = 0;
312  g->strt.size = g->strt.nuse = 0;
288  g->strt.size = 0;
289  g->strt.nuse = 0;
313290  g->strt.hash = NULL;
314291  setnilvalue(&g->l_registry);
315292  luaZ_initbuffer(L, &g->buff);
316293  g->panic = NULL;
317294  g->version = NULL;
318295  g->gcstate = GCSpause;
319  g->gckind = KGC_NORMAL;
320  g->allgc = g->finobj = g->tobefnz = g->fixedgc = NULL;
321  g->sweepgc = NULL;
296  g->allgc = NULL;
297  g->finobj = NULL;
298  g->tobefnz = NULL;
299  g->sweepgc = g->sweepfin = NULL;
322300  g->gray = g->grayagain = NULL;
323301  g->weak = g->ephemeron = g->allweak = NULL;
324  g->twups = NULL;
325302  g->totalbytes = sizeof(LG);
326303  g->GCdebt = 0;
327  g->gcfinnum = 0;
328304  g->gcpause = LUAI_GCPAUSE;
305  g->gcmajorinc = LUAI_GCMAJOR;
329306  g->gcstepmul = LUAI_GCMUL;
330307  for (i=0; i < LUA_NUMTAGS; i++) g->mt[i] = NULL;
331308  if (luaD_rawrunprotected(L, f_luaopen, NULL) != LUA_OK) {
trunk/3rdparty/lua/src/lstate.h
r242959r242960
11/*
2** $Id: lstate.h,v 2.119 2014/10/30 18:53:28 roberto Exp $
2** $Id: lstate.h,v 2.82.1.1 2013/04/12 18:48:47 roberto Exp $
33** Global State
44** See Copyright Notice in lua.h
55*/
r242959r242960
1616
1717/*
1818
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:
19** Some notes about garbage-collected objects:  All objects in Lua must
20** be kept somehow accessible until being freed.
2321**
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).
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.
2938
3039*/
3140
r242959r242960
4453/* kinds of Garbage Collection */
4554#define KGC_NORMAL   0
4655#define KGC_EMERGENCY   1   /* gc was forced by an allocation failure */
56#define KGC_GEN      2   /* generational collection */
4757
4858
4959typedef struct stringtable {
50  TString **hash;
51  int nuse;  /* number of elements */
60  GCObject **hash;
61  lu_int32 nuse;  /* number of elements */
5262  int size;
5363} stringtable;
5464
5565
5666/*
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.
67** information about a call
6468*/
6569typedef struct CallInfo {
6670  StkId func;  /* function index in the stack */
6771  StkId   top;  /* top for this function */
6872  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;
6976  union {
7077    struct {  /* only for Lua functions */
7178      StkId base;  /* base for this function */
7279      const Instruction *savedpc;
7380    } l;
7481    struct {  /* only for C functions */
75      lua_KFunction k;  /* continuation in case of yields */
82      int ctx;  /* context info. in case of yields */
83      lua_CFunction k;  /* continuation in case of yields */
7684      ptrdiff_t old_errfunc;
77      lua_KContext ctx;  /* context info. in case of yields */
85      lu_byte old_allowhook;
86      lu_byte status;
7887    } c;
7988  } u;
80  ptrdiff_t extra;
81  short nresults;  /* expected number of results from this function */
82  lu_byte callstatus;
8389} CallInfo;
8490
8591
8692/*
8793** Bits in CallInfo status
8894*/
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
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
9398                                   luaV_execute of previous call */
99#define CIST_YIELDED   (1<<3)   /* call reentered after suspension */
94100#define CIST_YPCALL   (1<<4)   /* call is a yieldable protected call */
95#define CIST_TAIL   (1<<5)   /* call was tail called */
96#define CIST_HOOKYIELD   (1<<6)   /* last hook called yielded */
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 */
97104
105
98106#define isLua(ci)   ((ci)->callstatus & CIST_LUA)
99107
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)
103108
104
105109/*
106** 'global state', shared by all threads of this state
110** `global state', shared by all threads of this state
107111*/
108112typedef struct global_State {
109113  lua_Alloc frealloc;  /* function to reallocate memory */
110  void *ud;         /* auxiliary data to 'frealloc' */
114  void *ud;         /* auxiliary data to `frealloc' */
111115  lu_mem totalbytes;  /* number of bytes currently allocated - GCdebt */
112116  l_mem GCdebt;  /* bytes allocated not yet compensated by the collector */
113117  lu_mem GCmemtrav;  /* memory traversed by the GC */
r242959r242960
119123  lu_byte gcstate;  /* state of garbage collector */
120124  lu_byte gckind;  /* kind of GC running */
121125  lu_byte gcrunning;  /* true if GC is running */
126  int sweepstrgc;  /* position of sweep in `strt' */
122127  GCObject *allgc;  /* list of all collectable objects */
123  GCObject **sweepgc;  /* current position of sweep in list */
124128  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' */
125131  GCObject *gray;  /* list of gray objects */
126132  GCObject *grayagain;  /* list of objects to be traversed atomically */
127133  GCObject *weak;  /* list of tables with weak values */
128134  GCObject *ephemeron;  /* list of ephemeron tables (weak keys) */
129135  GCObject *allweak;  /* list of all-weak tables */
130136  GCObject *tobefnz;  /* list of userdata to be GC */
131  GCObject *fixedgc;  /* list of objects not to be collected */
132  struct lua_State *twups;  /* list of threads with open upvalues */
137  UpVal uvhead;  /* head of double-linked list of all open upvalues */
133138  Mbuffer buff;  /* temporary buffer for string concatenation */
134  unsigned int gcfinnum;  /* number of finalizers to call in each GC step */
135139  int gcpause;  /* size of pause between successive GCs */
136  int gcstepmul;  /* GC 'granularity' */
140  int gcmajorinc;  /* pause between major collections (only in gen. mode) */
141  int gcstepmul;  /* GC `granularity' */
137142  lua_CFunction panic;  /* to be called in unprotected errors */
138143  struct lua_State *mainthread;
139144  const lua_Number *version;  /* pointer to version number */
r242959r242960
144149
145150
146151/*
147** 'per thread' state
152** `per thread' state
148153*/
149154struct lua_State {
150155  CommonHeader;
r242959r242960
155160  const Instruction *oldpc;  /* last pc traced */
156161  StkId stack_last;  /* last free slot in the stack */
157162  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) */
165163  int stacksize;
166  int basehookcount;
167  int hookcount;
168164  unsigned short nny;  /* number of non-yieldable calls in stack */
169165  unsigned short nCcalls;  /* number of nested C calls */
170166  lu_byte hookmask;
171167  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) */
172176};
173177
174178
r242959r242960
176180
177181
178182/*
179** Union of all collectable objects (only for conversions)
183** Union of all collectable objects
180184*/
181union GCUnion {
182  GCObject gc;  /* common header */
183  struct TString ts;
184  struct Udata u;
185union GCObject {
186  GCheader gch;  /* common header */
187  union TString ts;
188  union Udata u;
185189  union Closure cl;
186190  struct Table h;
187191  struct Proto p;
192  struct UpVal uv;
188193  struct lua_State th;  /* thread */
189194};
190195
191196
192#define cast_u(o)   cast(union GCUnion *, (o))
197#define gch(o)      (&(o)->gch)
193198
194199/* macros to convert a GCObject into a specific value */
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))
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))
200207#define gco2cl(o)  \
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))
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))
205213
214/* macro to convert any Lua object into a GCObject */
215#define obj2gco(v)   (cast(GCObject *, (v)))
206216
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)))
210217
211
212218/* actual number of total bytes allocated */
213219#define gettotalbytes(g)   ((g)->totalbytes + (g)->GCdebt)
214220
r242959r242960
216222LUAI_FUNC void luaE_freethread (lua_State *L, lua_State *L1);
217223LUAI_FUNC CallInfo *luaE_extendCI (lua_State *L);
218224LUAI_FUNC void luaE_freeCI (lua_State *L);
219LUAI_FUNC void luaE_shrinkCI (lua_State *L);
220225
221226
222227#endif
trunk/3rdparty/lua/src/lstring.c
r242959r242960
11/*
2** $Id: lstring.c,v 2.45 2014/11/02 19:19:04 roberto Exp $
2** $Id: lstring.c,v 2.26.1.1 2013/04/12 18:48:47 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
710#define lstring_c
811#define LUA_CORE
912
10#include "lprefix.h"
11
12
13#include <string.h>
14
1513#include "lua.h"
1614
17#include "ldebug.h"
18#include "ldo.h"
1915#include "lmem.h"
2016#include "lobject.h"
2117#include "lstate.h"
2218#include "lstring.h"
2319
2420
25
2621/*
2722** Lua will use at most ~(2^LUAI_HASHLIMIT) bytes from a string to
2823** compute its hash
r242959r242960
3631** equality for long strings
3732*/
3833int luaS_eqlngstr (TString *a, TString *b) {
39  size_t len = a->len;
40  lua_assert(a->tt == LUA_TLNGSTR && b->tt == LUA_TLNGSTR);
34  size_t len = a->tsv.len;
35  lua_assert(a->tsv.tt == LUA_TLNGSTR && b->tsv.tt == LUA_TLNGSTR);
4136  return (a == b) ||  /* same instance or... */
42    ((len == b->len) &&  /* equal length and ... */
37    ((len == b->tsv.len) &&  /* equal length and ... */
4338     (memcmp(getstr(a), getstr(b), len) == 0));  /* equal contents */
4439}
4540
4641
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
4751unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {
4852  unsigned int h = seed ^ cast(unsigned int, l);
4953  size_t l1;
r242959r242960
6064void luaS_resize (lua_State *L, int newsize) {
6165  int i;
6266  stringtable *tb = &G(L)->strt;
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;
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;
6772  }
68  for (i = 0; i < tb->size; i++) {  /* rehash */
69    TString *p = tb->hash[i];
73  /* rehash */
74  for (i=0; i<tb->size; i++) {
75    GCObject *p = tb->hash[i];
7076    tb->hash[i] = NULL;
7177    while (p) {  /* for each node in the list */
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 */
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 */
7581      tb->hash[h] = p;
76      p = hnext;
82      resetoldbit(p);  /* see MOVE OLD rule */
83      p = next;
7784    }
7885  }
79  if (newsize < tb->size) {  /* shrink table if needed */
80    /* vanishing slice should be empty */
86  if (newsize < tb->size) {
87    /* shrinking slice must be empty */
8188    lua_assert(tb->hash[newsize] == NULL && tb->hash[tb->size - 1] == NULL);
82    luaM_reallocvector(L, tb->hash, tb->size, newsize, TString *);
89    luaM_reallocvector(L, tb->hash, tb->size, newsize, GCObject *);
8390  }
8491  tb->size = newsize;
8592}
8693
8794
88
8995/*
9096** creates a new string object
9197*/
9298static TString *createstrobj (lua_State *L, const char *str, size_t l,
93                              int tag, unsigned int h) {
99                              int tag, unsigned int h, GCObject **list) {
94100  TString *ts;
95  GCObject *o;
96101  size_t totalsize;  /* total size of TString object */
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 */
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 */
105109  return ts;
106110}
107111
108112
109void luaS_remove (lua_State *L, TString *ts) {
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 */
110119  stringtable *tb = &G(L)->strt;
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--;
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;
116127}
117128
118129
r242959r242960
120131** checks whether short string exists and reuses it or creates a new one
121132*/
122133static TString *internshrstr (lua_State *L, const char *str, size_t l) {
123  TString *ts;
134  GCObject *o;
124135  global_State *g = G(L);
125136  unsigned int h = luaS_hash(str, l, g->seed);
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 &&
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 &&
129143        (memcmp(str, getstr(ts), l * sizeof(char)) == 0)) {
130      /* found! */
131      if (isdead(g, ts))  /* dead (but not collected yet)? */
132        changewhite(ts);  /* resurrect it */
144      if (isdead(G(L), o))  /* string is dead (but was not collected yet)? */
145        changewhite(o);  /* resurrect it */
133146      return ts;
134147    }
135148  }
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;
149  return newshrstr(L, str, l, h);  /* not found; create a new string */
145150}
146151
147152
r242959r242960
152157  if (l <= LUAI_MAXSHORTLEN)  /* short string? */
153158    return internshrstr(L, str, l);
154159  else {
155    if (l + 1 > (MAX_SIZE - sizeof(TString))/sizeof(char))
160    if (l + 1 > (MAX_SIZET - sizeof(TString))/sizeof(char))
156161      luaM_toobig(L);
157    return createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed);
162    return createstrobj(L, str, l, LUA_TLNGSTR, G(L)->seed, NULL);
158163  }
159164}
160165
r242959r242960
167172}
168173
169174
170Udata *luaS_newudata (lua_State *L, size_t s) {
175Udata *luaS_newudata (lua_State *L, size_t s, Table *e) {
171176  Udata *u;
172  GCObject *o;
173  if (s > MAX_SIZE - sizeof(Udata))
177  if (s > MAX_SIZET - sizeof(Udata))
174178    luaM_toobig(L);
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);
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;
180183  return u;
181184}
182185
trunk/3rdparty/lua/src/lstring.h
r242959r242960
11/*
2** $Id: lstring.h,v 1.56 2014/07/18 14:46:47 roberto Exp $
2** $Id: lstring.h,v 1.49.1.1 2013/04/12 18:48:47 roberto Exp $
33** String table (keep all strings handled by Lua)
44** See Copyright Notice in lua.h
55*/
r242959r242960
1212#include "lstate.h"
1313
1414
15#define sizelstring(l)  (sizeof(union UTString) + ((l) + 1) * sizeof(char))
16#define sizestring(s)   sizelstring((s)->len)
15#define sizestring(s)   (sizeof(union TString)+((s)->len+1)*sizeof(char))
1716
18#define sizeludata(l)   (sizeof(union UUdata) + (l))
19#define sizeudata(u)   sizeludata((u)->len)
17#define sizeudata(u)   (sizeof(union Udata)+(u)->len)
2018
2119#define luaS_newliteral(L, s)   (luaS_newlstr(L, "" s, \
2220                                 (sizeof(s)/sizeof(char))-1))
2321
22#define luaS_fix(s)   l_setbit((s)->tsv.marked, FIXEDBIT)
2423
24
2525/*
2626** test whether a string is a reserved word
2727*/
28#define isreserved(s)   ((s)->tt == LUA_TSHRSTR && (s)->extra > 0)
28#define isreserved(s)   ((s)->tsv.tt == LUA_TSHRSTR && (s)->tsv.extra > 0)
2929
3030
3131/*
3232** equality for short strings, which are always internalized
3333*/
34#define eqshrstr(a,b)   check_exp((a)->tt == LUA_TSHRSTR, (a) == (b))
34#define eqshrstr(a,b)   check_exp((a)->tsv.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);
3940LUAI_FUNC void luaS_resize (lua_State *L, int newsize);
40LUAI_FUNC void luaS_remove (lua_State *L, TString *ts);
41LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s);
41LUAI_FUNC Udata *luaS_newudata (lua_State *L, size_t s, Table *e);
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
r242959r242960
11/*
2** $Id: lstrlib.c,v 1.221 2014/12/11 14:03:07 roberto Exp $
2** $Id: lstrlib.c,v 1.178.1.1 2013/04/12 18:48:47 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
97
10#include "lprefix.h"
11
12
138#include <ctype.h>
14#include <limits.h>
159#include <stddef.h>
1610#include <stdio.h>
1711#include <stdlib.h>
1812#include <string.h>
1913
14#define lstrlib_c
15#define LUA_LIB
16
2017#include "lua.h"
2118
2219#include "lauxlib.h"
r242959r242960
3229#endif
3330
3431
35/* macro to 'unsign' a character */
32/* macro to `unsign' a character */
3633#define uchar(c)   ((unsigned char)(c))
3734
3835
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))
4536
46
47
48
4937static int str_len (lua_State *L) {
5038  size_t l;
5139  luaL_checklstring(L, 1, &l);
r242959r242960
5543
5644
5745/* translate a relative string position: negative means back from end */
58static lua_Integer posrelat (lua_Integer pos, size_t len) {
59  if (pos >= 0) return pos;
46static size_t posrelat (ptrdiff_t pos, size_t len) {
47  if (pos >= 0) return (size_t)pos;
6048  else if (0u - (size_t)pos > len) return 0;
61  else return (lua_Integer)len + pos + 1;
49  else return len - ((size_t)-pos) + 1;
6250}
6351
6452
6553static int str_sub (lua_State *L) {
6654  size_t l;
6755  const char *s = luaL_checklstring(L, 1, &l);
68  lua_Integer start = posrelat(luaL_checkinteger(L, 2), l);
69  lua_Integer end = posrelat(luaL_optinteger(L, 3, -1), l);
56  size_t start = posrelat(luaL_checkinteger(L, 2), l);
57  size_t end = posrelat(luaL_optinteger(L, 3, -1), l);
7058  if (start < 1) start = 1;
71  if (end > (lua_Integer)l) end = l;
59  if (end > l) end = l;
7260  if (start <= end)
73    lua_pushlstring(L, s + start - 1, (size_t)(end - start + 1));
61    lua_pushlstring(L, s + start - 1, end - start + 1);
7462  else lua_pushliteral(L, "");
7563  return 1;
7664}
r242959r242960
114102}
115103
116104
105/* reasonable limit to avoid arithmetic overflow */
106#define MAXSIZE      ((~(size_t)0) >> 1)
107
117108static int str_rep (lua_State *L) {
118109  size_t l, lsep;
119110  const char *s = luaL_checklstring(L, 1, &l);
120  lua_Integer n = luaL_checkinteger(L, 2);
111  int n = luaL_checkint(L, 2);
121112  const char *sep = luaL_optlstring(L, 3, "", &lsep);
122113  if (n <= 0) lua_pushliteral(L, "");
123  else if (l + lsep < l || l + lsep > MAXSIZE / n)  /* may overflow? */
114  else if (l + lsep < l || l + lsep >= MAXSIZE / n)  /* may overflow? */
124115    return luaL_error(L, "resulting string too large");
125116  else {
126    size_t totallen = (size_t)n * l + (size_t)(n - 1) * lsep;
117    size_t totallen = n * l + (n - 1) * lsep;
127118    luaL_Buffer b;
128119    char *p = luaL_buffinitsize(L, &b, totallen);
129120    while (n-- > 1) {  /* first n-1 copies (followed by separator) */
130121      memcpy(p, s, l * sizeof(char)); p += l;
131      if (lsep > 0) {  /* empty 'memcpy' is not that cheap */
132        memcpy(p, sep, lsep * sizeof(char));
133        p += lsep;
122      if (lsep > 0) {  /* avoid empty 'memcpy' (may be expensive) */
123        memcpy(p, sep, lsep * sizeof(char)); p += lsep;
134124      }
135125    }
136126    memcpy(p, s, l * sizeof(char));  /* last copy (not followed by separator) */
r242959r242960
143133static int str_byte (lua_State *L) {
144134  size_t l;
145135  const char *s = luaL_checklstring(L, 1, &l);
146  lua_Integer posi = posrelat(luaL_optinteger(L, 2, 1), l);
147  lua_Integer pose = posrelat(luaL_optinteger(L, 3, posi), l);
136  size_t posi = posrelat(luaL_optinteger(L, 2, 1), l);
137  size_t pose = posrelat(luaL_optinteger(L, 3, posi), l);
148138  int n, i;
149139  if (posi < 1) posi = 1;
150  if (pose > (lua_Integer)l) pose = l;
140  if (pose > l) pose = l;
151141  if (posi > pose) return 0;  /* empty interval; return no values */
152142  n = (int)(pose -  posi + 1);
153  if (posi + n <= pose)  /* arithmetic overflow? */
143  if (posi + n <= pose)  /* (size_t -> int) overflow? */
154144    return luaL_error(L, "string slice too long");
155145  luaL_checkstack(L, n, "string slice too long");
156146  for (i=0; i<n; i++)
r242959r242960
165155  luaL_Buffer b;
166156  char *p = luaL_buffinitsize(L, &b, n);
167157  for (i=1; i<=n; i++) {
168    lua_Integer c = luaL_checkinteger(L, i);
158    int c = luaL_checkint(L, i);
169159    luaL_argcheck(L, uchar(c) == c, i, "value out of range");
170160    p[i - 1] = uchar(c);
171161  }
r242959r242960
174164}
175165
176166
177static int writer (lua_State *L, const void *b, size_t size, void *B) {
167static int writer (lua_State *L, const void* b, size_t size, void* B) {
178168  (void)L;
179  luaL_addlstring((luaL_Buffer *) B, (const char *)b, size);
169  luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
180170  return 0;
181171}
182172
183173
184174static int str_dump (lua_State *L) {
185175  luaL_Buffer b;
186  int strip = lua_toboolean(L, 2);
187176  luaL_checktype(L, 1, LUA_TFUNCTION);
188177  lua_settop(L, 1);
189178  luaL_buffinit(L,&b);
190  if (lua_dump(L, writer, &b, strip) != 0)
179  if (lua_dump(L, writer, &b) != 0)
191180    return luaL_error(L, "unable to dump given function");
192181  luaL_pushresult(&b);
193182  return 1;
r242959r242960
254243  switch (*p++) {
255244    case L_ESC: {
256245      if (p == ms->p_end)
257        luaL_error(ms->L, "malformed pattern (ends with '%%')");
246        luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
258247      return p+1;
259248    }
260249    case '[': {
261250      if (*p == '^') p++;
262      do {  /* look for a ']' */
251      do {  /* look for a `]' */
263252        if (p == ms->p_end)
264          luaL_error(ms->L, "malformed pattern (missing ']')");
253          luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
265254        if (*(p++) == L_ESC && p < ms->p_end)
266          p++;  /* skip escapes (e.g. '%]') */
255          p++;  /* skip escapes (e.g. `%]') */
267256      } while (*p != ']');
268257      return p+1;
269258    }
r242959r242960
298287  int sig = 1;
299288  if (*(p+1) == '^') {
300289    sig = 0;
301    p++;  /* skip the '^' */
290    p++;  /* skip the `^' */
302291  }
303292  while (++p < ec) {
304293    if (*p == L_ESC) {
r242959r242960
336325static const char *matchbalance (MatchState *ms, const char *s,
337326                                   const char *p) {
338327  if (p >= ms->p_end - 1)
339    luaL_error(ms->L, "malformed pattern (missing arguments to '%%b')");
328    luaL_error(ms->L, "malformed pattern "
329                      "(missing arguments to " LUA_QL("%%b") ")");
340330  if (*s != *p) return NULL;
341331  else {
342332    int b = *p;
r242959r242960
435425        break;
436426      }
437427      case '$': {
438        if ((p + 1) != ms->p_end)  /* is the '$' the last char in pattern? */
428        if ((p + 1) != ms->p_end)  /* is the `$' the last char in pattern? */
439429          goto dflt;  /* no; go to default */
440430        s = (s == ms->src_end) ? s : NULL;  /* check end of string */
441431        break;
r242959r242960
453443            const char *ep; char previous;
454444            p += 2;
455445            if (*p != '[')
456              luaL_error(ms->L, "missing '[' after '%%f' in pattern");
446              luaL_error(ms->L, "missing " LUA_QL("[") " after "
447                                 LUA_QL("%%f") " in pattern");
457448            ep = classend(ms, p);  /* points to what is next */
458449            previous = (s == ms->src_init) ? '\0' : *(s - 1);
459450            if (!matchbracketclass(uchar(previous), p, ep - 1) &&
r242959r242960
523514static const char *lmemfind (const char *s1, size_t l1,
524515                               const char *s2, size_t l2) {
525516  if (l2 == 0) return s1;  /* empty strings are everywhere */
526  else if (l2 > l1) return NULL;  /* avoids a negative 'l1' */
517  else if (l2 > l1) return NULL;  /* avoids a negative `l1' */
527518  else {
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 */
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 */
531522    while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
532523      init++;   /* 1st char is already checked */
533524      if (memcmp(init, s2+1, l2) == 0)
534525        return init-1;
535      else {  /* correct 'l1' and 's1' to try again */
526      else {  /* correct `l1' and `s1' to try again */
536527        l1 -= init-s1;
537528        s1 = init;
538529      }
r242959r242960
548539    if (i == 0)  /* ms->level == 0, too */
549540      lua_pushlstring(ms->L, s, e - s);  /* add whole match */
550541    else
551      luaL_error(ms->L, "invalid capture index %%%d", i + 1);
542      luaL_error(ms->L, "invalid capture index");
552543  }
553544  else {
554545    ptrdiff_t l = ms->capture[i].len;
r242959r242960
587578  size_t ls, lp;
588579  const char *s = luaL_checklstring(L, 1, &ls);
589580  const char *p = luaL_checklstring(L, 2, &lp);
590  lua_Integer init = posrelat(luaL_optinteger(L, 3, 1), ls);
581  size_t init = posrelat(luaL_optinteger(L, 3, 1), ls);
591582  if (init < 1) init = 1;
592  else if (init > (lua_Integer)ls + 1) {  /* start after string's end? */
583  else if (init > ls + 1) {  /* start after string's end? */
593584    lua_pushnil(L);  /* cannot find anything */
594585    return 1;
595586  }
596587  /* explicit request or no special characters? */
597588  if (find && (lua_toboolean(L, 4) || nospecials(p, lp))) {
598589    /* do a plain search */
599    const char *s2 = lmemfind(s + init - 1, ls - (size_t)init + 1, p, lp);
590    const char *s2 = lmemfind(s + init - 1, ls - init + 1, p, lp);
600591    if (s2) {
601592      lua_pushinteger(L, s2 - s + 1);
602593      lua_pushinteger(L, s2 - s + lp);
r242959r242960
687678static void add_s (MatchState *ms, luaL_Buffer *b, const char *s,
688679                                                   const char *e) {
689680  size_t l, i;
690  lua_State *L = ms->L;
691  const char *news = lua_tolstring(L, 3, &l);
681  const char *news = lua_tolstring(ms->L, 3, &l);
692682  for (i = 0; i < l; i++) {
693683    if (news[i] != L_ESC)
694684      luaL_addchar(b, news[i]);
r242959r242960
696686      i++;  /* skip ESC */
697687      if (!isdigit(uchar(news[i]))) {
698688        if (news[i] != L_ESC)
699          luaL_error(L, "invalid use of '%c' in replacement string", L_ESC);
689          luaL_error(ms->L, "invalid use of " LUA_QL("%c")
690                           " in replacement string", L_ESC);
700691        luaL_addchar(b, news[i]);
701692      }
702693      else if (news[i] == '0')
703694          luaL_addlstring(b, s, e - s);
704695      else {
705696        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 */
708697        luaL_addvalue(b);  /* add capture to accumulated result */
709698      }
710699    }
r242959r242960
748737  const char *src = luaL_checklstring(L, 1, &srcl);
749738  const char *p = luaL_checklstring(L, 2, &lp);
750739  int tr = lua_type(L, 3);
751  lua_Integer max_s = luaL_optinteger(L, 4, srcl + 1);
740  size_t max_s = luaL_optinteger(L, 4, srcl+1);
752741  int anchor = (*p == '^');
753  lua_Integer n = 0;
742  size_t n = 0;
754743  MatchState ms;
755744  luaL_Buffer b;
756745  luaL_argcheck(L, tr == LUA_TNUMBER || tr == LUA_TSTRING ||
r242959r242960
797786** =======================================================
798787*/
799788
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
800822/* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
801823#define MAX_ITEM   512
802
803824/* valid flags in a format specification */
804825#define FLAGS   "-+ #0"
805
806826/*
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)
827** maximum size of each format specification (such as '%-099.99d')
828** (+10 accounts for %99.99x plus margin of error)
809829*/
810#define MAX_FORMAT   (sizeof(FLAGS) + 2 + 10)
830#define MAX_FORMAT   (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
811831
812832
813833static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
r242959r242960
883903    else if (*++strfrmt == L_ESC)
884904      luaL_addchar(&b, *strfrmt++);  /* %% */
885905    else { /* format item */
886      char form[MAX_FORMAT];  /* to store the format ('%...') */
906      char form[MAX_FORMAT];  /* to store the format (`%...') */
887907      char *buff = luaL_prepbuffsize(&b, MAX_ITEM);  /* to put formatted item */
888908      int nb = 0;  /* number of bytes in added item */
889909      if (++arg > top)
r242959r242960
891911      strfrmt = scanformat(L, strfrmt, form);
892912      switch (*strfrmt++) {
893913        case 'c': {
894          nb = sprintf(buff, form, (int)luaL_checkinteger(L, arg));
914          nb = sprintf(buff, form, luaL_checkint(L, arg));
895915          break;
896916        }
897        case 'd': case 'i':
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        }
898927        case 'o': case 'u': case 'x': case 'X': {
899          lua_Integer n = luaL_checkinteger(L, arg);
900          addlenmod(form, LUA_INTEGER_FRMLEN);
901          nb = sprintf(buff, form, n);
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);
902935          break;
903936        }
937        case 'e': case 'E': case 'f':
904938#if defined(LUA_USE_AFORMAT)
905939        case 'a': case 'A':
906940#endif
907        case 'e': case 'E': case 'f':
908941        case 'g': case 'G': {
909          addlenmod(form, LUA_NUMBER_FRMLEN);
910          nb = sprintf(buff, form, luaL_checknumber(L, arg));
942          addlenmod(form, LUA_FLTFRMLEN);
943          nb = sprintf(buff, form, (LUA_FLTFRM_T)luaL_checknumber(L, arg));
911944          break;
912945        }
913946        case 'q': {
r242959r242960
929962            break;
930963          }
931964        }
932        default: {  /* also treat cases 'pnLlh' */
933          return luaL_error(L, "invalid option '%%%c' to 'format'",
934                               *(strfrmt - 1));
965        default: {  /* also treat cases `pnLlh' */
966          return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
967                               LUA_QL("format"), *(strfrmt - 1));
935968        }
936969      }
937970      luaL_addsize(&b, nb);
r242959r242960
944977/* }====================================================== */
945978
946979
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
1388980static const luaL_Reg strlib[] = {
1389981  {"byte", str_byte},
1390982  {"char", str_char},
r242959r242960
1400992  {"reverse", str_reverse},
1401993  {"sub", str_sub},
1402994  {"upper", str_upper},
1403  {"pack", str_pack},
1404  {"packsize", str_packsize},
1405  {"unpack", str_unpack},
1406995  {NULL, NULL}
1407996};
1408997
trunk/3rdparty/lua/src/ltable.c
r242959r242960
11/*
2** $Id: ltable.c,v 2.100 2015/01/05 13:52:37 roberto Exp $
2** $Id: ltable.c,v 2.72.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lua tables (hash)
44** See Copyright Notice in lua.h
55*/
66
7#define ltable_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
138/*
149** Implementation of tables (aka arrays, objects, or hash tables).
1510** Tables keep its elements in two parts: an array part and a hash part.
1611** Non-negative integer keys are all candidates to be kept in the array
17** part. The actual size of the array is the largest 'n' such that at
12** part. The actual size of the array is the largest `n' such that at
1813** least half the slots between 0 and n are in use.
1914** Hash uses a mix of chained scatter table with Brent's variation.
2015** A main invariant of these tables is that, if an element is not
21** in its main position (i.e. the 'original' position that its hash gives
16** in its main position (i.e. the `original' position that its hash gives
2217** to it), then the colliding element is in its own main position.
2318** Hence even when the load factor reaches 100%, performance remains good.
2419*/
2520
26#include <float.h>
27#include <math.h>
2821#include <string.h>
29#include <limits.h>
3022
23#define ltable_c
24#define LUA_CORE
25
3126#include "lua.h"
3227
3328#include "ldebug.h"
r242959r242960
4237
4338
4439/*
45** Maximum size of array part (MAXASIZE) is 2^MAXABITS. MAXABITS is
46** the largest integer such that MAXASIZE fits in an unsigned int.
40** max size of array part is 2^MAXBITS
4741*/
48#define MAXABITS   cast_int(sizeof(int) * CHAR_BIT - 1)
49#define MAXASIZE   (1u << MAXABITS)
42#if LUAI_BITSINT >= 32
43#define MAXBITS      30
44#else
45#define MAXBITS      (LUAI_BITSINT-2)
46#endif
5047
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)
48#define MAXASIZE   (1 << MAXBITS)
5849
5950
6051#define hashpow2(t,n)      (gnode(t, lmod((n), sizenode(t))))
6152
62#define hashstr(t,str)      hashpow2(t, (str)->hash)
53#define hashstr(t,str)      hashpow2(t, (str)->tsv.hash)
6354#define hashboolean(t,p)   hashpow2(t, p)
64#define hashint(t,i)      hashpow2(t, i)
6555
6656
6757/*
r242959r242960
7161#define hashmod(t,n)   (gnode(t, ((n) % ((sizenode(t)-1)|1))))
7262
7363
74#define hashpointer(t,p)   hashmod(t, point2int(p))
64#define hashpointer(t,p)   hashmod(t, IntPoint(p))
7565
7666
7767#define dummynode      (&dummynode_)
r242959r242960
8070
8171static const Node dummynode_ = {
8272  {NILCONSTANT},  /* value */
83  {{NILCONSTANT, 0}}  /* key */
73  {{NILCONSTANT, NULL}}  /* key */
8474};
8575
8676
8777/*
88** Checks whether a float has a value representable as a lua_Integer
89** (and does the conversion if so)
78** hash for lua_Numbers
9079*/
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) {
80static Node *hashnum (const Table *t, lua_Number n) {
10281  int i;
103  n = l_mathop(frexp)(n, &i) * cast_num(INT_MAX - DBL_MAX_EXP);
104  i += cast_int(n);
82  luai_hashnum(i, n);
10583  if (i < 0) {
10684    if (cast(unsigned int, i) == 0u - i)  /* use unsigned to avoid overflows */
10785      i = 0;  /* handle INT_MIN */
r242959r242960
11391
11492
11593/*
116** returns the 'main' position of an element in a table (that is, the index
94** returns the `main' position of an element in a table (that is, the index
11795** of its hash value)
11896*/
11997static Node *mainposition (const Table *t, const TValue *key) {
12098  switch (ttype(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));
99    case LUA_TNUMBER:
100      return hashnum(t, nvalue(key));
127101    case LUA_TLNGSTR: {
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 */
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 */
132106      }
133      return hashstr(t, tsvalue(key));
107      return hashstr(t, rawtsvalue(key));
134108    }
109    case LUA_TSHRSTR:
110      return hashstr(t, rawtsvalue(key));
135111    case LUA_TBOOLEAN:
136112      return hashboolean(t, bvalue(key));
137113    case LUA_TLIGHTUSERDATA:
r242959r242960
145121
146122
147123/*
148** returns the index for 'key' if 'key' is an appropriate key to live in
149** the array part of the table, 0 otherwise.
124** returns the index for `key' if `key' is an appropriate key to live in
125** the array part of the table, -1 otherwise.
150126*/
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 */
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;
156134  }
157  return 0;  /* 'key' did not match some condition */
135  return -1;  /* `key' did not match some condition */
158136}
159137
160138
161139/*
162** returns the index of a 'key' for table traversals. First goes all
140** returns the index of a `key' for table traversals. First goes all
163141** elements in the array part, then elements in the hash part. The
164** beginning of a traversal is signaled by 0.
142** beginning of a traversal is signaled by -1.
165143*/
166static unsigned int findindex (lua_State *L, Table *t, StkId key) {
167  unsigned int i;
168  if (ttisnil(key)) return 0;  /* first iteration */
144static int findindex (lua_State *L, Table *t, StkId key) {
145  int i;
146  if (ttisnil(key)) return -1;  /* first iteration */
169147  i = arrayindex(key);
170  if (i != 0 && i <= t->sizearray)  /* is 'key' inside array part? */
171    return i;  /* yes; that's the index */
148  if (0 < i && i <= t->sizearray)  /* is `key' inside array part? */
149    return i-1;  /* yes; that's the index (corrected to C) */
172150  else {
173    int nx;
174151    Node *n = mainposition(t, key);
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' */
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' */
177154      if (luaV_rawequalobj(gkey(n), key) ||
178155            (ttisdeadkey(gkey(n)) && iscollectable(key) &&
179156             deadvalue(gkey(n)) == gcvalue(key))) {
180157        i = cast_int(n - gnode(t, 0));  /* key index in hash table */
181158        /* hash elements are numbered after array ones */
182        return (i + 1) + t->sizearray;
159        return i + t->sizearray;
183160      }
184      nx = gnext(n);
185      if (nx == 0)
186        luaG_runerror(L, "invalid key to 'next'");  /* key not found */
187      else n += nx;
161      else n = gnext(n);
162      if (n == NULL)
163        luaG_runerror(L, "invalid key to " LUA_QL("next"));  /* key not found */
188164    }
189165  }
190166}
191167
192168
193169int luaH_next (lua_State *L, Table *t, StkId key) {
194  unsigned int i = findindex(L, t, key);  /* find original element */
195  for (; i < t->sizearray; i++) {  /* try first array part */
170  int i = findindex(L, t, key);  /* find original element */
171  for (i++; i < t->sizearray; i++) {  /* try first array part */
196172    if (!ttisnil(&t->array[i])) {  /* a non-nil value? */
197      setivalue(key, i + 1);
173      setnvalue(key, cast_num(i+1));
198174      setobj2s(L, key+1, &t->array[i]);
199175      return 1;
200176    }
201177  }
202  for (i -= t->sizearray; cast_int(i) < sizenode(t); i++) {  /* hash part */
178  for (i -= t->sizearray; i < sizenode(t); i++) {  /* then hash part */
203179    if (!ttisnil(gval(gnode(t, i)))) {  /* a non-nil value? */
204180      setobj2s(L, key, gkey(gnode(t, i)));
205181      setobj2s(L, key+1, gval(gnode(t, i)));
r242959r242960
216192** ==============================================================
217193*/
218194
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) {
195
196static int computesizes (int nums[], int *narray) {
226197  int i;
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 */
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 */
231202  for (i = 0, twotoi = 1; twotoi/2 < *narray; i++, twotoi *= 2) {
232203    if (nums[i] > 0) {
233204      a += nums[i];
234205      if (a > twotoi/2) {  /* more than half elements present? */
235206        n = twotoi;  /* optimal size (till now) */
236        na = a;  /* all elements up to 'n' will go to array part */
207        na = a;  /* all elements smaller than n will go to array part */
237208      }
238209    }
239210    if (a == *narray) break;  /* all elements already counted */
r242959r242960
244215}
245216
246217
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? */
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? */
250221    nums[luaO_ceillog2(k)]++;  /* count as such */
251222    return 1;
252223  }
r242959r242960
255226}
256227
257228
258static unsigned int numusearray (const Table *t, unsigned int *nums) {
229static int numusearray (const Table *t, int *nums) {
259230  int lg;
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;
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;
267237    if (lim > t->sizearray) {
268238      lim = t->sizearray;  /* adjust upper limit */
269239      if (i > lim)
270240        break;  /* no more elements to count */
271241    }
272    /* count elements in range (2^(lg - 1), 2^lg] */
242    /* count elements in range (2^(lg-1), 2^lg] */
273243    for (; i <= lim; i++) {
274244      if (!ttisnil(&t->array[i-1]))
275245        lc++;
r242959r242960
281251}
282252
283253
284static int numusehash (const Table *t, unsigned int *nums,
285                       unsigned int *pnasize) {
254static int numusehash (const Table *t, int *nums, int *pnasize) {
286255  int totaluse = 0;  /* total number of elements */
287  int ause = 0;  /* elements added to 'nums' (can go to array part) */
256  int ause = 0;  /* summation of `nums' */
288257  int i = sizenode(t);
289258  while (i--) {
290259    Node *n = &t->node[i];
r242959r242960
298267}
299268
300269
301static void setarrayvector (lua_State *L, Table *t, unsigned int size) {
302  unsigned int i;
270static void setarrayvector (lua_State *L, Table *t, int size) {
271  int i;
303272  luaM_reallocvector(L, t->array, t->sizearray, size, TValue);
304273  for (i=t->sizearray; i<size; i++)
305274     setnilvalue(&t->array[i]);
r242959r242960
307276}
308277
309278
310static void setnodevector (lua_State *L, Table *t, unsigned int size) {
279static void setnodevector (lua_State *L, Table *t, int size) {
311280  int lsize;
312281  if (size == 0) {  /* no elements to hash part? */
313    t->node = cast(Node *, dummynode);  /* use common 'dummynode' */
282    t->node = cast(Node *, dummynode);  /* use common `dummynode' */
314283    lsize = 0;
315284  }
316285  else {
317286    int i;
318287    lsize = luaO_ceillog2(size);
319    if (lsize > MAXHBITS)
288    if (lsize > MAXBITS)
320289      luaG_runerror(L, "table overflow");
321290    size = twoto(lsize);
322291    t->node = luaM_newvector(L, size, Node);
323    for (i = 0; i < (int)size; i++) {
292    for (i=0; i<size; i++) {
324293      Node *n = gnode(t, i);
325      gnext(n) = 0;
326      setnilvalue(wgkey(n));
294      gnext(n) = NULL;
295      setnilvalue(gkey(n));
327296      setnilvalue(gval(n));
328297    }
329298  }
r242959r242960
332301}
333302
334303
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;
304void luaH_resize (lua_State *L, Table *t, int nasize, int nhsize) {
305  int i;
306  int oldasize = t->sizearray;
340307  int oldhsize = t->lsizenode;
341308  Node *nold = t->node;  /* save old hash ... */
342309  if (nasize > oldasize)  /* array part must grow? */
r242959r242960
354321    luaM_reallocvector(L, t->array, oldasize, nasize, TValue);
355322  }
356323  /* re-insert elements from hash part */
357  for (j = twoto(oldhsize) - 1; j >= 0; j--) {
358    Node *old = nold + j;
324  for (i = twoto(oldhsize) - 1; i >= 0; i--) {
325    Node *old = nold+i;
359326    if (!ttisnil(gval(old))) {
360327      /* doesn't need barrier/invalidate cache, as entry was
361328         already present in the table */
r242959r242960
367334}
368335
369336
370void luaH_resizearray (lua_State *L, Table *t, unsigned int nasize) {
337void luaH_resizearray (lua_State *L, Table *t, int nasize) {
371338  int nsize = isdummy(t->node) ? 0 : sizenode(t);
372339  luaH_resize(L, t, nasize, nsize);
373340}
374341
375/*
376** nums[i] = number of keys 'k' where 2^(i - 1) < k <= 2^i
377*/
342
378343static void rehash (lua_State *L, Table *t, const TValue *ek) {
379  unsigned int nasize, na;
380  unsigned int nums[MAXABITS + 1];
344  int nasize, na;
345  int nums[MAXBITS+1];  /* nums[i] = number of keys with 2^(i-1) < k <= 2^i */
381346  int i;
382347  int totaluse;
383  for (i = 0; i <= MAXABITS; i++) nums[i] = 0;  /* reset counts */
348  for (i=0; i<=MAXBITS; i++) nums[i] = 0;  /* reset counts */
384349  nasize = numusearray(t, nums);  /* count keys in array part */
385350  totaluse = nasize;  /* all those keys are integer keys */
386351  totaluse += numusehash(t, nums, &nasize);  /* count keys in hash part */
r242959r242960
401366
402367
403368Table *luaH_new (lua_State *L) {
404  GCObject *o = luaC_newobj(L, LUA_TTABLE, sizeof(Table));
405  Table *t = gco2t(o);
369  Table *t = &luaC_newobj(L, LUA_TTABLE, sizeof(Table), NULL, 0)->h;
406370  t->metatable = NULL;
407371  t->flags = cast_byte(~0);
408372  t->array = NULL;
r242959r242960
440404*/
441405TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
442406  Node *mp;
443  TValue aux;
444407  if (ttisnil(key)) luaG_runerror(L, "table index is nil");
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  }
408  else if (ttisnumber(key) && luai_numisnan(L, nvalue(key)))
409    luaG_runerror(L, "table index is NaN");
455410  mp = mainposition(t, key);
456411  if (!ttisnil(gval(mp)) || isdummy(mp)) {  /* main position is taken? */
457412    Node *othern;
458    Node *f = getfreepos(t);  /* get a free place */
459    if (f == NULL) {  /* cannot find a free place? */
413    Node *n = getfreepos(t);  /* get a free place */
414    if (n == NULL) {  /* cannot find a free place? */
460415      rehash(L, t, key);  /* grow table */
461      /* whatever called 'newkey' takes care of TM cache and GC barrier */
416      /* whatever called 'newkey' take care of TM cache and GC barrier */
462417      return luaH_set(L, t, key);  /* insert key into grown table */
463418    }
464    lua_assert(!isdummy(f));
419    lua_assert(!isdummy(n));
465420    othern = mainposition(t, gkey(mp));
466421    if (othern != mp) {  /* is colliding node out of its main position? */
467422      /* yes; move colliding node into free position */
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      }
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 */
476427      setnilvalue(gval(mp));
477428    }
478429    else {  /* colliding node is in its own main position */
479430      /* new node will go into free position */
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;
431      gnext(n) = gnext(mp);  /* chain new position */
432      gnext(mp) = n;
433      mp = n;
485434    }
486435  }
487  setnodekey(L, &mp->i_key, key);
488  luaC_barrierback(L, t, key);
436  setobj2t(L, gkey(mp), key);
437  luaC_barrierback(L, obj2gco(t), key);
489438  lua_assert(ttisnil(gval(mp)));
490439  return gval(mp);
491440}
r242959r242960
494443/*
495444** search function for integers
496445*/
497const TValue *luaH_getint (Table *t, lua_Integer key) {
446const TValue *luaH_getint (Table *t, int key) {
498447  /* (1 <= key && key <= t->sizearray) */
499  if (l_castS2U(key - 1) < t->sizearray)
500    return &t->array[key - 1];
448  if (cast(unsigned int, key-1) < cast(unsigned int, t->sizearray))
449    return &t->array[key-1];
501450  else {
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)
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))
505455        return gval(n);  /* that's it */
506      else {
507        int nx = gnext(n);
508        if (nx == 0) break;
509        n += nx;
510      }
511    };
456      else n = gnext(n);
457    } while (n);
512458    return luaO_nilobject;
513459  }
514460}
r242959r242960
519465*/
520466const TValue *luaH_getstr (Table *t, TString *key) {
521467  Node *n = hashstr(t, 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))
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))
526471      return gval(n);  /* that's it */
527    else {
528      int nx = gnext(n);
529      if (nx == 0) break;
530      n += nx;
531    }
532  };
472    else n = gnext(n);
473  } while (n);
533474  return luaO_nilobject;
534475}
535476
r242959r242960
539480*/
540481const TValue *luaH_get (Table *t, const TValue *key) {
541482  switch (ttype(key)) {
542    case LUA_TSHRSTR: return luaH_getstr(t, tsvalue(key));
543    case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
483    case LUA_TSHRSTR: return luaH_getstr(t, rawtsvalue(key));
544484    case LUA_TNIL: return luaO_nilobject;
545    case LUA_TNUMFLT: {
546      lua_Integer k;
547      if (numisinteger(fltvalue(key), &k)) /* index is int? */
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? */
548490        return luaH_getint(t, k);  /* use specialized version */
549491      /* else go through */
550492    }
551493    default: {
552494      Node *n = mainposition(t, key);
553      for (;;) {  /* check whether 'key' is somewhere in the chain */
495      do {  /* check whether `key' is somewhere in the chain */
554496        if (luaV_rawequalobj(gkey(n), key))
555497          return gval(n);  /* that's it */
556        else {
557          int nx = gnext(n);
558          if (nx == 0) break;
559          n += nx;
560        }
561      };
498        else n = gnext(n);
499      } while (n);
562500      return luaO_nilobject;
563501    }
564502  }
r242959r242960
577515}
578516
579517
580void luaH_setint (lua_State *L, Table *t, lua_Integer key, TValue *value) {
518void luaH_setint (lua_State *L, Table *t, int key, TValue *value) {
581519  const TValue *p = luaH_getint(t, key);
582520  TValue *cell;
583521  if (p != luaO_nilobject)
584522    cell = cast(TValue *, p);
585523  else {
586524    TValue k;
587    setivalue(&k, key);
525    setnvalue(&k, cast_num(key));
588526    cell = luaH_newkey(L, t, &k);
589527  }
590528  setobj2t(L, cell, value);
r242959r242960
594532static int unbound_search (Table *t, unsigned int j) {
595533  unsigned int i = j;  /* i is zero or a present index */
596534  j++;
597  /* find 'i' and 'j' such that i is present and j is not */
535  /* find `i' and `j' such that i is present and j is not */
598536  while (!ttisnil(luaH_getint(t, j))) {
599537    i = j;
600    if (j > cast(unsigned int, MAX_INT)/2) {  /* overflow? */
538    j *= 2;
539    if (j > cast(unsigned int, MAX_INT)) {  /* overflow? */
601540      /* table was built with bad purposes: resort to linear search */
602541      i = 1;
603542      while (!ttisnil(luaH_getint(t, i))) i++;
604543      return i - 1;
605544    }
606    j *= 2;
607545  }
608546  /* now do a binary search between them */
609547  while (j - i > 1) {
r242959r242960
616554
617555
618556/*
619** Try to find a boundary in table 't'. A 'boundary' is an integer index
557** Try to find a boundary in table `t'. A `boundary' is an integer index
620558** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil).
621559*/
622560int luaH_getn (Table *t) {
trunk/3rdparty/lua/src/ltable.h
r242959r242960
11/*
2** $Id: ltable.h,v 2.20 2014/09/04 18:15:29 roberto Exp $
2** $Id: ltable.h,v 2.16.1.2 2013/08/30 15:49:41 roberto Exp $
33** Lua tables (hash)
44** See Copyright Notice in lua.h
55*/
r242959r242960
1111
1212
1313#define gnode(t,i)   (&(t)->node[i])
14#define gkey(n)      (&(n)->i_key.tvk)
1415#define gval(n)      (&(n)->i_val)
1516#define gnext(n)   ((n)->i_key.nk.next)
1617
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
2318#define invalidateTMcache(t)   ((t)->flags = 0)
2419
25
2620/* returns the key, given the value of a table entry */
2721#define keyfromval(v) \
2822  (gkey(cast(Node *, cast(char *, (v)) - offsetof(Node, i_val))))
2923
3024
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);
25LUAI_FUNC const TValue *luaH_getint (Table *t, int key);
26LUAI_FUNC void luaH_setint (lua_State *L, Table *t, int key, TValue *value);
3427LUAI_FUNC const TValue *luaH_getstr (Table *t, TString *key);
3528LUAI_FUNC const TValue *luaH_get (Table *t, const TValue *key);
3629LUAI_FUNC TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key);
3730LUAI_FUNC TValue *luaH_set (lua_State *L, Table *t, const TValue *key);
3831LUAI_FUNC Table *luaH_new (lua_State *L);
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);
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);
4234LUAI_FUNC void luaH_free (lua_State *L, Table *t);
4335LUAI_FUNC int luaH_next (lua_State *L, Table *t, StkId key);
4436LUAI_FUNC int luaH_getn (Table *t);
trunk/3rdparty/lua/src/ltablib.c
r242959r242960
11/*
2** $Id: ltablib.c,v 1.79 2014/11/02 19:19:04 roberto Exp $
2** $Id: ltablib.c,v 1.65.1.1 2013/04/12 18:48:47 roberto Exp $
33** Library for Table Manipulation
44** See Copyright Notice in lua.h
55*/
66
7#define ltablib_c
8#define LUA_LIB
97
10#include "lprefix.h"
11
12
13#include <limits.h>
148#include <stddef.h>
159
10#define ltablib_c
11#define LUA_LIB
12
1613#include "lua.h"
1714
1815#include "lauxlib.h"
1916#include "lualib.h"
2017
2118
19#define aux_getn(L,n)   (luaL_checktype(L, n, LUA_TTABLE), luaL_len(L, n))
2220
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;
3021
3122
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
5823#if defined(LUA_COMPAT_MAXN)
5924static int maxn (lua_State *L) {
6025  lua_Number max = 0;
r242959r242960
7439
7540
7641static int tinsert (lua_State *L) {
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 */
42  int e = aux_getn(L, 1) + 1;  /* first empty element */
43  int pos;  /* where to insert new element */
8044  switch (lua_gettop(L)) {
8145    case 2: {  /* called with only 2 arguments */
8246      pos = e;  /* insert new element at the end */
8347      break;
8448    }
8549    case 3: {
86      lua_Integer i;
87      pos = luaL_checkinteger(L, 2);  /* 2nd argument is the position */
50      int i;
51      pos = luaL_checkint(L, 2);  /* 2nd argument is the position */
8852      luaL_argcheck(L, 1 <= pos && pos <= e, 2, "position out of bounds");
8953      for (i = e; i > pos; i--) {  /* move up elements */
90        (*ta.geti)(L, 1, i - 1);
91        (*ta.seti)(L, 1, i);  /* t[i] = t[i - 1] */
54        lua_rawgeti(L, 1, i-1);
55        lua_rawseti(L, 1, i);  /* t[i] = t[i-1] */
9256      }
9357      break;
9458    }
9559    default: {
96      return luaL_error(L, "wrong number of arguments to 'insert'");
60      return luaL_error(L, "wrong number of arguments to " LUA_QL("insert"));
9761    }
9862  }
99  (*ta.seti)(L, 1, pos);  /* t[pos] = v */
63  lua_rawseti(L, 1, pos);  /* t[pos] = v */
10064  return 0;
10165}
10266
10367
10468static int tremove (lua_State *L) {
105  TabA ta;
106  lua_Integer size = aux_getn(L, 1, &ta);
107  lua_Integer pos = luaL_optinteger(L, 2, size);
69  int size = aux_getn(L, 1);
70  int pos = luaL_optint(L, 2, size);
10871  if (pos != size)  /* validate 'pos' if given */
10972    luaL_argcheck(L, 1 <= pos && pos <= size + 1, 1, "position out of bounds");
110  (*ta.geti)(L, 1, pos);  /* result = t[pos] */
73  lua_rawgeti(L, 1, pos);  /* result = t[pos] */
11174  for ( ; pos < size; pos++) {
112    (*ta.geti)(L, 1, pos + 1);
113    (*ta.seti)(L, 1, pos);  /* t[pos] = t[pos + 1] */
75    lua_rawgeti(L, 1, pos+1);
76    lua_rawseti(L, 1, pos);  /* t[pos] = t[pos+1] */
11477  }
11578  lua_pushnil(L);
116  (*ta.seti)(L, 1, pos);  /* t[pos] = nil */
79  lua_rawseti(L, 1, pos);  /* t[pos] = nil */
11780  return 1;
11881}
11982
12083
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);
84static void addfield (lua_State *L, luaL_Buffer *b, int i) {
85  lua_rawgeti(L, 1, i);
15886  if (!lua_isstring(L, -1))
159    luaL_error(L, "invalid value (%s) at index %d in table for 'concat'",
160                  luaL_typename(L, -1), i);
87    luaL_error(L, "invalid value (%s) at index %d in table for "
88                  LUA_QL("concat"), luaL_typename(L, -1), i);
16189  luaL_addvalue(b);
16290}
16391
16492
16593static int tconcat (lua_State *L) {
166  TabA ta;
16794  luaL_Buffer b;
16895  size_t lsep;
169  lua_Integer i, last;
96  int i, last;
17097  const char *sep = luaL_optlstring(L, 2, "", &lsep);
171  checktab(L, 1, &ta);
172  i = luaL_optinteger(L, 3, 1);
173  last = luaL_opt(L, luaL_checkinteger, 4, luaL_len(L, 1));
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));
174101  luaL_buffinit(L, &b);
175102  for (; i < last; i++) {
176    addfield(L, &b, &ta, i);
103    addfield(L, &b, i);
177104    luaL_addlstring(&b, sep, lsep);
178105  }
179106  if (i == last)  /* add last value (if interval was not empty) */
180    addfield(L, &b, &ta, i);
107    addfield(L, &b, i);
181108  luaL_pushresult(&b);
182109  return 1;
183110}
r242959r242960
190117*/
191118
192119static int pack (lua_State *L) {
193  int i;
194120  int n = lua_gettop(L);  /* number of elements to pack */
195121  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);
199122  lua_pushinteger(L, n);
200  lua_setfield(L, 1, "n");  /* t.n = number of elements */
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  }
201132  return 1;  /* return table */
202133}
203134
204135
205136static int unpack (lua_State *L) {
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));
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));
212141  if (i > e) return 0;  /* empty range */
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)))
142  n = e - i + 1;  /* number of elements */
143  if (n <= 0 || !lua_checkstack(L, n))  /* n <= 0 means arith. overflow */
215144    return luaL_error(L, "too many results to unpack");
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;
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;
221149}
222150
223151/* }====================================================== */
r242959r242960
227155/*
228156** {======================================================
229157** Quicksort
230** (based on 'Algorithms in MODULA-3', Robert Sedgewick;
158** (based on `Algorithms in MODULA-3', Robert Sedgewick;
231159**  Addison-Wesley, 1993.)
232160** =======================================================
233161*/
234162
235163
236static void set2 (lua_State *L, TabA *ta, int i, int j) {
237  (*ta->seti)(L, 1, i);
238  (*ta->seti)(L, 1, j);
164static void set2 (lua_State *L, int i, int j) {
165  lua_rawseti(L, 1, i);
166  lua_rawseti(L, 1, j);
239167}
240168
241169static int sort_comp (lua_State *L, int a, int b) {
r242959r242960
243171    int res;
244172    lua_pushvalue(L, 2);
245173    lua_pushvalue(L, a-1);  /* -1 to compensate function */
246    lua_pushvalue(L, b-2);  /* -2 to compensate function and 'a' */
174    lua_pushvalue(L, b-2);  /* -2 to compensate function and `a' */
247175    lua_call(L, 2, 1);
248176    res = lua_toboolean(L, -1);
249177    lua_pop(L, 1);
r242959r242960
253181    return lua_compare(L, a, b, LUA_OPLT);
254182}
255183
256static void auxsort (lua_State *L, TabA *ta, int l, int u) {
184static void auxsort (lua_State *L, int l, int u) {
257185  while (l < u) {  /* for tail recursion */
258186    int i, j;
259187    /* sort elements a[l], a[(l+u)/2] and a[u] */
260    (*ta->geti)(L, 1, l);
261    (*ta->geti)(L, 1, u);
188    lua_rawgeti(L, 1, l);
189    lua_rawgeti(L, 1, u);
262190    if (sort_comp(L, -1, -2))  /* a[u] < a[l]? */
263      set2(L, ta, l, u);  /* swap a[l] - a[u] */
191      set2(L, l, u);  /* swap a[l] - a[u] */
264192    else
265193      lua_pop(L, 2);
266194    if (u-l == 1) break;  /* only 2 elements */
267195    i = (l+u)/2;
268    (*ta->geti)(L, 1, i);
269    (*ta->geti)(L, 1, l);
196    lua_rawgeti(L, 1, i);
197    lua_rawgeti(L, 1, l);
270198    if (sort_comp(L, -2, -1))  /* a[i]<a[l]? */
271      set2(L, ta, i, l);
199      set2(L, i, l);
272200    else {
273201      lua_pop(L, 1);  /* remove a[l] */
274      (*ta->geti)(L, 1, u);
202      lua_rawgeti(L, 1, u);
275203      if (sort_comp(L, -1, -2))  /* a[u]<a[i]? */
276        set2(L, ta, i, u);
204        set2(L, i, u);
277205      else
278206        lua_pop(L, 2);
279207    }
280208    if (u-l == 2) break;  /* only 3 elements */
281    (*ta->geti)(L, 1, i);  /* Pivot */
209    lua_rawgeti(L, 1, i);  /* Pivot */
282210    lua_pushvalue(L, -1);
283    (*ta->geti)(L, 1, u-1);
284    set2(L, ta, i, u-1);
211    lua_rawgeti(L, 1, u-1);
212    set2(L, i, u-1);
285213    /* a[l] <= P == a[u-1] <= a[u], only need to sort from l+1 to u-2 */
286214    i = l; j = u-1;
287215    for (;;) {  /* invariant: a[l..i] <= P <= a[j..u] */
288216      /* repeat ++i until a[i] >= P */
289      while ((*ta->geti)(L, 1, ++i), sort_comp(L, -1, -2)) {
217      while (lua_rawgeti(L, 1, ++i), sort_comp(L, -1, -2)) {
290218        if (i>=u) luaL_error(L, "invalid order function for sorting");
291219        lua_pop(L, 1);  /* remove a[i] */
292220      }
293221      /* repeat --j until a[j] <= P */
294      while ((*ta->geti)(L, 1, --j), sort_comp(L, -3, -1)) {
222      while (lua_rawgeti(L, 1, --j), sort_comp(L, -3, -1)) {
295223        if (j<=l) luaL_error(L, "invalid order function for sorting");
296224        lua_pop(L, 1);  /* remove a[j] */
297225      }
r242959r242960
299227        lua_pop(L, 3);  /* pop pivot, a[i], a[j] */
300228        break;
301229      }
302      set2(L, ta, i, j);
230      set2(L, i, j);
303231    }
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] */
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] */
307235    /* a[l..i-1] <= a[i] == P <= a[i+1..u] */
308236    /* adjust so that smaller half is in [j..i] and larger one in [l..u] */
309237    if (i-l < u-i) {
r242959r242960
312240    else {
313241      j=i+1; i=u; u=j-2;
314242    }
315    auxsort(L, ta, j, i);  /* call recursively the smaller one */
243    auxsort(L, j, i);  /* call recursively the smaller one */
316244  }  /* repeat the routine for the larger one */
317245}
318246
319247static int sort (lua_State *L) {
320  TabA ta;
321  int n = (int)aux_getn(L, 1, &ta);
322  luaL_checkstack(L, 50, "");  /* assume array is smaller than 2^50 */
248  int n = aux_getn(L, 1);
249  luaL_checkstack(L, 40, "");  /* assume array is smaller than 2^40 */
323250  if (!lua_isnoneornil(L, 2))  /* is there a 2nd argument? */
324251    luaL_checktype(L, 2, LUA_TFUNCTION);
325  lua_settop(L, 2);  /* make sure there are two arguments */
326  auxsort(L, &ta, 1, n);
252  lua_settop(L, 2);  /* make sure there is two arguments */
253  auxsort(L, 1, n);
327254  return 0;
328255}
329256
r242959r242960
339266  {"pack", pack},
340267  {"unpack", unpack},
341268  {"remove", tremove},
342  {"move", tmove},
343269  {"sort", sort},
344270  {NULL, NULL}
345271};
trunk/3rdparty/lua/src/ltm.c
r242959r242960
11/*
2** $Id: ltm.c,v 2.33 2014/11/21 12:15:57 roberto Exp $
2** $Id: ltm.c,v 2.14.1.1 2013/04/12 18:48:47 roberto Exp $
33** Tag methods
44** See Copyright Notice in lua.h
55*/
66
7#define ltm_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
138#include <string.h>
149
10#define ltm_c
11#define LUA_CORE
12
1513#include "lua.h"
1614
17#include "ldebug.h"
18#include "ldo.h"
1915#include "lobject.h"
2016#include "lstate.h"
2117#include "lstring.h"
2218#include "ltable.h"
2319#include "ltm.h"
24#include "lvm.h"
2520
2621
2722static const char udatatypename[] = "userdata";
r242959r242960
3025  "no value",
3126  "nil", "boolean", udatatypename, "number",
3227  "string", "table", "function", udatatypename, "thread",
33  "proto" /* this last case is used for tests only */
28  "proto", "upval"  /* these last two cases are used for tests only */
3429};
3530
3631
r242959r242960
3833  static const char *const luaT_eventname[] = {  /* ORDER TM */
3934    "__index", "__newindex",
4035    "__gc", "__mode", "__len", "__eq",
41    "__add", "__sub", "__mul", "__mod", "__pow",
42    "__div", "__idiv",
43    "__band", "__bor", "__bxor", "__shl", "__shr",
44    "__unm", "__bnot", "__lt", "__le",
36    "__add", "__sub", "__mul", "__div", "__mod",
37    "__pow", "__unm", "__lt", "__le",
4538    "__concat", "__call"
4639  };
4740  int i;
4841  for (i=0; i<TM_N; i++) {
4942    G(L)->tmname[i] = luaS_new(L, luaT_eventname[i]);
50    luaC_fix(L, obj2gco(G(L)->tmname[i]));  /* never collect these names */
43    luaS_fix(G(L)->tmname[i]);  /* never collect these names */
5144  }
5245}
5346
r242959r242960
6962
7063const TValue *luaT_gettmbyobj (lua_State *L, const TValue *o, TMS event) {
7164  Table *mt;
72  switch (ttnov(o)) {
65  switch (ttypenv(o)) {
7366    case LUA_TTABLE:
7467      mt = hvalue(o)->metatable;
7568      break;
r242959r242960
7770      mt = uvalue(o)->metatable;
7871      break;
7972    default:
80      mt = G(L)->mt[ttnov(o)];
73      mt = G(L)->mt[ttypenv(o)];
8174  }
8275  return (mt ? luaH_getstr(mt, G(L)->tmname[event]) : luaO_nilobject);
8376}
8477
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
r242959r242960
11/*
2** $Id: ltm.h,v 2.21 2014/10/25 11:50:46 roberto Exp $
2** $Id: ltm.h,v 2.11.1.1 2013/04/12 18:48:47 roberto Exp $
33** Tag methods
44** See Copyright Notice in lua.h
55*/
r242959r242960
1313
1414/*
1515* WARNING: if you change the order of this enumeration,
16* grep "ORDER TM" and "ORDER OP"
16* grep "ORDER TM"
1717*/
1818typedef enum {
1919  TM_INDEX,
r242959r242960
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,
2829  TM_MOD,
2930  TM_POW,
30  TM_DIV,
31  TM_IDIV,
32  TM_BAND,
33  TM_BOR,
34  TM_BXOR,
35  TM_SHL,
36  TM_SHR,
3731  TM_UNM,
38  TM_BNOT,
3932  TM_LT,
4033  TM_LE,
4134  TM_CONCAT,
r242959r242960
5144#define fasttm(l,et,e)   gfasttm(G(l), et, e)
5245
5346#define ttypename(x)   luaT_typenames_[(x) + 1]
54#define objtypename(x)   ttypename(ttnov(x))
47#define objtypename(x)   ttypename(ttypenv(x))
5548
5649LUAI_DDEC const char *const luaT_typenames_[LUA_TOTALTAGS];
5750
r242959r242960
6154                                                       TMS event);
6255LUAI_FUNC void luaT_init (lua_State *L);
6356
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
7557#endif
trunk/3rdparty/lua/src/lua.c
r242959r242960
11/*
2** $Id: lua.c,v 1.222 2014/11/11 19:41:27 roberto Exp $
2** $Id: lua.c,v 1.206.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lua stand-alone interpreter
44** See Copyright Notice in lua.h
55*/
66
7#define lua_c
87
9#include "lprefix.h"
10
11
128#include <signal.h>
139#include <stdio.h>
1410#include <stdlib.h>
1511#include <string.h>
1612
13#define lua_c
14
1715#include "lua.h"
1816
1917#include "lauxlib.h"
r242959r242960
3331#define LUA_MAXINPUT      512
3432#endif
3533
36#if !defined(LUA_INIT_VAR)
37#define LUA_INIT_VAR      "LUA_INIT"
34#if !defined(LUA_INIT)
35#define LUA_INIT      "LUA_INIT"
3836#endif
3937
40#define LUA_INITVARVERSION  \
41   LUA_INIT_VAR "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
38#define LUA_INITVERSION  \
39   LUA_INIT "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
4240
4341
4442/*
4543** lua_stdin_is_tty detects whether the standard input is a 'tty' (that
4644** is, whether we're running lua interactively).
4745*/
48#if !defined(lua_stdin_is_tty)   /* { */
49
50#if defined(LUA_USE_POSIX)   /* { */
51
46#if defined(LUA_USE_ISATTY)
5247#include <unistd.h>
5348#define lua_stdin_is_tty()   isatty(0)
54
55#elif defined(LUA_USE_WINDOWS)   /* }{ */
56
49#elif defined(LUA_WIN)
5750#include <io.h>
51#include <stdio.h>
5852#define lua_stdin_is_tty()   _isatty(_fileno(stdin))
59
60#else            /* }{ */
61
62/* ISO C definition */
53#else
6354#define lua_stdin_is_tty()   1  /* assume stdin is a tty */
55#endif
6456
65#endif            /* } */
6657
67#endif            /* } */
68
69
7058/*
7159** lua_readline defines how to show a prompt and then read a line from
7260** the standard input.
7361** lua_saveline defines how to "save" a read line in a "history".
7462** lua_freeline defines how to free a line read by lua_readline.
7563*/
76#if !defined(lua_readline)   /* { */
64#if defined(LUA_USE_READLINE)
7765
78#if defined(LUA_USE_READLINE)   /* { */
79
66#include <stdio.h>
8067#include <readline/readline.h>
8168#include <readline/history.h>
8269#define lua_readline(L,b,p)   ((void)L, ((b)=readline(p)) != NULL)
r242959r242960
8572          add_history(lua_tostring(L, idx));  /* add it to history */
8673#define lua_freeline(L,b)   ((void)L, free(b))
8774
88#else            /* }{ */
75#elif !defined(lua_readline)
8976
9077#define lua_readline(L,b,p) \
9178        ((void)L, fputs(p, stdout), fflush(stdout),  /* show prompt */ \
r242959r242960
9380#define lua_saveline(L,idx)   { (void)L; (void)idx; }
9481#define lua_freeline(L,b)   { (void)L; (void)b; }
9582
96#endif            /* } */
83#endif
9784
98#endif            /* } */
9985
10086
10187
102
10388static lua_State *globalL = NULL;
10489
10590static const char *progname = LUA_PROGNAME;
10691
10792
108/*
109** Hook set by signal function to stop the interpreter.
110*/
93
11194static void lstop (lua_State *L, lua_Debug *ar) {
11295  (void)ar;  /* unused arg. */
113  lua_sethook(L, NULL, 0, 0);  /* reset hook */
96  lua_sethook(L, NULL, 0, 0);
11497  luaL_error(L, "interrupted!");
11598}
11699
117100
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*/
124101static void laction (int i) {
125  signal(i, SIG_DFL); /* if another SIGINT happens, terminate process */
102  signal(i, SIG_DFL); /* if another SIGINT happens before lstop,
103                              terminate process (default action) */
126104  lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1);
127105}
128106
129107
130108static void print_usage (const char *badoption) {
131  lua_writestringerror("%s: ", progname);
109  luai_writestringerror("%s: ", progname);
132110  if (badoption[1] == 'e' || badoption[1] == 'l')
133    lua_writestringerror("'%s' needs argument\n", badoption);
111    luai_writestringerror("'%s' needs argument\n", badoption);
134112  else
135    lua_writestringerror("unrecognized option '%s'\n", badoption);
136  lua_writestringerror(
113    luai_writestringerror("unrecognized option '%s'\n", badoption);
114  luai_writestringerror(
137115  "usage: %s [options] [script [args]]\n"
138116  "Available options are:\n"
139  "  -e stat  execute string 'stat'\n"
140  "  -i       enter interactive mode after executing 'script'\n"
141  "  -l name  require library 'name'\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"
142120  "  -v       show version information\n"
143121  "  -E       ignore environment variables\n"
144122  "  --       stop handling options\n"
r242959r242960
148126}
149127
150128
151/*
152** Prints an error message, adding the program name in front of it
153** (if present)
154*/
155129static void l_message (const char *pname, const char *msg) {
156  if (pname) lua_writestringerror("%s: ", pname);
157  lua_writestringerror("%s\n", msg);
130  if (pname) luai_writestringerror("%s: ", pname);
131  luai_writestringerror("%s\n", msg);
158132}
159133
160134
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*/
166135static int report (lua_State *L, int status) {
167  if (status != LUA_OK) {
136  if (status != LUA_OK && !lua_isnil(L, -1)) {
168137    const char *msg = lua_tostring(L, -1);
138    if (msg == NULL) msg = "(error object is not a string)";
169139    l_message(progname, msg);
170    lua_pop(L, 1);  /* remove message */
140    lua_pop(L, 1);
141    /* force a complete garbage collection in case of errors */
142    lua_gc(L, LUA_GCCOLLECT, 0);
171143  }
172144  return status;
173145}
174146
175147
176/*
177** Message handler used to run all chunks
178*/
179static int msghandler (lua_State *L) {
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) {
180161  const char *msg = lua_tostring(L, 1);
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));
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)");
188167  }
189  luaL_traceback(L, L, msg, 1);  /* append a standard traceback */
190  return 1;  /* return the traceback */
168  return 1;
191169}
192170
193171
194/*
195** Interface to 'lua_pcall', which sets appropriate message function
196** and C-signal handler. Used to run all chunks.
197*/
198172static int docall (lua_State *L, int narg, int nres) {
199173  int status;
200174  int base = lua_gettop(L) - narg;  /* function index */
201  lua_pushcfunction(L, msghandler);  /* push message handler */
202  lua_insert(L, base);  /* put it under function and args */
175  lua_pushcfunction(L, traceback);  /* push traceback function */
176  lua_insert(L, base);  /* put it under chunk and args */
203177  globalL = L;  /* to be available to 'laction' */
204  signal(SIGINT, laction);  /* set C-signal handler */
178  signal(SIGINT, laction);
205179  status = lua_pcall(L, narg, nres, base);
206  signal(SIGINT, SIG_DFL); /* reset C-signal handler */
207  lua_remove(L, base);  /* remove message handler from the stack */
180  signal(SIGINT, SIG_DFL);
181  lua_remove(L, base);  /* remove traceback function */
208182  return status;
209183}
210184
211185
212186static void print_version (void) {
213  lua_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
214  lua_writeline();
187  luai_writestring(LUA_COPYRIGHT, strlen(LUA_COPYRIGHT));
188  luai_writeline();
215189}
216190
217191
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++) {
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++)
232200    lua_pushstring(L, argv[i]);
233    lua_rawseti(L, -2, i - script);
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);
234205  }
235  lua_setglobal(L, "arg");
206  return narg;
236207}
237208
238209
239static int dochunk (lua_State *L, int status) {
210static int dofile (lua_State *L, const char *name) {
211  int status = luaL_loadfile(L, name);
240212  if (status == LUA_OK) status = docall(L, 0, 0);
241213  return report(L, status);
242214}
243215
244216
245static int dofile (lua_State *L, const char *name) {
246  return dochunk(L, luaL_loadfile(L, name));
247}
248
249
250217static int dostring (lua_State *L, const char *s, const char *name) {
251  return dochunk(L, luaL_loadbuffer(L, s, strlen(s), 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);
252221}
253222
254223
255/*
256** Calls 'require(name)' and stores the result in a global variable
257** with the given name.
258*/
259224static int dolibrary (lua_State *L, const char *name) {
260225  int status;
261226  lua_getglobal(L, "require");
r242959r242960
267232}
268233
269234
270/*
271** Returns the string to be used as a prompt by the interpreter.
272*/
273235static const char *get_prompt (lua_State *L, int firstline) {
274236  const char *p;
275237  lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2");
r242959r242960
282244#define EOFMARK      "<eof>"
283245#define marklen      (sizeof(EOFMARK)/sizeof(char) - 1)
284246
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*/
291247static int incomplete (lua_State *L, int status) {
292248  if (status == LUA_ERRSYNTAX) {
293249    size_t lmsg;
r242959r242960
301257}
302258
303259
304/*
305** Prompt the user, read a line, and push it into the Lua stack.
306*/
307260static int pushline (lua_State *L, int firstline) {
308261  char buffer[LUA_MAXINPUT];
309262  char *b = buffer;
310263  size_t l;
311264  const char *prmt = get_prompt(L, firstline);
312265  int readstatus = lua_readline(L, b, prmt);
266  lua_pop(L, 1);  /* remove result from 'get_prompt' */
313267  if (readstatus == 0)
314    return 0;  /* no input (prompt will be popped by caller) */
315  lua_pop(L, 1);  /* remove prompt */
268    return 0;  /* no input */
316269  l = strlen(b);
317270  if (l > 0 && b[l-1] == '\n')  /* line ends with newline? */
318271    b[l-1] = '\0';  /* remove it */
319  if (firstline && b[0] == '=')  /* for compatibility with 5.2, ... */
320    lua_pushfstring(L, "return %s", b + 1);  /* change '=' to 'return' */
272  if (firstline && b[0] == '=')  /* first line starts with `=' ? */
273    lua_pushfstring(L, "return %s", b+1);  /* change it to `return' */
321274  else
322275    lua_pushstring(L, b);
323276  lua_freeline(L, b);
r242959r242960
325278}
326279
327280
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*/
370281static int loadline (lua_State *L) {
371282  int status;
372283  lua_settop(L, 0);
373284  if (!pushline(L, 1))
374285    return -1;  /* no input */
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);
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 */
380299  return status;
381300}
382301
383302
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) {
303static void dotty (lua_State *L) {
405304  int status;
406305  const char *oldprogname = progname;
407  progname = NULL;  /* no 'progname' on errors in interactive mode */
306  progname = NULL;
408307  while ((status = loadline(L)) != -1) {
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);
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    }
413319  }
414320  lua_settop(L, 0);  /* clear stack */
415  lua_writeline();
321  luai_writeline();
416322  progname = oldprogname;
417323}
418324
419325
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) {
326static int handle_script (lua_State *L, char **argv, int n) {
437327  int status;
438  const char *fname = argv[0];
439  if (strcmp(fname, "-") == 0 && strcmp(argv[-1], "--") != 0)
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)
440333    fname = NULL;  /* stdin */
441334  status = luaL_loadfile(L, fname);
442  if (status == LUA_OK) {
443    int n = pushargs(L);  /* push arguments to script */
444    status = docall(L, n, LUA_MULTRET);
445  }
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);
446340  return report(L, status);
447341}
448342
449343
344/* check that argument has no extra characters at the end */
345#define noextrachars(x)      {if ((x)[2] != '\0') return -1;}
450346
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 */
457347
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;
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) {
466358  int i;
467359  for (i = 1; argv[i] != NULL; i++) {
468    *first = i;
469360    if (argv[i][0] != '-')  /* not an option? */
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 '-' */
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;
479368      case 'E':
480        if (argv[i][2] != '\0')  /* extra characters after 1st? */
481          return has_error;  /* invalid option */
482        args |= has_E;
369        args[has_E] = 1;
483370        break;
484371      case 'i':
485        args |= has_i;  /* goes through  (-i implies -v) */
372        noextrachars(argv[i]);
373        args[has_i] = 1;  /* go through */
486374      case 'v':
487        if (argv[i][2] != '\0')  /* extra characters after 1st? */
488          return has_error;  /* invalid option */
489        args |= has_v;
375        noextrachars(argv[i]);
376        args[has_v] = 1;
490377        break;
491378      case 'e':
492        args |= has_e;  /* go through */
379        args[has_e] = 1;  /* go through */
493380      case 'l':  /* both options need an argument */
494381        if (argv[i][2] == '\0') {  /* no concatenated argument? */
495382          i++;  /* try next 'argv' */
496383          if (argv[i] == NULL || argv[i][0] == '-')
497            return has_error;  /* no next argument or it is another option */
384            return -(i - 1);  /* no next argument or it is another option */
498385        }
499386        break;
500      default:  /* invalid option */
501        return has_error;
387      default:  /* invalid option; return its index... */
388        return -i;  /* ...as a negative value */
502389    }
503390  }
504  *first = i;  /* no script name */
505  return args;
391  return 0;
506392}
507393
508394
509/*
510** Processes options 'e' and 'l', which involve running Lua code.
511** Returns 0 if some code raises an error.
512*/
513395static int runargs (lua_State *L, char **argv, int n) {
514396  int i;
515397  for (i = 1; i < n; i++) {
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;
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;
528417    }
529418  }
530419  return 1;
r242959r242960
532421
533422
534423static int handle_luainit (lua_State *L) {
535  const char *name = "=" LUA_INITVARVERSION;
424  const char *name = "=" LUA_INITVERSION;
536425  const char *init = getenv(name + 1);
537426  if (init == NULL) {
538    name = "=" LUA_INIT_VAR;
427    name = "=" LUA_INIT;
539428    init = getenv(name + 1);  /* try alternative name */
540429  }
541430  if (init == NULL) return LUA_OK;
r242959r242960
546435}
547436
548437
549/*
550** Main body of stand-alone interpreter (to be called in protected mode).
551** Reads the options and handles them all.
552*/
553438static int pmain (lua_State *L) {
554439  int argc = (int)lua_tointeger(L, 1);
555440  char **argv = (char **)lua_touserdata(L, 2);
556441  int script;
557  int args = collectargs(argv, &script);
558  luaL_checkversion(L);  /* check that interpreter has correct version */
442  int args[num_has];
443  args[has_i] = args[has_v] = args[has_e] = args[has_E] = 0;
559444  if (argv[0] && argv[0][0]) progname = argv[0];
560  if (args == has_error) {  /* bad arg? */
561    print_usage(argv[script]);  /* 'script' has index of bad arg. */
445  script = collectargs(argv, args);
446  if (script < 0) {  /* invalid arg? */
447    print_usage(argv[-script]);
562448    return 0;
563449  }
564  if (args & has_v)  /* option '-v'? */
565    print_version();
566  if (args & has_E) {  /* option '-E'? */
450  if (args[has_v]) print_version();
451  if (args[has_E]) {  /* option '-E'? */
567452    lua_pushboolean(L, 1);  /* signal for libraries to ignore env. vars. */
568453    lua_setfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
569454  }
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? */
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()) {
585470      print_version();
586      doREPL(L);  /* do read-eval-print loop */
471      dotty(L);
587472    }
588473    else dofile(L, NULL);  /* executes stdin as a file */
589474  }
r242959r242960
599484    l_message(argv[0], "cannot create state: not enough memory");
600485    return EXIT_FAILURE;
601486  }
602  lua_pushcfunction(L, &pmain);  /* to call 'pmain' in protected mode */
487  /* call 'pmain' in protected mode */
488  lua_pushcfunction(L, &pmain);
603489  lua_pushinteger(L, argc);  /* 1st argument */
604490  lua_pushlightuserdata(L, argv); /* 2nd argument */
605  status = lua_pcall(L, 2, 1, 0);  /* do the call */
491  status = lua_pcall(L, 2, 1, 0);
606492  result = lua_toboolean(L, -1);  /* get result */
607  report(L, status);
493  finalreport(L, status);
608494  lua_close(L);
609495  return (result && status == LUA_OK) ? EXIT_SUCCESS : EXIT_FAILURE;
610496}
trunk/3rdparty/lua/src/lua.h
r242959r242960
11/*
2** $Id: lua.h,v 1.325 2014/12/26 17:24:27 roberto Exp $
2** $Id: lua.h,v 1.285.1.2 2013/11/11 12:09:16 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
r242959r242960
1717
1818
1919#define LUA_VERSION_MAJOR   "5"
20#define LUA_VERSION_MINOR   "3"
21#define LUA_VERSION_NUM      503
22#define LUA_VERSION_RELEASE   "0"
20#define LUA_VERSION_MINOR   "2"
21#define LUA_VERSION_NUM      502
22#define LUA_VERSION_RELEASE   "3"
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-2015 Lua.org, PUC-Rio"
26#define LUA_COPYRIGHT   LUA_RELEASE "  Copyright (C) 1994-2013 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   "\x1bLua"
31#define LUA_SIGNATURE   "\033Lua"
3232
3333/* option for multiple returns in 'lua_pcall' and 'lua_call' */
3434#define LUA_MULTRET   (-1)
r242959r242960
5353
5454typedef struct lua_State lua_State;
5555
56typedef int (*lua_CFunction) (lua_State *L);
5657
58
5759/*
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/*
5874** basic types
5975*/
6076#define LUA_TNONE      (-1)
r242959r242960
93109/* unsigned integer type */
94110typedef LUA_UNSIGNED lua_Unsigned;
95111
96/* type for continuation-function contexts */
97typedef LUA_KCONTEXT lua_KContext;
98112
99113
100114/*
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/*
127115** generic extra include file
128116*/
129117#if defined(LUA_USER_H)
r242959r242960
157145LUA_API int   (lua_gettop) (lua_State *L);
158146LUA_API void  (lua_settop) (lua_State *L, int idx);
159147LUA_API void  (lua_pushvalue) (lua_State *L, int idx);
160LUA_API void  (lua_rotate) (lua_State *L, int idx, int n);
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);
161151LUA_API void  (lua_copy) (lua_State *L, int fromidx, int toidx);
162LUA_API int   (lua_checkstack) (lua_State *L, int n);
152LUA_API int   (lua_checkstack) (lua_State *L, int sz);
163153
164154LUA_API void  (lua_xmove) (lua_State *from, lua_State *to, int n);
165155
r242959r242960
171161LUA_API int             (lua_isnumber) (lua_State *L, int idx);
172162LUA_API int             (lua_isstring) (lua_State *L, int idx);
173163LUA_API int             (lua_iscfunction) (lua_State *L, int idx);
174LUA_API int             (lua_isinteger) (lua_State *L, int idx);
175164LUA_API int             (lua_isuserdata) (lua_State *L, int idx);
176165LUA_API int             (lua_type) (lua_State *L, int idx);
177166LUA_API const char     *(lua_typename) (lua_State *L, int tp);
178167
179168LUA_API lua_Number      (lua_tonumberx) (lua_State *L, int idx, int *isnum);
180169LUA_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);
181171LUA_API int             (lua_toboolean) (lua_State *L, int idx);
182172LUA_API const char     *(lua_tolstring) (lua_State *L, int idx, size_t *len);
183173LUA_API size_t          (lua_rawlen) (lua_State *L, int idx);
r242959r242960
191181** Comparison and arithmetic functions
192182*/
193183
194#define LUA_OPADD   0   /* ORDER TM, ORDER OP */
184#define LUA_OPADD   0   /* ORDER TM */
195185#define LUA_OPSUB   1
196186#define LUA_OPMUL   2
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
187#define LUA_OPDIV   3
188#define LUA_OPMOD   4
189#define LUA_OPPOW   5
190#define LUA_OPUNM   6
208191
209192LUA_API void  (lua_arith) (lua_State *L, int op);
210193
r242959r242960
222205LUA_API void        (lua_pushnil) (lua_State *L);
223206LUA_API void        (lua_pushnumber) (lua_State *L, lua_Number n);
224207LUA_API void        (lua_pushinteger) (lua_State *L, lua_Integer n);
225LUA_API const char *(lua_pushlstring) (lua_State *L, const char *s, size_t len);
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);
226210LUA_API const char *(lua_pushstring) (lua_State *L, const char *s);
227211LUA_API const char *(lua_pushvfstring) (lua_State *L, const char *fmt,
228212                                                      va_list argp);
r242959r242960
236220/*
237221** get functions (Lua -> stack)
238222*/
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
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);
247229LUA_API void  (lua_createtable) (lua_State *L, int narr, int nrec);
248230LUA_API void *(lua_newuserdata) (lua_State *L, size_t sz);
249231LUA_API int   (lua_getmetatable) (lua_State *L, int objindex);
250LUA_API int  (lua_getuservalue) (lua_State *L, int idx);
232LUA_API void  (lua_getuservalue) (lua_State *L, int idx);
251233
252234
253235/*
254236** set functions (stack -> Lua)
255237*/
256LUA_API void  (lua_setglobal) (lua_State *L, const char *name);
238LUA_API void  (lua_setglobal) (lua_State *L, const char *var);
257239LUA_API void  (lua_settable) (lua_State *L, int idx);
258240LUA_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);
260241LUA_API void  (lua_rawset) (lua_State *L, int idx);
261LUA_API void  (lua_rawseti) (lua_State *L, int idx, lua_Integer n);
242LUA_API void  (lua_rawseti) (lua_State *L, int idx, int n);
262243LUA_API void  (lua_rawsetp) (lua_State *L, int idx, const void *p);
263244LUA_API int   (lua_setmetatable) (lua_State *L, int objindex);
264245LUA_API void  (lua_setuservalue) (lua_State *L, int idx);
r242959r242960
267248/*
268249** 'load' and 'call' functions (load and run Lua code)
269250*/
270LUA_API void  (lua_callk) (lua_State *L, int nargs, int nresults,
271                           lua_KContext ctx, lua_KFunction k);
251LUA_API void  (lua_callk) (lua_State *L, int nargs, int nresults, int ctx,
252                           lua_CFunction k);
272253#define lua_call(L,n,r)      lua_callk(L, (n), (r), 0, NULL)
273254
255LUA_API int   (lua_getctx) (lua_State *L, int *ctx);
256
274257LUA_API int   (lua_pcallk) (lua_State *L, int nargs, int nresults, int errfunc,
275                            lua_KContext ctx, lua_KFunction k);
258                            int ctx, lua_CFunction k);
276259#define lua_pcall(L,n,r,f)   lua_pcallk(L, (n), (r), (f), 0, NULL)
277260
278261LUA_API int   (lua_load) (lua_State *L, lua_Reader reader, void *dt,
279                          const char *chunkname, const char *mode);
262                                        const char *chunkname,
263                                        const char *mode);
280264
281LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data, int strip);
265LUA_API int (lua_dump) (lua_State *L, lua_Writer writer, void *data);
282266
283267
284268/*
285269** coroutine functions
286270*/
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
271LUA_API int  (lua_yieldk) (lua_State *L, int nresults, int ctx,
272                           lua_CFunction k);
293273#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);
294276
295
296277/*
297278** garbage-collection function and options
298279*/
r242959r242960
305286#define LUA_GCSTEP      5
306287#define LUA_GCSETPAUSE      6
307288#define LUA_GCSETSTEPMUL   7
289#define LUA_GCSETMAJORINC   8
308290#define LUA_GCISRUNNING      9
291#define LUA_GCGEN      10
292#define LUA_GCINC      11
309293
310294LUA_API int (lua_gc) (lua_State *L, int what, int data);
311295
r242959r242960
321305LUA_API void  (lua_concat) (lua_State *L, int n);
322306LUA_API void  (lua_len)    (lua_State *L, int idx);
323307
324LUA_API size_t   (lua_stringtonumber) (lua_State *L, const char *s);
325
326308LUA_API lua_Alloc (lua_getallocf) (lua_State *L, void **ud);
327309LUA_API void      (lua_setallocf) (lua_State *L, lua_Alloc f, void *ud);
328310
329311
330312
331313/*
332** {==============================================================
314** ===============================================================
333315** some useful macros
334316** ===============================================================
335317*/
336318
337#define lua_getextraspace(L)   ((void *)((char *)(L) - LUA_EXTRASPACE))
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)
338322
339#define lua_tonumber(L,i)   lua_tonumberx(L,(i),NULL)
340#define lua_tointeger(L,i)   lua_tointegerx(L,(i),NULL)
341
342323#define lua_pop(L,n)      lua_settop(L, -(n)-1)
343324
344325#define lua_newtable(L)      lua_createtable(L, 0, 0)
r242959r242960
365346#define lua_tostring(L,i)   lua_tolstring(L, (i), NULL)
366347
367348
368#define lua_insert(L,idx)   lua_rotate(L, (idx), 1)
369349
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
377350/*
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/*
392351** {======================================================================
393352** Debug API
394353** =======================================================================
r242959r242960
431390LUA_API void  (lua_upvaluejoin) (lua_State *L, int fidx1, int n1,
432391                                               int fidx2, int n2);
433392
434LUA_API void (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);
393LUA_API int (lua_sethook) (lua_State *L, lua_Hook func, int mask, int count);
435394LUA_API lua_Hook (lua_gethook) (lua_State *L);
436395LUA_API int (lua_gethookmask) (lua_State *L);
437396LUA_API int (lua_gethookcount) (lua_State *L);
r242959r242960
459418
460419
461420/******************************************************************************
462* Copyright (C) 1994-2015 Lua.org, PUC-Rio.
421* Copyright (C) 1994-2013 Lua.org, PUC-Rio.
463422*
464423* Permission is hereby granted, free of charge, to any person obtaining
465424* a copy of this software and associated documentation files (the
trunk/3rdparty/lua/src/luac.c
r242959r242960
11/*
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)
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)
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>
137#include <errno.h>
148#include <stdio.h>
159#include <stdlib.h>
1610#include <string.h>
1711
12#define luac_c
13#define LUA_CORE
14
1815#include "lua.h"
1916#include "lauxlib.h"
2017
r242959r242960
5047static void usage(const char* message)
5148{
5249 if (*message=='-')
53  fprintf(stderr,"%s: unrecognized option '%s'\n",progname,message);
50  fprintf(stderr,"%s: unrecognized option " LUA_QS "\n",progname,message);
5451 else
5552  fprintf(stderr,"%s: %s\n",progname,message);
5653 fprintf(stderr,
5754  "usage: %s [options] [filenames]\n"
5855  "Available options are:\n"
5956  "  -l       list (use -l -l for full listing)\n"
60  "  -o name  output to file 'name' (default is \"%s\")\n"
57  "  -o name  output to file " LUA_QL("name") " (default is \"%s\")\n"
6158  "  -p       parse only\n"
6259  "  -s       strip debug information\n"
6360  "  -v       show version information\n"
r242959r242960
9289  {
9390   output=argv[++i];
9491   if (output==NULL || *output==0 || (*output=='-' && output[1]!=0))
95    usage("'-o' needs argument");
92    usage(LUA_QL("-o") " needs argument");
9693   if (IS("-")) output=NULL;
9794  }
9895  else if (IS("-p"))         /* parse only */
r242959r242960
206203}
207204
208205/*
209** $Id: print.c,v 1.76 2015/01/05 16:12:50 lhf Exp $
206** $Id: print.c,v 1.69 2013/07/04 01:03:46 lhf Exp $
210207** print bytecodes
211208** See Copyright Notice in lua.h
212209*/
r242959r242960
226223static void PrintString(const TString* ts)
227224{
228225 const char* s=getstr(ts);
229 size_t i,n=ts->len;
226 size_t i,n=ts->tsv.len;
230227 printf("%c",'"');
231228 for (i=0; i<n; i++)
232229 {
r242959r242960
254251static void PrintConstant(const Proto* f, int i)
255252{
256253 const TValue* o=&f->k[i];
257 switch (ttype(o))
254 switch (ttypenv(o))
258255 {
259256  case LUA_TNIL:
260257   printf("nil");
r242959r242960
262259  case LUA_TBOOLEAN:
263260   printf(bvalue(o) ? "true" : "false");
264261   break;
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");
262  case LUA_TNUMBER:
263   printf(LUA_NUMBER_FMT,nvalue(o));
271264   break;
272   }
273  case LUA_TNUMINT:
274   printf(LUA_INTEGER_FMT,ivalue(o));
265  case LUA_TSTRING:
266   PrintString(rawtsvalue(o));
275267   break;
276  case LUA_TSHRSTR: case LUA_TLNGSTR:
277   PrintString(tsvalue(o));
278   break;
279268  default:            /* cannot happen */
280269   printf("? type=%d",ttype(o));
281270   break;
r242959r242960
348337   case OP_ADD:
349338   case OP_SUB:
350339   case OP_MUL:
351   case OP_POW:
352340   case OP_DIV:
353   case OP_IDIV:
354   case OP_BAND:
355   case OP_BOR:
356   case OP_BXOR:
357   case OP_SHL:
358   case OP_SHR:
341   case OP_POW:
359342   case OP_EQ:
360343   case OP_LT:
361344   case OP_LE:
trunk/3rdparty/lua/src/luaconf.h
r242959r242960
11/*
2** $Id: luaconf.h,v 1.238 2014/12/29 13:27:55 roberto Exp $
2** $Id: luaconf.h,v 1.176.1.1 2013/04/12 18:48:47 roberto Exp $
33** Configuration file for Lua
44** See Copyright Notice in lua.h
55*/
66
77
8#ifndef luaconf_h
9#define luaconf_h
8#ifndef lconfig_h
9#define lconfig_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** {====================================================================
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** =====================================================================
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.
2826*/
27#if !defined(LUA_ANSI) && defined(__STRICT_ANSI__)
28#define LUA_ANSI
29#endif
2930
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 */
3731
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 */
32#if !defined(LUA_ANSI) && defined(_WIN32) && !defined(_WIN32_WCE)
33#define LUA_WIN      /* enable goodies for regular Windows platforms */
5234#endif
5335
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 */
36#if defined(LUA_WIN)
37#define LUA_DL_DLL
38#define LUA_USE_AFORMAT      /* assume 'printf' handles 'aA' specifiers */
5839#endif
5940
6041
42
6143#if defined(LUA_USE_LINUX)
6244#define LUA_USE_POSIX
6345#define LUA_USE_DLOPEN      /* needs an extra library: -ldl */
6446#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 */
6550#endif
6651
67
6852#if defined(LUA_USE_MACOSX)
6953#define LUA_USE_POSIX
70#define LUA_USE_DLOPEN      /* MacOS does not need -ldl */
54#define LUA_USE_DLOPEN      /* does not need -ldl */
7155#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 */
7259#endif
7360
7461
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
8362
84
85
8663/*
87@@ LUAI_BITSINT defines the (minimum) number of bits in an 'int'.
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.
8867*/
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
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
9574#endif
9675
9776
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*/
10977
110#if defined(LUA_32BITS)      /* { */
11178/*
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/*
14979@@ LUA_PATH_DEFAULT is the default path that Lua uses to look for
150** Lua libraries.
80@* Lua libraries.
15181@@ LUA_CPATH_DEFAULT is the default path that Lua uses to look for
152** C libraries.
82@* C libraries.
15383** CHANGE them if your machine has a non-conventional directory
15484** hierarchy or if you want to install your libraries in
15585** non-conventional directories.
15686*/
157#define LUA_VDIR   LUA_VERSION_MAJOR "." LUA_VERSION_MINOR
158#if defined(_WIN32)    /* { */
87#if defined(_WIN32)   /* { */
15988/*
16089** In Windows, any exclamation mark ('!') in the path is replaced by the
16190** path of the directory of the executable file of the current process.
16291*/
16392#define LUA_LDIR   "!\\lua\\"
16493#define LUA_CDIR   "!\\"
165#define LUA_SHRDIR   "!\\..\\share\\lua\\" LUA_VDIR "\\"
16694#define LUA_PATH_DEFAULT  \
16795      LUA_LDIR"?.lua;"  LUA_LDIR"?\\init.lua;" \
168      LUA_CDIR"?.lua;"  LUA_CDIR"?\\init.lua;" \
169      LUA_SHRDIR"?.lua;" LUA_SHRDIR"?\\init.lua;" \
170      ".\\?.lua;" ".\\?\\init.lua"
96      LUA_CDIR"?.lua;"  LUA_CDIR"?\\init.lua;" ".\\?.lua"
17197#define LUA_CPATH_DEFAULT \
172      LUA_CDIR"?.dll;" \
173      LUA_CDIR"..\\lib\\lua\\" LUA_VDIR "\\?.dll;" \
174      LUA_CDIR"loadall.dll;" ".\\?.dll"
98      LUA_CDIR"?.dll;" LUA_CDIR"loadall.dll;" ".\\?.dll"
17599
176100#else         /* }{ */
177101
102#define LUA_VDIR   LUA_VERSION_MAJOR "." LUA_VERSION_MINOR "/"
178103#define LUA_ROOT   "/usr/local/"
179#define LUA_LDIR   LUA_ROOT "share/lua/" LUA_VDIR "/"
180#define LUA_CDIR   LUA_ROOT "lib/lua/" LUA_VDIR "/"
104#define LUA_LDIR   LUA_ROOT "share/lua/" LUA_VDIR
105#define LUA_CDIR   LUA_ROOT "lib/lua/" LUA_VDIR
181106#define LUA_PATH_DEFAULT  \
182107      LUA_LDIR"?.lua;"  LUA_LDIR"?/init.lua;" \
183      LUA_CDIR"?.lua;"  LUA_CDIR"?/init.lua;" \
184      "./?.lua;" "./?/init.lua"
108      LUA_CDIR"?.lua;"  LUA_CDIR"?/init.lua;" "./?.lua"
185109#define LUA_CPATH_DEFAULT \
186110      LUA_CDIR"?.so;" LUA_CDIR"loadall.so;" "./?.so"
187111#endif         /* } */
r242959r242960
198122#define LUA_DIRSEP   "/"
199123#endif
200124
201/* }================================================================== */
202125
203
204126/*
205** {==================================================================
206** Marks for exported symbols in the C code
207** ===================================================================
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.
208130*/
131#define LUA_ENV      "_ENV"
209132
133
210134/*
211135@@ LUA_API is a mark for all core API functions.
212136@@ LUALIB_API is a mark for all auxiliary library functions.
r242959r242960
238162
239163/*
240164@@ LUAI_FUNC is a mark for all extern functions that are not to be
241** exported to outside modules.
165@* exported to outside modules.
242166@@ LUAI_DDEF and LUAI_DDEC are marks for all extern (const) variables
243** that are not to be exported to outside modules (LUAI_DDEF for
244** definitions and LUAI_DDEC for declarations).
167@* that are not to be exported to outside modules (LUAI_DDEF for
168@* definitions and LUAI_DDEC for declarations).
245169** CHANGE them if you need to mark them in some special way. Elf/gcc
246170** (versions 3.2 and later) mark them as "hidden" to optimize access
247171** when Lua is compiled as a shared library. Not all elf targets support
r242959r242960
253177#if defined(__GNUC__) && ((__GNUC__*100 + __GNUC_MINOR__) >= 302) && \
254178    defined(__ELF__)      /* { */
255179#define LUAI_FUNC   __attribute__((visibility("hidden"))) extern
180#define LUAI_DDEC   LUAI_FUNC
181#define LUAI_DDEF   /* empty */
182
256183#else            /* }{ */
257184#define LUAI_FUNC   extern
185#define LUAI_DDEC   extern
186#define LUAI_DDEF   /* empty */
258187#endif            /* } */
259188
260#define LUAI_DDEC   LUAI_FUNC
261#define LUAI_DDEF   /* empty */
262189
263/* }================================================================== */
264190
265
266191/*
267** {==================================================================
268** Compatibility with previous versions
269** ===================================================================
192@@ LUA_QL describes how error messages quote program elements.
193** CHANGE it if you want a different appearance.
270194*/
195#define LUA_QL(x)   "'" x "'"
196#define LUA_QS      LUA_QL("%s")
271197
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)   /* { */
279198
280199/*
281@@ LUA_COMPAT_MATHLIB controls the presence of several deprecated
282** functions in the mathematical library.
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.
283203*/
284#define LUA_COMPAT_MATHLIB
204#define LUA_IDSIZE   60
285205
286/*
287@@ LUA_COMPAT_BITLIB controls the presence of library 'bit32'.
288*/
289#define LUA_COMPAT_BITLIB
290206
291207/*
292@@ LUA_COMPAT_IPAIRS controls the effectiveness of the __ipairs metamethod.
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.)
293211*/
294#define LUA_COMPAT_IPAIRS
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
295217
296218/*
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.)
219@@ luai_writestringerror defines how to print error messages.
220** (A format string with one argument is enough for Lua...)
300221*/
301#define LUA_COMPAT_APIINTCASTS
222#define luai_writestringerror(s,p) \
223   (fprintf(stderr, (s), (p)), fflush(stderr))
302224
303225
304226/*
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.
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.)
309231*/
310/* #define LUA_COMPAT_FLOATSTRING */
232#define LUAI_MAXSHORTLEN        40
311233
312#endif            /* } */
313234
314235
315#if defined(LUA_COMPAT_5_1)   /* { */
236/*
237** {==================================================================
238** Compatibility with previous versions
239** ===================================================================
240*/
316241
317242/*
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/*
318250@@ LUA_COMPAT_UNPACK controls the presence of global 'unpack'.
319251** You can replace it with 'table.unpack'.
320252*/
r242959r242960
378310
379311
380312/*
381** {==================================================================
382** Configuration for Numbers.
383** Change these definitions if no predefined LUA_REAL_* / LUA_INT_*
384** satisfy your needs.
385** ===================================================================
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.
386316*/
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            /* } */
387326
327
388328/*
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.
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.
401337*/
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            /* } */
402348
403#if defined(LUA_REAL_FLOAT)      /* { single float */
404349
405#define LUA_NUMBER   float
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
406361
407#define LUAI_UACNUMBER   double
362/* reserve some space for error handling */
363#define LUAI_FIRSTPSEUDOIDX   (-LUAI_MAXSTACK - 1000)
408364
409#define LUA_NUMBER_FRMLEN   ""
410#define LUA_NUMBER_FMT      "%.7g"
411365
412#define l_mathop(op)      op##f
413366
414#define lua_str2number(s,p)   strtof((s), (p))
415367
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
416373
417#elif defined(LUA_REAL_LONGDOUBLE)   /* }{ long double */
418374
419#define LUA_NUMBER   long double
420375
421#define LUAI_UACNUMBER   long double
422376
423#define LUA_NUMBER_FRMLEN   "L"
424#define LUA_NUMBER_FMT      "%.19Lg"
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*/
425385
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
386#define LUA_NUMBER_DOUBLE
432387#define LUA_NUMBER   double
433388
389/*
390@@ LUAI_UACNUMBER is the result of an 'usual argument conversion'
391@* over a number.
392*/
434393#define LUAI_UACNUMBER   double
435394
436#define LUA_NUMBER_FRMLEN   ""
437#define LUA_NUMBER_FMT      "%.14g"
438395
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
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"
452404#define lua_number2str(s,n)   sprintf((s), LUA_NUMBER_FMT, (n))
405#define LUAI_MAXNUMBER2STR   32 /* 16 digits, sign, point, and \0 */
453406
454407
455408/*
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.)
409@@ l_mathop allows the addition of an 'l' or 'f' to all math operations
462410*/
463#define lua_numbertointeger(n,p) \
464  ((n) >= (LUA_NUMBER)(LUA_MININTEGER) && \
465   (n) < -(LUA_NUMBER)(LUA_MININTEGER) && \
466      (*(p) = (LUA_INTEGER)(n), 1))
411#define l_mathop(x)      (x)
467412
468413
469414/*
470@@ The luai_num* macros define the primitive operations over numbers.
471** They should work for any size of floating numbers.
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.
472421*/
422#define lua_str2number(s,p)   strtod((s), (p))
473423
474/* the following operations need the math library */
475#if defined(lobject_c) || defined(lvm_c)
476#include <math.h>
424#if defined(LUA_USE_STRTODHEX)
425#define lua_strx2number(s,p)   strtod((s), (p))
426#endif
477427
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)))
480428
481429/*
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
430@@ The luai_num* macros define the primitive operations over numbers.
487431*/
488#define luai_nummod(L,a,b,m)  \
489  { (m) = l_mathop(fmod)(a,b); if ((m)*(b) < 0) (m) += (b); }
490432
491/* exponentiation */
492#define luai_numpow(L,a,b)   ((void)L, l_mathop(pow)(a,b))
493
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))
494438#endif
495439
496440/* these are quite standard operations */
r242959r242960
501445#define luai_numdiv(L,a,b)   ((a)/(b))
502446#define luai_numunm(L,a)   (-(a))
503447#define luai_numeq(a,b)      ((a)==(b))
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)))
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)))
507451#endif
508452
509453
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*/
523454
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
532455/*
533** use LUAI_UACINT here to avoid problems with promotions (which
534** can turn a comparison between unsigneds into a signed comparison)
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.)
535459*/
536#define LUA_UNSIGNED      unsigned LUAI_UACINT
460#define LUA_INTEGER   ptrdiff_t
537461
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
593462/*
594** {==================================================================
595** Dependencies with C99
596** ===================================================================
463@@ LUA_UNSIGNED is the integral type used by lua_pushunsigned/lua_tounsigned.
464** It must have at least 32 bits.
597465*/
466#define LUA_UNSIGNED   unsigned LUA_INT32
598467
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
608468
609469
610470/*
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.)
471** Some tricks with doubles
614472*/
615#if !defined(LUA_USE_C89) || defined(LUA_USE_WINDOWS)
616#define LUA_USE_AFORMAT
617#endif
618473
619
474#if defined(LUA_NUMBER_DOUBLE) && !defined(LUA_ANSI)   /* { */
620475/*
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.)
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).
625498*/
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
632499
500/* Microsoft compiler on a Pentium (32 bit) ? */
501#if defined(LUA_WIN) && defined(_MSC_VER) && defined(_M_IX86)   /* { */
633502
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
503#define LUA_MSASMTRICK
504#define LUA_IEEEENDIAN      0
505#define LUA_NANTRICK
641506
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
650507
651/* }================================================================== */
508/* pentium 32 bits? */
509#elif defined(__i386__) || defined(__i386) || defined(__X86__) /* }{ */
652510
511#define LUA_IEEE754TRICK
512#define LUA_IEEELL
513#define LUA_IEEEENDIAN      0
514#define LUA_NANTRICK
653515
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*/
516/* pentium 64 bits? */
517#elif defined(__x86_64)                  /* }{ */
661518
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
519#define LUA_IEEE754TRICK
520#define LUA_IEEEENDIAN      0
673521
674/* reserve some space for error handling */
675#define LUAI_FIRSTPSEUDOIDX   (-LUAI_MAXSTACK - 1000)
522#elif defined(__POWERPC__) || defined(__ppc__)         /* }{ */
676523
524#define LUA_IEEE754TRICK
525#define LUA_IEEEENDIAN      1
677526
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 *))
527#else                        /* }{ */
684528
529/* assume IEEE754 and a 32-bit integer type */
530#define LUA_IEEE754TRICK
685531
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
532#endif                        /* } */
692533
534#endif                     /* } */
693535
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
709536/* }================================================================== */
710537
711538
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")
719539
720540
721
722
723541/* =================================================================== */
724542
725543/*
r242959r242960
729547
730548
731549
732
733
734550#endif
735551
trunk/3rdparty/lua/src/lualib.h
r242959r242960
11/*
2** $Id: lualib.h,v 1.44 2014/02/06 17:32:33 roberto Exp $
2** $Id: lualib.h,v 1.43.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lua standard libraries
44** See Copyright Notice in lua.h
55*/
r242959r242960
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
3532#define LUA_BITLIBNAME   "bit32"
3633LUAMOD_API int (luaopen_bit32) (lua_State *L);
3734
trunk/3rdparty/lua/src/lundump.c
r242959r242960
11/*
2** $Id: lundump.c,v 2.41 2014/11/02 19:19:04 roberto Exp $
2** $Id: lundump.c,v 2.22.1.1 2013/04/12 18:48:47 roberto Exp $
33** load precompiled Lua chunks
44** See Copyright Notice in lua.h
55*/
66
7#include <string.h>
8
79#define lundump_c
810#define LUA_CORE
911
10#include "lprefix.h"
11
12
13#include <string.h>
14
1512#include "lua.h"
1613
1714#include "ldebug.h"
r242959r242960
2320#include "lundump.h"
2421#include "lzio.h"
2522
26
27#if !defined(luai_verifycode)
28#define luai_verifycode(L,b,f)  /* empty */
29#endif
30
31
3223typedef struct {
33  lua_State *L;
34  ZIO *Z;
35  Mbuffer *b;
36  const char *name;
24 lua_State* L;
25 ZIO* Z;
26 Mbuffer* b;
27 const char* name;
3728} LoadState;
3829
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);
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);
4334}
4435
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)
4540
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]))
41#if !defined(luai_verifycode)
42#define luai_verifycode(L,b,f)   /* empty */
43#endif
5144
52static void LoadBlock (LoadState *S, void *b, size_t size) {
53  if (luaZ_read(S->Z, b, size) != 0)
54    error(S, "truncated");
45static void LoadBlock(LoadState* S, void* b, size_t size)
46{
47 if (luaZ_read(S->Z,b,size)!=0) error(S,"truncated");
5548}
5649
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;
50static int LoadChar(LoadState* S)
51{
52 char x;
53 LoadVar(S,x);
54 return x;
6555}
6656
67
68static int LoadInt (LoadState *S) {
69  int x;
70  LoadVar(S, x);
71  return x;
57static int LoadInt(LoadState* S)
58{
59 int x;
60 LoadVar(S,x);
61 if (x<0) error(S,"corrupted");
62 return x;
7263}
7364
74
75static lua_Number LoadNumber (LoadState *S) {
76  lua_Number x;
77  LoadVar(S, x);
78  return x;
65static lua_Number LoadNumber(LoadState* S)
66{
67 lua_Number x;
68 LoadVar(S,x);
69 return x;
7970}
8071
81
82static lua_Integer LoadInteger (LoadState *S) {
83  lua_Integer x;
84  LoadVar(S, x);
85  return x;
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 }
8684}
8785
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  }
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));
10092}
10193
94static void LoadFunction(LoadState* S, Proto* f);
10295
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    }
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);
144122  }
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 }
145133}
146134
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  }
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 }
159147}
160148
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  }
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);
173169}
174170
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);
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);
195182}
196183
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
197189
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);
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");
212201}
213202
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);
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;
221233}
222234
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 */
223238
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
251239/*
252** load precompiled chunk
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
253243*/
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;
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));
276258}
277
trunk/3rdparty/lua/src/lundump.h
r242959r242960
11/*
2** $Id: lundump.h,v 1.44 2014/06/19 18:27:20 roberto Exp $
2** $Id: lundump.h,v 1.39.1.1 2013/04/12 18:48:47 roberto Exp $
33** load precompiled Lua chunks
44** See Copyright Notice in lua.h
55*/
r242959r242960
77#ifndef lundump_h
88#define lundump_h
99
10#include "llimits.h"
1110#include "lobject.h"
1211#include "lzio.h"
1312
13/* load one chunk; from lundump.c */
14LUAI_FUNC Closure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff, const char* name);
1415
15/* data to catch conversion errors */
16#define LUAC_DATA   "\x19\x93\r\n\x1a\n"
16/* make header; from lundump.c */
17LUAI_FUNC void luaU_header (lu_byte* h);
1718
18#define LUAC_INT   0x5678
19#define LUAC_NUM   cast_num(370.5)
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);
2021
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 */
22/* data to catch conversion errors */
23#define LUAC_TAIL      "\x19\x93\r\n\x1a\n"
2424
25/* load one chunk; from lundump.c */
26LUAI_FUNC LClosure* luaU_undump (lua_State* L, ZIO* Z, Mbuffer* buff,
27                                 const char* name);
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))
2827
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
3328#endif
trunk/3rdparty/lua/src/lutf8lib.c
r242959r242960
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
r242959r242960
11/*
2** $Id: lvm.c,v 2.232 2014/12/27 20:30:38 roberto Exp $
2** $Id: lvm.c,v 2.155.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lua virtual machine
44** See Copyright Notice in lua.h
55*/
66
7#define lvm_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
13#include <limits.h>
148#include <stdio.h>
159#include <stdlib.h>
1610#include <string.h>
1711
12#define lvm_c
13#define LUA_CORE
14
1815#include "lua.h"
1916
2017#include "ldebug.h"
r242959r242960
3027#include "lvm.h"
3128
3229
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
4130
42
4331/* limit for table tag-method chains (to avoid loops) */
44#define MAXTAGLOOP   2000
32#define MAXTAGLOOP   100
4533
4634
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;
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;
5641  }
57  else {
58    *n = 0;  /* to avoid warnings */
59    return 0;
60  }
61  return 1;
42  else
43    return NULL;
6244}
6345
6446
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));
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));
7355    return 1;
7456  }
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 */
8257}
8358
8459
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);
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) */
10369  }
104  else if (ttisinteger(obj)) {
105    *p = ivalue(obj);
106    return 1;
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 */
10780  }
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 */
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);
11289  }
113  return 0;  /* conversion failed */
11490}
11591
11692
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    }
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);
155106  }
156  return 1;
157107}
158108
159109
160/*
161** Main function for table access (invoking metamethods if needed).
162** Compute 'val = t[key]'
163*/
164110void luaV_gettable (lua_State *L, const TValue *t, TValue *key, StkId val) {
165  int loop;  /* counter to avoid infinite loops */
111  int loop;
166112  for (loop = 0; loop < MAXTAGLOOP; loop++) {
167113    const TValue *tm;
168    if (ttistable(t)) {  /* 't' is a table? */
114    if (ttistable(t)) {  /* `t' is a table? */
169115      Table *h = hvalue(t);
170116      const TValue *res = luaH_get(h, key); /* do a primitive get */
171117      if (!ttisnil(res) ||  /* result is not nil? */
172118          (tm = fasttm(L, h->metatable, TM_INDEX)) == NULL) { /* or no TM? */
173        setobj2s(L, val, res);  /* result is the raw get */
119        setobj2s(L, val, res);
174120        return;
175121      }
176      /* else will try metamethod */
122      /* else will try the tag method */
177123    }
178124    else if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_INDEX)))
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);
125      luaG_typeerror(L, t, "index");
126    if (ttisfunction(tm)) {
127      callTM(L, tm, t, key, val, 1);
182128      return;
183129    }
184    t = tm;  /* else repeat access over 'tm' */
130    t = tm;  /* else repeat with 'tm' */
185131  }
186  luaG_runerror(L, "gettable chain too long; possible loop");
132  luaG_runerror(L, "loop in gettable");
187133}
188134
189135
190/*
191** Main function for table assignment (invoking metamethods if needed).
192** Compute 't[key] = val'
193*/
194136void luaV_settable (lua_State *L, const TValue *t, TValue *key, StkId val) {
195  int loop;  /* counter to avoid infinite loops */
137  int loop;
196138  for (loop = 0; loop < MAXTAGLOOP; loop++) {
197139    const TValue *tm;
198    if (ttistable(t)) {  /* 't' is a table? */
140    if (ttistable(t)) {  /* `t' is a table? */
199141      Table *h = hvalue(t);
200142      TValue *oldval = cast(TValue *, luaH_get(h, key));
201143      /* if previous value is not nil, there must be a previous entry
202         in the table; a metamethod has no relevance */
144         in the table; moreover, a metamethod has no relevance */
203145      if (!ttisnil(oldval) ||
204146         /* previous value is nil; must check the metamethod */
205147         ((tm = fasttm(L, h->metatable, TM_NEWINDEX)) == NULL &&
r242959r242960
211153        /* no metamethod and (now) there is an entry with given key */
212154        setobj2t(L, oldval, val);  /* assign new value to that entry */
213155        invalidateTMcache(h);
214        luaC_barrierback(L, h, val);
156        luaC_barrierback(L, obj2gco(h), val);
215157        return;
216158      }
217159      /* else will try the metamethod */
r242959r242960
219161    else  /* not a table; check metamethod */
220162      if (ttisnil(tm = luaT_gettmbyobj(L, t, TM_NEWINDEX)))
221163        luaG_typeerror(L, t, "index");
222    /* try the metamethod */
164    /* there is a metamethod */
223165    if (ttisfunction(tm)) {
224      luaT_callTM(L, tm, t, key, val, 0);
166      callTM(L, tm, t, key, val, 0);
225167      return;
226168    }
227    t = tm;  /* else repeat assignment over 'tm' */
169    t = tm;  /* else repeat with 'tm' */
228170  }
229  luaG_runerror(L, "settable chain too long; possible loop");
171  luaG_runerror(L, "loop in settable");
230172}
231173
232174
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*/
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
240209static int l_strcmp (const TString *ls, const TString *rs) {
241210  const char *l = getstr(ls);
242  size_t ll = ls->len;
211  size_t ll = ls->tsv.len;
243212  const char *r = getstr(rs);
244  size_t lr = rs->len;
245  for (;;) {  /* for each segment */
213  size_t lr = rs->tsv.len;
214  for (;;) {
246215    int temp = strcoll(l, r);
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' */
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') */
256224      len++;
257225      l += len; ll -= len; r += len; lr -= len;
258226    }
r242959r242960
260228}
261229
262230
263/*
264** Main operation less than; return 'l < r'.
265*/
266231int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r) {
267232  int res;
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 */
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);
277239  return res;
278240}
279241
280242
281/*
282** Main operation less than or equal to; return 'l <= r'.
283*/
284243int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r) {
285244  int res;
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' */
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' */
294250    return res;
295  else if ((res = luaT_callorderTM(L, r, l, TM_LT)) < 0)  /* else try 'lt' */
251  else if ((res = call_orderTM(L, r, l, TM_LT)) < 0)  /* else try `lt' */
296252    luaG_ordererror(L, l, r);
297253  return !res;
298254}
299255
300256
301257/*
302** Main operation for equality of Lua values; return 't1 == t2'.
303** L == NULL means raw equality (no metamethods)
258** equality of Lua values. L == NULL means raw equality (no metamethods)
304259*/
305int luaV_equalobj (lua_State *L, const TValue *t1, const TValue *t2) {
260int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2) {
306261  const TValue *tm;
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 */
262  lua_assert(ttisequal(t1, t2));
318263  switch (ttype(t1)) {
319264    case LUA_TNIL: return 1;
320    case LUA_TNUMINT: return (ivalue(t1) == ivalue(t2));
321    case LUA_TNUMFLT: return luai_numeq(fltvalue(t1), fltvalue(t2));
265    case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2));
322266    case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2);  /* true must be 1 !! */
323267    case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2);
324268    case LUA_TLCF: return fvalue(t1) == fvalue(t2);
325    case LUA_TSHRSTR: return eqshrstr(tsvalue(t1), tsvalue(t2));
326    case LUA_TLNGSTR: return luaS_eqlngstr(tsvalue(t1), tsvalue(t2));
269    case LUA_TSHRSTR: return eqshrstr(rawtsvalue(t1), rawtsvalue(t2));
270    case LUA_TLNGSTR: return luaS_eqlngstr(rawtsvalue(t1), rawtsvalue(t2));
327271    case LUA_TUSERDATA: {
328272      if (uvalue(t1) == uvalue(t2)) return 1;
329273      else if (L == NULL) return 0;
330      tm = fasttm(L, uvalue(t1)->metatable, TM_EQ);
331      if (tm == NULL)
332        tm = fasttm(L, uvalue(t2)->metatable, TM_EQ);
274      tm = get_equalTM(L, uvalue(t1)->metatable, uvalue(t2)->metatable, TM_EQ);
333275      break;  /* will try TM */
334276    }
335277    case LUA_TTABLE: {
336278      if (hvalue(t1) == hvalue(t2)) return 1;
337279      else if (L == NULL) return 0;
338      tm = fasttm(L, hvalue(t1)->metatable, TM_EQ);
339      if (tm == NULL)
340        tm = fasttm(L, hvalue(t2)->metatable, TM_EQ);
280      tm = get_equalTM(L, hvalue(t1)->metatable, hvalue(t2)->metatable, TM_EQ);
341281      break;  /* will try TM */
342282    }
343283    default:
284      lua_assert(iscollectable(t1));
344285      return gcvalue(t1) == gcvalue(t2);
345286  }
346  if (tm == NULL)  /* no TM? */
347    return 0;  /* objects are different */
348  luaT_callTM(L, tm, t1, t2, L->top, 1);  /* call TM */
287  if (tm == NULL) return 0;  /* no TM? */
288  callTM(L, tm, t1, t2, L->top, 1);  /* call TM */
349289  return !l_isfalse(L->top);
350290}
351291
352292
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*/
361293void luaV_concat (lua_State *L, int total) {
362294  lua_assert(total >= 2);
363295  do {
364296    StkId top = L->top;
365297    int n = 2;  /* number of elements handled in this pass (at least 2) */
366    if (!(ttisstring(top-2) || cvt2str(top-2)) || !tostring(L, top-1))
367      luaT_trybinTM(L, top-2, top-1, top-2, TM_CONCAT);
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    }
368302    else if (tsvalue(top-1)->len == 0)  /* second operand is empty? */
369      cast_void(tostring(L, top - 2));  /* result is first operand */
303      (void)tostring(L, top - 2);  /* result is first operand */
370304    else if (ttisstring(top-2) && tsvalue(top-2)->len == 0) {
371305      setobjs2s(L, top - 2, top - 1);  /* result is second op. */
372306    }
r242959r242960
378312      /* collect total length */
379313      for (i = 1; i < total && tostring(L, top-i-1); i++) {
380314        size_t l = tsvalue(top-i-1)->len;
381        if (l >= (MAX_SIZE/sizeof(char)) - tl)
315        if (l >= (MAX_SIZET/sizeof(char)) - tl)
382316          luaG_runerror(L, "string length overflow");
383317        tl += l;
384318      }
385319      buffer = luaZ_openspace(L, &G(L)->buff, tl);
386320      tl = 0;
387321      n = i;
388      do {  /* copy all strings to buffer */
322      do {  /* concat all strings */
389323        size_t l = tsvalue(top-i)->len;
390324        memcpy(buffer+tl, svalue(top-i), l * sizeof(char));
391325        tl += l;
392326      } while (--i > 0);
393      setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));  /* create result */
327      setsvalue2s(L, top-n, luaS_newlstr(L, buffer, tl));
394328    }
395329    total -= n-1;  /* got 'n' strings to create 1 new */
396330    L->top -= n-1;  /* popped 'n' strings and pushed one */
r242959r242960
398332}
399333
400334
401/*
402** Main operation 'ra' = #rb'.
403*/
404335void luaV_objlen (lua_State *L, StkId ra, const TValue *rb) {
405336  const TValue *tm;
406  switch (ttnov(rb)) {
337  switch (ttypenv(rb)) {
407338    case LUA_TTABLE: {
408339      Table *h = hvalue(rb);
409340      tm = fasttm(L, h->metatable, TM_LEN);
410341      if (tm) break;  /* metamethod? break switch to call it */
411      setivalue(ra, luaH_getn(h));  /* else primitive len */
342      setnvalue(ra, cast_num(1.0*luaH_getn(h)));  /* else primitive len */
412343      return;
413344    }
414345    case LUA_TSTRING: {
415      setivalue(ra, tsvalue(rb)->len);
346      setnvalue(ra, cast_num(tsvalue(rb)->len));
416347      return;
417348    }
418349    default: {  /* try metamethod */
r242959r242960
422353      break;
423354    }
424355  }
425  luaT_callTM(L, tm, rb, rb, ra, 1);
356  callTM(L, tm, rb, rb, ra, 1);
426357}
427358
428359
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 */
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);
440368  }
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  }
369  else if (!call_binTM(L, rb, rc, ra, op))
370    luaG_aritherror(L, rb, rc);
447371}
448372
449373
450374/*
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/*
489375** check whether cached closure in prototype 'p' may be reused, that is,
490376** whether there is a cached closure with the same upvalues needed by
491377** new closure to be created.
492378*/
493static LClosure *getcached (Proto *p, UpVal **encup, StkId base) {
494  LClosure *c = p->cache;
379static Closure *getcached (Proto *p, UpVal **encup, StkId base) {
380  Closure *c = p->cache;
495381  if (c != NULL) {  /* is there a cached closure? */
496382    int nup = p->sizeupvalues;
497383    Upvaldesc *uv = p->upvalues;
498384    int i;
499385    for (i = 0; i < nup; i++) {  /* check whether it has right upvalues */
500386      TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v;
501      if (c->upvals[i]->v != v)
387      if (c->l.upvals[i]->v != v)
502388        return NULL;  /* wrong upvalue; cannot reuse closure */
503389    }
504390  }
r242959r242960
508394
509395/*
510396** create a new Lua closure, push it in the stack, and initialize
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).
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.
514400*/
515401static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
516402                         StkId ra) {
517403  int nup = p->sizeupvalues;
518404  Upvaldesc *uv = p->upvalues;
519405  int i;
520  LClosure *ncl = luaF_newLclosure(L, nup);
521  ncl->p = p;
406  Closure *ncl = luaF_newLclosure(L, nup);
407  ncl->l.p = p;
522408  setclLvalue(L, ra, ncl);  /* anchor new closure in stack */
523409  for (i = 0; i < nup; i++) {  /* fill in its upvalues */
524410    if (uv[i].instack)  /* upvalue refers to local variable? */
525      ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx);
411      ncl->l.upvals[i] = luaF_findupval(L, base + uv[i].idx);
526412    else  /* get upvalue from enclosing function */
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 */
413      ncl->l.upvals[i] = encup[uv[i].idx];
530414  }
531  if (!isblack(p))  /* cache will not break GC invariant? */
532    p->cache = ncl;  /* save it on cache for reuse */
415  luaC_barrierproto(L, p, ncl);
416  p->cache = ncl;  /* save it on cache for reuse */
533417}
534418
535419
r242959r242960
542426  Instruction inst = *(ci->u.l.savedpc - 1);  /* interrupted instruction */
543427  OpCode op = GET_OPCODE(inst);
544428  switch (op) {  /* finish its execution */
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:
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:
549431    case OP_GETTABUP: case OP_GETTABLE: case OP_SELF: {
550432      setobjs2s(L, base + GETARG_A(inst), --L->top);
551433      break;
r242959r242960
564446      break;
565447    }
566448    case OP_CONCAT: {
567      StkId top = L->top - 1;  /* top when 'luaT_trybinTM' was called */
449      StkId top = L->top - 1;  /* top when 'call_binTM' was called */
568450      int b = GETARG_B(inst);      /* first element to concatenate */
569451      int total = cast_int(top - 1 - (base + b));  /* yet to concatenate */
570452      setobj2s(L, top - 2, top);  /* put TM result in proper position */
r242959r242960
595477
596478
597479
598
599480/*
600** {==================================================================
601** Function 'luaV_execute': main interpreter loop
602** ===================================================================
481** some macros for common tasks in `luaV_execute'
603482*/
604483
605
606/*
607** some macros for common tasks in 'luaV_execute'
608*/
609
610484#if !defined luai_runtimecheck
611485#define luai_runtimecheck(L, c)      /* void */
612486#endif
r242959r242960
643517           luai_threadyield(L); )
644518
645519
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
646530#define vmdispatch(o)   switch(o)
647#define vmcase(l)   case l:
648#define vmbreak      break
531#define vmcase(l,b)   case l: {b}  break;
532#define vmcasenb(l,b)   case l: {b}      /* nb = no break */
649533
650534void luaV_execute (lua_State *L) {
651535  CallInfo *ci = L->ci;
r242959r242960
663547    StkId ra;
664548    if ((L->hookmask & (LUA_MASKLINE | LUA_MASKCOUNT)) &&
665549        (--L->hookcount == 0 || L->hookmask & LUA_MASKLINE)) {
666      Protect(luaG_traceexec(L));
550      Protect(traceexec(L));
667551    }
668    /* WARNING: several calls may realloc the stack and invalidate 'ra' */
552    /* WARNING: several calls may realloc the stack and invalidate `ra' */
669553    ra = RA(i);
670554    lua_assert(base == ci->u.l.base);
671555    lua_assert(base <= L->top && L->top < L->stack + L->stacksize);
672556    vmdispatch (GET_OPCODE(i)) {
673      vmcase(OP_MOVE) {
557      vmcase(OP_MOVE,
674558        setobjs2s(L, ra, RB(i));
675        vmbreak;
676      }
677      vmcase(OP_LOADK) {
559      )
560      vmcase(OP_LOADK,
678561        TValue *rb = k + GETARG_Bx(i);
679562        setobj2s(L, ra, rb);
680        vmbreak;
681      }
682      vmcase(OP_LOADKX) {
563      )
564      vmcase(OP_LOADKX,
683565        TValue *rb;
684566        lua_assert(GET_OPCODE(*ci->u.l.savedpc) == OP_EXTRAARG);
685567        rb = k + GETARG_Ax(*ci->u.l.savedpc++);
686568        setobj2s(L, ra, rb);
687        vmbreak;
688      }
689      vmcase(OP_LOADBOOL) {
569      )
570      vmcase(OP_LOADBOOL,
690571        setbvalue(ra, GETARG_B(i));
691572        if (GETARG_C(i)) ci->u.l.savedpc++;  /* skip next instruction (if C) */
692        vmbreak;
693      }
694      vmcase(OP_LOADNIL) {
573      )
574      vmcase(OP_LOADNIL,
695575        int b = GETARG_B(i);
696576        do {
697577          setnilvalue(ra++);
698578        } while (b--);
699        vmbreak;
700      }
701      vmcase(OP_GETUPVAL) {
579      )
580      vmcase(OP_GETUPVAL,
702581        int b = GETARG_B(i);
703582        setobj2s(L, ra, cl->upvals[b]->v);
704        vmbreak;
705      }
706      vmcase(OP_GETTABUP) {
583      )
584      vmcase(OP_GETTABUP,
707585        int b = GETARG_B(i);
708586        Protect(luaV_gettable(L, cl->upvals[b]->v, RKC(i), ra));
709        vmbreak;
710      }
711      vmcase(OP_GETTABLE) {
587      )
588      vmcase(OP_GETTABLE,
712589        Protect(luaV_gettable(L, RB(i), RKC(i), ra));
713        vmbreak;
714      }
715      vmcase(OP_SETTABUP) {
590      )
591      vmcase(OP_SETTABUP,
716592        int a = GETARG_A(i);
717593        Protect(luaV_settable(L, cl->upvals[a]->v, RKB(i), RKC(i)));
718        vmbreak;
719      }
720      vmcase(OP_SETUPVAL) {
594      )
595      vmcase(OP_SETUPVAL,
721596        UpVal *uv = cl->upvals[GETARG_B(i)];
722597        setobj(L, uv->v, ra);
723        luaC_upvalbarrier(L, uv);
724        vmbreak;
725      }
726      vmcase(OP_SETTABLE) {
598        luaC_barrier(L, uv, ra);
599      )
600      vmcase(OP_SETTABLE,
727601        Protect(luaV_settable(L, ra, RKB(i), RKC(i)));
728        vmbreak;
729      }
730      vmcase(OP_NEWTABLE) {
602      )
603      vmcase(OP_NEWTABLE,
731604        int b = GETARG_B(i);
732605        int c = GETARG_C(i);
733606        Table *t = luaH_new(L);
r242959r242960
735608        if (b != 0 || c != 0)
736609          luaH_resize(L, t, luaO_fb2int(b), luaO_fb2int(c));
737610        checkGC(L, ra + 1);
738        vmbreak;
739      }
740      vmcase(OP_SELF) {
611      )
612      vmcase(OP_SELF,
741613        StkId rb = RB(i);
742614        setobjs2s(L, ra+1, rb);
743615        Protect(luaV_gettable(L, rb, RKC(i), ra));
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) {
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,
889636        TValue *rb = RB(i);
890        lua_Number nb;
891        if (ttisinteger(rb)) {
892          lua_Integer ib = ivalue(rb);
893          setivalue(ra, intop(-, 0, ib));
637        if (ttisnumber(rb)) {
638          lua_Number nb = nvalue(rb);
639          setnvalue(ra, luai_numunm(L, nb));
894640        }
895        else if (tonumber(rb, &nb)) {
896          setfltvalue(ra, luai_numunm(L, nb));
897        }
898641        else {
899          Protect(luaT_trybinTM(L, rb, rb, ra, TM_UNM));
642          Protect(luaV_arith(L, ra, rb, rb, TM_UNM));
900643        }
901        vmbreak;
902      }
903      vmcase(OP_BNOT) {
644      )
645      vmcase(OP_NOT,
904646        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);
916647        int res = l_isfalse(rb);  /* next assignment may change this value */
917648        setbvalue(ra, res);
918        vmbreak;
919      }
920      vmcase(OP_LEN) {
649      )
650      vmcase(OP_LEN,
921651        Protect(luaV_objlen(L, ra, RB(i)));
922        vmbreak;
923      }
924      vmcase(OP_CONCAT) {
652      )
653      vmcase(OP_CONCAT,
925654        int b = GETARG_B(i);
926655        int c = GETARG_C(i);
927656        StkId rb;
r242959r242960
932661        setobjs2s(L, ra, rb);
933662        checkGC(L, (ra >= rb ? ra + 1 : rb));
934663        L->top = ci->top;  /* restore top */
935        vmbreak;
936      }
937      vmcase(OP_JMP) {
664      )
665      vmcase(OP_JMP,
938666        dojump(ci, i, 0);
939        vmbreak;
940      }
941      vmcase(OP_EQ) {
667      )
668      vmcase(OP_EQ,
942669        TValue *rb = RKB(i);
943670        TValue *rc = RKC(i);
944671        Protect(
945          if (cast_int(luaV_equalobj(L, rb, rc)) != GETARG_A(i))
672          if (cast_int(equalobj(L, rb, rc)) != GETARG_A(i))
946673            ci->u.l.savedpc++;
947674          else
948675            donextjump(ci);
949676        )
950        vmbreak;
951      }
952      vmcase(OP_LT) {
677      )
678      vmcase(OP_LT,
953679        Protect(
954680          if (luaV_lessthan(L, RKB(i), RKC(i)) != GETARG_A(i))
955681            ci->u.l.savedpc++;
956682          else
957683            donextjump(ci);
958684        )
959        vmbreak;
960      }
961      vmcase(OP_LE) {
685      )
686      vmcase(OP_LE,
962687        Protect(
963688          if (luaV_lessequal(L, RKB(i), RKC(i)) != GETARG_A(i))
964689            ci->u.l.savedpc++;
965690          else
966691            donextjump(ci);
967692        )
968        vmbreak;
969      }
970      vmcase(OP_TEST) {
693      )
694      vmcase(OP_TEST,
971695        if (GETARG_C(i) ? l_isfalse(ra) : !l_isfalse(ra))
972696            ci->u.l.savedpc++;
973697          else
974698          donextjump(ci);
975        vmbreak;
976      }
977      vmcase(OP_TESTSET) {
699      )
700      vmcase(OP_TESTSET,
978701        TValue *rb = RB(i);
979702        if (GETARG_C(i) ? l_isfalse(rb) : !l_isfalse(rb))
980703          ci->u.l.savedpc++;
r242959r242960
982705          setobjs2s(L, ra, rb);
983706          donextjump(ci);
984707        }
985        vmbreak;
986      }
987      vmcase(OP_CALL) {
708      )
709      vmcase(OP_CALL,
988710        int b = GETARG_B(i);
989711        int nresults = GETARG_C(i) - 1;
990712        if (b != 0) L->top = ra+b;  /* else previous instruction set top */
r242959r242960
997719          ci->callstatus |= CIST_REENTRY;
998720          goto newframe;  /* restart luaV_execute over new Lua function */
999721        }
1000        vmbreak;
1001      }
1002      vmcase(OP_TAILCALL) {
722      )
723      vmcase(OP_TAILCALL,
1003724        int b = GETARG_B(i);
1004725        if (b != 0) L->top = ra+b;  /* else previous instruction set top */
1005726        lua_assert(GETARG_C(i) - 1 == LUA_MULTRET);
r242959r242960
1027748          lua_assert(L->top == oci->u.l.base + getproto(ofunc)->maxstacksize);
1028749          goto newframe;  /* restart luaV_execute over new Lua function */
1029750        }
1030        vmbreak;
1031      }
1032      vmcase(OP_RETURN) {
751      )
752      vmcasenb(OP_RETURN,
1033753        int b = GETARG_B(i);
1034754        if (b != 0) L->top = ra+b-1;
1035755        if (cl->p->sizep > 0) luaF_close(L, base);
r242959r242960
1043763          lua_assert(GET_OPCODE(*((ci)->u.l.savedpc - 1)) == OP_CALL);
1044764          goto newframe;  /* restart luaV_execute over new Lua function */
1045765        }
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          }
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 */
1057776        }
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        }
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)));
1096789        ci->u.l.savedpc += GETARG_sBx(i);
1097        vmbreak;
1098      }
1099      vmcase(OP_TFORCALL) {
790      )
791      vmcasenb(OP_TFORCALL,
1100792        StkId cb = ra + 3;  /* call base */
1101793        setobjs2s(L, cb+2, ra+2);
1102794        setobjs2s(L, cb+1, ra+1);
r242959r242960
1108800        ra = RA(i);
1109801        lua_assert(GET_OPCODE(i) == OP_TFORLOOP);
1110802        goto l_tforloop;
1111      }
1112      vmcase(OP_TFORLOOP) {
803      )
804      vmcase(OP_TFORLOOP,
1113805        l_tforloop:
1114806        if (!ttisnil(ra + 1)) {  /* continue loop? */
1115807          setobjs2s(L, ra, ra + 1);  /* save control variable */
1116808           ci->u.l.savedpc += GETARG_sBx(i);  /* jump back */
1117809        }
1118        vmbreak;
1119      }
1120      vmcase(OP_SETLIST) {
810      )
811      vmcase(OP_SETLIST,
1121812        int n = GETARG_B(i);
1122813        int c = GETARG_C(i);
1123        unsigned int last;
814        int last;
1124815        Table *h;
1125816        if (n == 0) n = cast_int(L->top - ra) - 1;
1126817        if (c == 0) {
r242959r242960
1135826        for (; n > 0; n--) {
1136827          TValue *val = ra+n;
1137828          luaH_setint(L, h, last--, val);
1138          luaC_barrierback(L, h, val);
829          luaC_barrierback(L, obj2gco(h), val);
1139830        }
1140831        L->top = ci->top;  /* correct top (in case of previous open call) */
1141        vmbreak;
1142      }
1143      vmcase(OP_CLOSURE) {
832      )
833      vmcase(OP_CLOSURE,
1144834        Proto *p = cl->p->p[GETARG_Bx(i)];
1145        LClosure *ncl = getcached(p, cl->upvals, base);  /* cached closure */
835        Closure *ncl = getcached(p, cl->upvals, base);  /* cached closure */
1146836        if (ncl == NULL)  /* no match? */
1147837          pushclosure(L, p, cl->upvals, base, ra);  /* create a new one */
1148838        else
1149839          setclLvalue(L, ra, ncl);  /* push cashed closure */
1150840        checkGC(L, ra + 1);
1151        vmbreak;
1152      }
1153      vmcase(OP_VARARG) {
841      )
842      vmcase(OP_VARARG,
1154843        int b = GETARG_B(i) - 1;
1155844        int j;
1156845        int n = cast_int(base - ci->func) - cl->p->numparams - 1;
r242959r242960
1168857            setnilvalue(ra + j);
1169858          }
1170859        }
1171        vmbreak;
1172      }
1173      vmcase(OP_EXTRAARG) {
860      )
861      vmcase(OP_EXTRAARG,
1174862        lua_assert(0);
1175        vmbreak;
1176      }
863      )
1177864    }
1178865  }
1179866}
1180867
1181/* }================================================================== */
1182
trunk/3rdparty/lua/src/lvm.h
r242959r242960
11/*
2** $Id: lvm.h,v 2.34 2014/08/01 17:24:02 roberto Exp $
2** $Id: lvm.h,v 2.18.1.1 2013/04/12 18:48:47 roberto Exp $
33** Lua virtual machine
44** See Copyright Notice in lua.h
55*/
r242959r242960
1313#include "ltm.h"
1414
1515
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
16#define tostring(L,o) (ttisstring(o) || (luaV_tostring(L, o)))
2117
18#define tonumber(o,n)   (ttisnumber(o) || (((o) = luaV_tonumber(o,n)) != NULL))
2219
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
20#define equalobj(L,o1,o2)  (ttisequal(o1, o2) && luaV_equalobj_(L, o1, o2))
2821
22#define luaV_rawequalobj(o1,o2)      equalobj(NULL,o1,o2)
2923
30#define tonumber(o,n) \
31   (ttisfloat(o) ? (*(n) = fltvalue(o), 1) : luaV_tonumber_(o,n))
3224
33#define tointeger(o,i) \
34   (ttisinteger(o) ? (*(i) = ivalue(o), 1) : luaV_tointeger_(o,i))
25/* not to called directly */
26LUAI_FUNC int luaV_equalobj_ (lua_State *L, const TValue *t1, const TValue *t2);
3527
36#define intop(op,v1,v2) l_castU2S(l_castS2U(v1) op l_castS2U(v2))
3728
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);
4229LUAI_FUNC int luaV_lessthan (lua_State *L, const TValue *l, const TValue *r);
4330LUAI_FUNC int luaV_lessequal (lua_State *L, const TValue *l, const TValue *r);
44LUAI_FUNC int luaV_tonumber_ (const TValue *obj, lua_Number *n);
45LUAI_FUNC int luaV_tointeger_ (const TValue *obj, lua_Integer *p);
31LUAI_FUNC const TValue *luaV_tonumber (const TValue *obj, TValue *n);
32LUAI_FUNC int luaV_tostring (lua_State *L, StkId obj);
4633LUAI_FUNC void luaV_gettable (lua_State *L, const TValue *t, TValue *key,
4734                                            StkId val);
4835LUAI_FUNC void luaV_settable (lua_State *L, const TValue *t, TValue *key,
r242959r242960
5037LUAI_FUNC void luaV_finishOp (lua_State *L);
5138LUAI_FUNC void luaV_execute (lua_State *L);
5239LUAI_FUNC void luaV_concat (lua_State *L, int total);
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);
40LUAI_FUNC void luaV_arith (lua_State *L, StkId ra, const TValue *rb,
41                           const TValue *rc, TMS op);
5642LUAI_FUNC void luaV_objlen (lua_State *L, StkId ra, const TValue *rb);
5743
5844#endif
trunk/3rdparty/lua/src/lzio.c
r242959r242960
11/*
2** $Id: lzio.c,v 1.36 2014/11/02 19:19:04 roberto Exp $
2** $Id: lzio.c,v 1.35.1.1 2013/04/12 18:48:47 roberto Exp $
33** Buffered streams
44** See Copyright Notice in lua.h
55*/
66
7#define lzio_c
8#define LUA_CORE
97
10#include "lprefix.h"
11
12
138#include <string.h>
149
10#define lzio_c
11#define LUA_CORE
12
1513#include "lua.h"
1614
1715#include "llimits.h"
trunk/3rdparty/lua/src/lzio.h
r242959r242960
11/*
2** $Id: lzio.h,v 1.30 2014/12/19 17:26:14 roberto Exp $
2** $Id: lzio.h,v 1.26.1.1 2013/04/12 18:48:47 roberto Exp $
33** Buffered streams
44** See Copyright Notice in lua.h
55*/
r242959r242960
3232#define luaZ_sizebuffer(buff)   ((buff)->buffsize)
3333#define luaZ_bufflen(buff)   ((buff)->n)
3434
35#define luaZ_buffremove(buff,i)   ((buff)->n -= (i))
3635#define luaZ_resetbuffer(buff) ((buff)->n = 0)
3736
3837
3938#define luaZ_resizebuffer(L, buff, size) \
40   ((buff)->buffer = luaM_reallocvchar(L, (buff)->buffer, \
41            (buff)->buffsize, size), \
39   (luaM_reallocvector(L, (buff)->buffer, (buff)->buffsize, size, char), \
4240   (buff)->buffsize = size)
4341
4442#define luaZ_freebuffer(L, buff)   luaZ_resizebuffer(L, buff, 0)
r242959r242960
4745LUAI_FUNC char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n);
4846LUAI_FUNC void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader,
4947                                        void *data);
50LUAI_FUNC size_t luaZ_read (ZIO* z, void *b, size_t n);   /* read next n bytes */
48LUAI_FUNC size_t luaZ_read (ZIO* z, void* b, size_t n);   /* read next n bytes */
5149
5250
5351
r242959r242960
5755  size_t n;         /* bytes still unread */
5856  const char *p;      /* current position in buffer */
5957  lua_Reader reader;      /* reader function */
60  void *data;         /* additional data */
58  void* data;         /* additional data */
6159  lua_State *L;         /* Lua state (for reader) */
6260};
6361
trunk/hash/apple3.xml
r242959r242960
1<?xml version="1.0"?>
2<!DOCTYPE softwarelist SYSTEM "softwarelist.dtd">
3
4<softwarelist name="apple3" description="Apple III 5.25 disks">
5
6   <software name="magneto">
7      <description>Capt'n Magneto (PD release APPLE-3-WAP-GAM-03)</description> <!-- was also released commercially - need those images, original game is 1983, this is a PD release of it from 1995 -->
8      <year>1995</year>
9      <publisher>Al Evans / WAP</publisher>
10
11      <part name="flop1" interface="floppy_5_25">
12         <dataarea name="flop" size="143360">
13            <rom name="apple-3-wap-gam-03a.dsk" size="143360" crc="fec20dbb" sha1="5ee6b1610649ad32df8ab00a2a272c3b79a92f26" offset="0x0000" />
14         </dataarea>
15      </part>
16      <part name="flop2" interface="floppy_5_25">
17         <dataarea name="flop" size="143360">
18            <rom name="apple-3-wap-gam-03b.dsk" size="143360" crc="a489f0b3" sha1="82c369ffec141b551732522edbe6d726b28da181" offset="0x0000" />
19         </dataarea>
20      </part>
21   </software>
22
23
24</softwarelist>
trunk/hash/gjmovie.xml
r242959r242960
1<?xml version="1.0"?>
2<!DOCTYPE softwarelist SYSTEM "softwarelist.dtd">
3<softwarelist name="gjmovie" description="VTech Genius Junior Movie cartridges">
4
5   <software name="wuz" supported="no">
6      <description>Wort-und Zahlenspaß</description>
7      <year>1993</year>
8      <publisher>VTech</publisher>
9      <part name="rom" interface="genius_cart">
10         <dataarea name="rom" size="0x40000">
11            <rom name="27-5364-00.u6" size="0x40000" crc="203f0461" sha1="dfc8bb341f703c5f018a7222c24d4a2195316387" offset="0" />
12         </dataarea>
13      </part>
14   </software>
15</softwarelist>
trunk/hash/ibm5170.xml
r242959r242960
14471447      </part>
14481448   </software>
14491449
1450   <software name="msdos4m">
1451      <description>MS-DOS 4.0M</description>
1452      <year>1985</year>
1453      <publisher>Microsoft</publisher>
1454      <part name="flop1" interface="floppy_5_25">
1455         <dataarea name="flop" size="368640">
1456            <rom name="msdos400m-disk1.img" size="368640" crc="67848d5c" sha1="9e44fc3ed1f689c4136a08d48f9efa156cbaf250" offset="0" />
1457         </dataarea>
1458      </part>
1459      <part name="flop2" interface="floppy_5_25">
1460         <dataarea name="flop" size="368640">
1461            <rom name="msdos400m-disk2-unpatched.img" size="368640" crc="85a8cb6c" sha1="88d8ec84a6e24f2c918508dc65de0cdee182a48e" offset="0" />
1462         </dataarea>
1463      </part>
1464   </software>
1465
14661450   <software name="msdos401">
14671451      <description>MS-DOS 4.01</description>
14681452      <year>1988</year>
trunk/makefile
r242959r242960
493493DEFS += -DMAME_DEBUG_FAST
494494endif
495495
496# To support casting in Lua 5.3
497DEFS += -DLUA_COMPAT_APIINTCASTS
498
499496#-------------------------------------------------
500497# compile flags
501498# CCOMFLAGS are common flags
r242959r242960
512509
513510# CFLAGS is defined based on C or C++ targets
514511# (remember, expansion only happens when used, so doing it here is ok)
515CFLAGS = $(CCOMFLAGS) $(CPPONLYFLAGS) $(INCPATH)
512CFLAGS = $(CCOMFLAGS) $(CPPONLYFLAGS)
516513
517514# we compile C-only to C89 standard with GNU extensions
518515# we compile C++ code to C++98 standard with GNU extensions
r242959r242960
867864include $(SRC)/regtests/regtests.mak
868865
869866# combine the various definitions to one
867CCOMFLAGS += $(INCPATH)
870868CDEFS = $(DEFS)
871869
872870# TODO: -x c++ should not be hard-coded
r242959r242960
996994
997995$(OBJ)/%.lh: $(SRC)/%.lay $(SRC)/build/file2str.py
998996   @echo Converting $<...
999   $(PYTHON) $(SRC)/build/file2str.py $< $@ layout_$(basename $(notdir $<))
997   @$(PYTHON) $(SRC)/build/file2str.py $< $@ layout_$(basename $(notdir $<))
1000998
1001999$(OBJ)/%.fh: $(SRC)/%.png $(SRC)/build/png2bdc.py $(SRC)/build/file2str.py
10021000   @echo Converting $<...
1003   $(PYTHON) $(SRC)/build/png2bdc.py $< $(OBJ)/temp.bdc
1004   $(PYTHON) $(SRC)/build/file2str.py $(OBJ)/temp.bdc $@ font_$(basename $(notdir $<)) UINT8
1001   @$(PYTHON) $(SRC)/build/png2bdc.py $< $(OBJ)/temp.bdc
1002   @$(PYTHON) $(SRC)/build/file2str.py $(OBJ)/temp.bdc $@ font_$(basename $(notdir $<)) UINT8
10051003
10061004$(DRIVLISTOBJ): $(DRIVLISTSRC)
10071005   @echo Compiling $<...
r242959r242960
10221020ifeq ($(TARGETOS),macosx)
10231021$(OBJ)/%.o: $(SRC)/%.m | $(OSPREBUILD)
10241022   @echo Objective-C compiling $<...
1025   $(CC) $(CDEFS) $(COBJFLAGS) $(CCOMFLAGS) $(INCPATH) -c $< -o $@
1023   $(CC) $(CDEFS) $(COBJFLAGS) $(CCOMFLAGS) -c $< -o $@
10261024endif
10271025
10281026
trunk/src/emu/bus/nes/ggenie.c
r242959r242960
4848   save_item(NAME(m_gg_bypass));
4949}
5050
51void nes_ggenie_device::pcb_start(running_machine &machine, UINT8 *ciram_ptr, bool cart_mounted)
52{
53   device_nes_cart_interface::pcb_start(machine, ciram_ptr, cart_mounted);
54   if (m_ggslot->m_cart)
55      m_ggslot->pcb_start(m_ciram);
56}
57
5851void nes_ggenie_device::pcb_reset()
5952{
6053   m_chr_source = m_vrom_chunks ? CHRROM : CHRRAM;
r242959r242960
6558   m_gg_bypass = 0;
6659
6760   if (m_ggslot->m_cart)
61   {
62      m_ggslot->pcb_start(m_ciram);
6863      m_ggslot->m_cart->pcb_reset();
64   }
6965}
7066
7167
trunk/src/emu/bus/nes/ggenie.h
r242959r242960
3333   virtual machine_config_constructor device_mconfig_additions() const;
3434
3535   virtual void pcb_reset();
36   virtual void pcb_start(running_machine &machine, UINT8 *ciram_ptr, bool cart_mounted);
3736
3837private:
3938   // emulate the Game Genie!
trunk/src/emu/bus/nes/nes_slot.h
r242959r242960
216216   virtual void scanline_irq(int scanline, int vblank, int blanked) {}
217217
218218   virtual void pcb_reset() {} // many pcb expect specific PRG/CHR banking at start
219   virtual void pcb_start(running_machine &machine, UINT8 *ciram_ptr, bool cart_mounted);
219   void pcb_start(running_machine &machine, UINT8 *ciram_ptr, bool cart_mounted);
220220   void pcb_reg_postload(running_machine &machine);
221221   void nes_banks_restore();
222222
trunk/src/emu/bus/nes/pt554.c
r242959r242960
77 Visit http://mamedev.org for licensing and usage restrictions.
88
99
10 Here we emulate the following Bandai PT-554 PCB (a CNROM PCB + LPC / PARCOR speech synthesis chip)
10 Here we emulate the following Bandai PT-554 PCB (a CNROM PCB + ADPCM sound chip)
1111
1212 TODO:
1313 - emulate the mat controller
r242959r242960
5252 Bandai PT-554 board emulation
5353
5454 This is used by Aerobics Studio. It is basically a CNROM board
55 with an Mitsubishi M50805 LPC / PARCOR speech synthesis chip
56 with internal tables stored in ROM which have not yet been dumped.
55 with an Mitsubishi M50805 sound chip with an internal ROM which
56 is not dumpable at the moment
5757
5858 iNES: mapper 3?
5959
trunk/src/emu/bus/vcs/dpc.c
r242959r242960
2626{
2727   m_oscillator = timer_alloc(TIMER_OSC);
2828   m_oscillator->reset();
29
30   for (int i = 0; i < 8; i++)
31   {
32      save_item(NAME(m_df[i].top), i);
33      save_item(NAME(m_df[i].bottom), i);
34      save_item(NAME(m_df[i].low), i);
35      save_item(NAME(m_df[i].high), i);
36      save_item(NAME(m_df[i].flag), i);
37      save_item(NAME(m_df[i].music_mode), i);
38      save_item(NAME(m_df[i].osc_clk), i);
39   }
40   
41   save_item(NAME(m_movamt));
42   save_item(NAME(m_latch_62));
43   save_item(NAME(m_latch_64));
44   save_item(NAME(m_dlc));
45   save_item(NAME(m_shift_reg));
4629}
4730
4831void dpc_device::device_reset()
trunk/src/emu/clifront.c
r242959r242960
1818#include "un7z.h"
1919#include "validity.h"
2020#include "sound/samples.h"
21#include "cliopts.h"
2221#include "clifront.h"
2322#include "xmlfile.h"
2423
25#include "drivenum.h"
26
27#include "osdepend.h"
28
2924#include <new>
3025#include <ctype.h>
3126
3227
28//**************************************************************************
29//  COMMAND-LINE OPTIONS
30//**************************************************************************
3331
34// media_identifier class identifies media by hash via a search in
35// the driver database
36class media_identifier
32const options_entry cli_options::s_option_entries[] =
3733{
38public:
39    // construction/destruction
40    media_identifier(cli_options &options);
34   /* core commands */
35   { NULL,                            NULL,       OPTION_HEADER,     "CORE COMMANDS" },
36   { CLICOMMAND_HELP ";h;?",           "0",       OPTION_COMMAND,    "show help message" },
37   { CLICOMMAND_VALIDATE ";valid",     "0",       OPTION_COMMAND,    "perform driver validation on all game drivers" },
4138
42    // getters
43    int total() const { return m_total; }
44    int matches() const { return m_matches; }
45    int nonroms() const { return m_nonroms; }
39   /* configuration commands */
40   { NULL,                            NULL,       OPTION_HEADER,     "CONFIGURATION COMMANDS" },
41   { CLICOMMAND_CREATECONFIG ";cc",    "0",       OPTION_COMMAND,    "create the default configuration file" },
42   { CLICOMMAND_SHOWCONFIG ";sc",      "0",       OPTION_COMMAND,    "display running parameters" },
43   { CLICOMMAND_SHOWUSAGE ";su",       "0",       OPTION_COMMAND,    "show this help" },
4644
47    // operations
48    void reset() { m_total = m_matches = m_nonroms = 0; }
49    void identify(const char *name);
50    void identify_file(const char *name);
51    void identify_data(const char *name, const UINT8 *data, int length);
52    int find_by_hash(const hash_collection &hashes, int length);
53
54private:
55    // internal state
56    driver_enumerator   m_drivlist;
57    int                 m_total;
58    int                 m_matches;
59    int                 m_nonroms;
45   /* frontend commands */
46   { NULL,                            NULL,       OPTION_HEADER,     "FRONTEND COMMANDS" },
47   { CLICOMMAND_LISTXML ";lx",         "0",       OPTION_COMMAND,    "all available info on driver in XML format" },
48   { CLICOMMAND_LISTFULL ";ll",        "0",       OPTION_COMMAND,    "short name, full name" },
49   { CLICOMMAND_LISTSOURCE ";ls",      "0",       OPTION_COMMAND,    "driver sourcefile" },
50   { CLICOMMAND_LISTCLONES ";lc",      "0",       OPTION_COMMAND,    "show clones" },
51   { CLICOMMAND_LISTBROTHERS ";lb",    "0",       OPTION_COMMAND,    "show \"brothers\", or other drivers from same sourcefile" },
52   { CLICOMMAND_LISTCRC,               "0",       OPTION_COMMAND,    "CRC-32s" },
53   { CLICOMMAND_LISTROMS ";lr",        "0",       OPTION_COMMAND,    "list required roms for a driver" },
54   { CLICOMMAND_LISTSAMPLES,           "0",       OPTION_COMMAND,    "list optional samples for a driver" },
55   { CLICOMMAND_VERIFYROMS,            "0",       OPTION_COMMAND,    "report romsets that have problems" },
56   { CLICOMMAND_VERIFYSAMPLES,         "0",       OPTION_COMMAND,    "report samplesets that have problems" },
57   { CLICOMMAND_ROMIDENT,              "0",       OPTION_COMMAND,    "compare files with known MAME roms" },
58   { CLICOMMAND_LISTDEVICES ";ld",     "0",       OPTION_COMMAND,    "list available devices" },
59   { CLICOMMAND_LISTSLOTS ";lslot",    "0",       OPTION_COMMAND,    "list available slots and slot devices" },
60   { CLICOMMAND_LISTMEDIA ";lm",       "0",       OPTION_COMMAND,    "list available media for the system" },
61   { CLICOMMAND_LISTSOFTWARE ";lsoft", "0",       OPTION_COMMAND,    "list known software for the system" },
62   { CLICOMMAND_VERIFYSOFTWARE ";vsoft", "0",     OPTION_COMMAND,    "verify known software for the system" },
63   { CLICOMMAND_GETSOFTLIST ";glist",  "0",       OPTION_COMMAND,    "retrieve software list by name" },
64   { CLICOMMAND_VERIFYSOFTLIST ";vlist", "0",     OPTION_COMMAND,    "verify software list by name" },
65   { CLICOMMAND_LIST_MIDI_DEVICES ";mlist", "0",  OPTION_COMMAND,    "list available MIDI I/O devices" },
66   { CLICOMMAND_LIST_NETWORK_ADAPTERS ";nlist", "0",  OPTION_COMMAND,    "list available network adapters" },
67   { NULL }
6068};
6169
6270
71
6372//**************************************************************************
73//  CLI OPTIONS
74//**************************************************************************
75
76//-------------------------------------------------
77//  cli_options - constructor
78//-------------------------------------------------
79
80cli_options::cli_options()
81{
82   add_entries(s_option_entries);
83}
84
85
86
87//**************************************************************************
6488//  CLI FRONTEND
6589//**************************************************************************
6690
r242959r242960
750774}
751775
752776//-------------------------------------------------
777//  listmididevices - output the list of MIDI devices
778//  available in the current system to be used
779//-------------------------------------------------
780
781void cli_frontend::listmididevices(const char *gamename)
782{
783   m_osd.list_midi_devices();
784}
785
786
787//-------------------------------------------------
788//  listnetworkadapters - output the list of network
789//  adapters available in the current system to be used
790//-------------------------------------------------
791
792void cli_frontend::listnetworkadapters(const char *gamename)
793{
794   m_osd.network_init();
795   osd_list_network_adapters();
796   m_osd.network_exit();
797}
798
799
800//-------------------------------------------------
753801//  verifyroms - verify the ROM sets of one or
754802//  more games
755803//-------------------------------------------------
r242959r242960
16021650      { CLICOMMAND_VERIFYSAMPLES, &cli_frontend::verifysamples },
16031651      { CLICOMMAND_LISTMEDIA,     &cli_frontend::listmedia },
16041652      { CLICOMMAND_LISTSOFTWARE,  &cli_frontend::listsoftware },
1605      { CLICOMMAND_VERIFYSOFTWARE,&cli_frontend::verifysoftware },
1653      { CLICOMMAND_VERIFYSOFTWARE,    &cli_frontend::verifysoftware },
16061654      { CLICOMMAND_ROMIDENT,      &cli_frontend::romident },
16071655      { CLICOMMAND_GETSOFTLIST,   &cli_frontend::getsoftlist },
1608      { CLICOMMAND_VERIFYSOFTLIST,&cli_frontend::verifysoftlist },
1656      { CLICOMMAND_VERIFYSOFTLIST,    &cli_frontend::verifysoftlist },
1657      { CLICOMMAND_LIST_MIDI_DEVICES, &cli_frontend::listmididevices },
1658      { CLICOMMAND_LIST_NETWORK_ADAPTERS, &cli_frontend::listnetworkadapters },
16091659   };
16101660
16111661   // find the command
r242959r242960
16181668         return;
16191669      }
16201670
1621   if (!m_osd.execute_command(m_options.command()))
1622        // if we get here, we don't know what has been requested
1623        throw emu_fatalerror(MAMERR_INVALID_CONFIG, "Unknown command '%s' specified", m_options.command());
1671   // if we get here, we don't know what has been requested
1672   throw emu_fatalerror(MAMERR_INVALID_CONFIG, "Unknown command '%s' specified", m_options.command());
16241673}
16251674
16261675
trunk/src/emu/clifront.h
r242959r242960
1313#ifndef __CLIFRONT_H__
1414#define __CLIFRONT_H__
1515
16#include "emu.h"
17#include "cliopts.h"
16#include "emuopts.h"
17#include "drivenum.h"
1818
19// don't include osd_interface in header files
20class osd_interface;
2119
2220//**************************************************************************
21//  CONSTANTS
22//**************************************************************************
23
24// core commands
25#define CLICOMMAND_HELP                 "help"
26#define CLICOMMAND_VALIDATE             "validate"
27
28// configuration commands
29#define CLICOMMAND_CREATECONFIG         "createconfig"
30#define CLICOMMAND_SHOWCONFIG           "showconfig"
31#define CLICOMMAND_SHOWUSAGE            "showusage"
32
33// frontend commands
34#define CLICOMMAND_LISTXML              "listxml"
35#define CLICOMMAND_LISTFULL             "listfull"
36#define CLICOMMAND_LISTSOURCE           "listsource"
37#define CLICOMMAND_LISTCLONES           "listclones"
38#define CLICOMMAND_LISTBROTHERS         "listbrothers"
39#define CLICOMMAND_LISTCRC              "listcrc"
40#define CLICOMMAND_LISTROMS             "listroms"
41#define CLICOMMAND_LISTSAMPLES          "listsamples"
42#define CLICOMMAND_VERIFYROMS           "verifyroms"
43#define CLICOMMAND_VERIFYSAMPLES        "verifysamples"
44#define CLICOMMAND_ROMIDENT             "romident"
45#define CLICOMMAND_LISTDEVICES          "listdevices"
46#define CLICOMMAND_LISTSLOTS            "listslots"
47#define CLICOMMAND_LISTMEDIA            "listmedia"     // needed by MESS
48#define CLICOMMAND_LISTSOFTWARE         "listsoftware"
49#define CLICOMMAND_VERIFYSOFTWARE       "verifysoftware"
50#define CLICOMMAND_GETSOFTLIST          "getsoftlist"
51#define CLICOMMAND_VERIFYSOFTLIST       "verifysoftlist"
52#define CLICOMMAND_LIST_MIDI_DEVICES    "listmidi"
53#define CLICOMMAND_LIST_NETWORK_ADAPTERS "listnetwork"
54
55
56//**************************************************************************
2357//  TYPE DEFINITIONS
2458//**************************************************************************
2559
60// cli_options wraps the general emu options with CLI-specific additions
61class cli_options : public emu_options
62{
63public:
64   // construction/destruction
65   cli_options();
2666
67private:
68   static const options_entry s_option_entries[];
69};
70
71
2772// cli_frontend handles command-line processing and emulator execution
2873class cli_frontend
2974{
r242959r242960
75120};
76121
77122
123// media_identifier class identifies media by hash via a search in
124// the driver database
125class media_identifier
126{
127public:
128   // construction/destruction
129   media_identifier(cli_options &options);
78130
131   // getters
132   int total() const { return m_total; }
133   int matches() const { return m_matches; }
134   int nonroms() const { return m_nonroms; }
79135
136   // operations
137   void reset() { m_total = m_matches = m_nonroms = 0; }
138   void identify(const char *name);
139   void identify_file(const char *name);
140   void identify_data(const char *name, const UINT8 *data, int length);
141   int find_by_hash(const hash_collection &hashes, int length);
142
143private:
144   // internal state
145   driver_enumerator   m_drivlist;
146   int                 m_total;
147   int                 m_matches;
148   int                 m_nonroms;
149};
150
151
152
80153#endif  /* __CLIFRONT_H__ */
trunk/src/emu/cliopts.c
r242959r242960
1// license:BSD-3-Clause
2// copyright-holders:Aaron Giles
3/***************************************************************************
4
5    cliopts.c
6
7***************************************************************************/
8
9#include "clifront.h"
10#include "cliopts.h"
11
12//**************************************************************************
13//  COMMAND-LINE OPTIONS
14//**************************************************************************
15
16const options_entry cli_options::s_option_entries[] =
17{
18   /* core commands */
19   { NULL,                            NULL,       OPTION_HEADER,     "CORE COMMANDS" },
20   { CLICOMMAND_HELP ";h;?",           "0",       OPTION_COMMAND,    "show help message" },
21   { CLICOMMAND_VALIDATE ";valid",     "0",       OPTION_COMMAND,    "perform driver validation on all game drivers" },
22
23   /* configuration commands */
24   { NULL,                            NULL,       OPTION_HEADER,     "CONFIGURATION COMMANDS" },
25   { CLICOMMAND_CREATECONFIG ";cc",    "0",       OPTION_COMMAND,    "create the default configuration file" },
26   { CLICOMMAND_SHOWCONFIG ";sc",      "0",       OPTION_COMMAND,    "display running parameters" },
27   { CLICOMMAND_SHOWUSAGE ";su",       "0",       OPTION_COMMAND,    "show this help" },
28
29   /* frontend commands */
30   { NULL,                            NULL,       OPTION_HEADER,     "FRONTEND COMMANDS" },
31   { CLICOMMAND_LISTXML ";lx",         "0",       OPTION_COMMAND,    "all available info on driver in XML format" },
32   { CLICOMMAND_LISTFULL ";ll",        "0",       OPTION_COMMAND,    "short name, full name" },
33   { CLICOMMAND_LISTSOURCE ";ls",      "0",       OPTION_COMMAND,    "driver sourcefile" },
34   { CLICOMMAND_LISTCLONES ";lc",      "0",       OPTION_COMMAND,    "show clones" },
35   { CLICOMMAND_LISTBROTHERS ";lb",    "0",       OPTION_COMMAND,    "show \"brothers\", or other drivers from same sourcefile" },
36   { CLICOMMAND_LISTCRC,               "0",       OPTION_COMMAND,    "CRC-32s" },
37   { CLICOMMAND_LISTROMS ";lr",        "0",       OPTION_COMMAND,    "list required roms for a driver" },
38   { CLICOMMAND_LISTSAMPLES,           "0",       OPTION_COMMAND,    "list optional samples for a driver" },
39   { CLICOMMAND_VERIFYROMS,            "0",       OPTION_COMMAND,    "report romsets that have problems" },
40   { CLICOMMAND_VERIFYSAMPLES,         "0",       OPTION_COMMAND,    "report samplesets that have problems" },
41   { CLICOMMAND_ROMIDENT,              "0",       OPTION_COMMAND,    "compare files with known MAME roms" },
42   { CLICOMMAND_LISTDEVICES ";ld",     "0",       OPTION_COMMAND,    "list available devices" },
43   { CLICOMMAND_LISTSLOTS ";lslot",    "0",       OPTION_COMMAND,    "list available slots and slot devices" },
44   { CLICOMMAND_LISTMEDIA ";lm",       "0",       OPTION_COMMAND,    "list available media for the system" },
45   { CLICOMMAND_LISTSOFTWARE ";lsoft", "0",       OPTION_COMMAND,    "list known software for the system" },
46   { CLICOMMAND_VERIFYSOFTWARE ";vsoft", "0",     OPTION_COMMAND,    "verify known software for the system" },
47   { CLICOMMAND_GETSOFTLIST ";glist",  "0",       OPTION_COMMAND,    "retrieve software list by name" },
48   { CLICOMMAND_VERIFYSOFTLIST ";vlist", "0",     OPTION_COMMAND,    "verify software list by name" },
49   { NULL }
50};
51
52//**************************************************************************
53//  CLI OPTIONS
54//**************************************************************************
55
56//-------------------------------------------------
57//  cli_options - constructor
58//-------------------------------------------------
59
60cli_options::cli_options()
61: emu_options()
62{
63    add_entries(cli_options::s_option_entries);
64}
65
trunk/src/emu/cliopts.h
r242959r242960
1// license:BSD-3-Clause
2// copyright-holders:Aaron Giles
3/***************************************************************************
4
5    clifront.h
6
7    Command-line interface frontend for MAME.
8
9***************************************************************************/
10
11#pragma once
12
13#ifndef __CLIOPTS_H__
14#define __CLIOPTS_H__
15
16#include "emuopts.h"
17
18//**************************************************************************
19//  CONSTANTS
20//**************************************************************************
21
22// core commands
23#define CLICOMMAND_HELP                 "help"
24#define CLICOMMAND_VALIDATE             "validate"
25
26// configuration commands
27#define CLICOMMAND_CREATECONFIG         "createconfig"
28#define CLICOMMAND_SHOWCONFIG           "showconfig"
29#define CLICOMMAND_SHOWUSAGE            "showusage"
30
31// frontend commands
32#define CLICOMMAND_LISTXML              "listxml"
33#define CLICOMMAND_LISTFULL             "listfull"
34#define CLICOMMAND_LISTSOURCE           "listsource"
35#define CLICOMMAND_LISTCLONES           "listclones"
36#define CLICOMMAND_LISTBROTHERS         "listbrothers"
37#define CLICOMMAND_LISTCRC              "listcrc"
38#define CLICOMMAND_LISTROMS             "listroms"
39#define CLICOMMAND_LISTSAMPLES          "listsamples"
40#define CLICOMMAND_VERIFYROMS           "verifyroms"
41#define CLICOMMAND_VERIFYSAMPLES        "verifysamples"
42#define CLICOMMAND_ROMIDENT             "romident"
43#define CLICOMMAND_LISTDEVICES          "listdevices"
44#define CLICOMMAND_LISTSLOTS            "listslots"
45#define CLICOMMAND_LISTMEDIA            "listmedia"     // needed by MESS
46#define CLICOMMAND_LISTSOFTWARE         "listsoftware"
47#define CLICOMMAND_VERIFYSOFTWARE       "verifysoftware"
48#define CLICOMMAND_GETSOFTLIST          "getsoftlist"
49#define CLICOMMAND_VERIFYSOFTLIST       "verifysoftlist"
50
51
52//**************************************************************************
53//  TYPE DEFINITIONS
54//**************************************************************************
55
56// cli_options wraps the general emu options with CLI-specific additions
57class cli_options : public emu_options
58{
59public:
60   // construction/destruction
61   cli_options();
62
63private:
64   static const options_entry s_option_entries[];
65};
66
67#endif  /* __CLIFRONT_H__ */
trunk/src/emu/cpu/tms0980/tms0980.c
r242959r242960
6969*/
7070
7171/* Microinstructions */
72#define M_15TN              (1<<0)  /* 15 to -ALU */
73#define M_ATN               (1<<1)  /* ACC to -ALU */
74#define M_AUTA              (1<<2)  /* ALU to ACC */
75#define M_AUTY              (1<<3)  /* ALU to Y */
76#define M_C8                (1<<4)  /* CARRY8 to STATUS */
77#define M_CIN               (1<<5)  /* Carry In to ALU */
78#define M_CKM               (1<<6)  /* CKB to MEM */
79#define M_CKN               (1<<7)  /* CKB to -ALU */
80#define M_CKP               (1<<8)  /* CKB to +ALU */
81#define M_MTN               (1<<9)  /* MEM to -ALU */
82#define M_MTP               (1<<10) /* MEM to +ALU */
83#define M_NATN              (1<<11) /* ~ACC to -ALU */
84#define M_NE                (1<<12) /* COMP to STATUS */
85#define M_STO               (1<<13) /* ACC to MEM */
86#define M_STSL              (1<<14) /* STATUS to Status Latch */
87#define M_YTP               (1<<15) /* Y to +ALU */
72#define M_15TN              0x00000001 /* 15 to -ALU */
73#define M_ATN               0x00000002 /* ACC to -ALU */
74#define M_AUTA              0x00000004 /* ALU to ACC */
75#define M_AUTY              0x00000008 /* ALU to Y */
76#define M_C8                0x00000010 /* CARRY8 to STATUS */
77#define M_CIN               0x00000020 /* Carry In to ALU */
78#define M_CKM               0x00000040 /* CKB to MEM */
79#define M_CKN               0x00000080 /* CKB to -ALU */
80#define M_CKP               0x00000100 /* CKB to +ALU */
81#define M_MTN               0x00000200 /* MEM to -ALU */
82#define M_MTP               0x00000400 /* MEM to +ALU */
83#define M_NATN              0x00000800 /* ~ACC to -ALU */
84#define M_NE                0x00001000 /* COMP to STATUS */
85#define M_STO               0x00002000 /* ACC to MEM */
86#define M_STSL              0x00004000 /* STATUS to Status Latch */
87#define M_YTP               0x00008000 /* Y to +ALU */
8888
89#define M_CME               (1<<16) /* Conditional Memory Enable */
90#define M_DMTP              (1<<17) /* DAM to +ALU */
91#define M_NDMTP             (1<<18) /* ~DAM to +ALU */
92#define M_SSE               (1<<19) /* Special Status Enable */
93#define M_SSS               (1<<20) /* Special Status Sample */
89#define M_CME               0x00010000 /* Conditional Memory Enable */
90#define M_DMTP              0x00020000 /* DAM to +ALU */
91#define M_NDMTP             0x00040000 /* ~DAM to +ALU */
92#define M_SSE               0x00080000 /* Special Status Enable */
93#define M_SSS               0x00100000 /* Special Status Sample */
9494
95#define M_RSTR              (1<<21) /* -> line #36, F_RSTR (TMS02x0 custom) */
96#define M_UNK1              (1<<22) /* -> line #37, F_???? (TMS0270 custom) */
95#define M_RSTR              0x00200000 /* -> line #36, F_RSTR (TMS02x0 custom) */
96#define M_UNK1              0x00400000 /* -> line #37, F_???? (TMS0270 custom) */
9797
9898/* Standard/fixed instructions - these are documented more in their specific handlers below */
99#define F_BR                (1<<0)
100#define F_CALL              (1<<1)
101#define F_CLO               (1<<2)
102#define F_COMC              (1<<3)
103#define F_COMX              (1<<4)
104#define F_COMX8             (1<<5)
105#define F_LDP               (1<<6)
106#define F_LDX               (1<<7)
107#define F_RBIT              (1<<8)
108#define F_RETN              (1<<9)
109#define F_RSTR              (1<<10)
110#define F_SBIT              (1<<11)
111#define F_SETR              (1<<12)
112#define F_TDO               (1<<13)
113#define F_TPC               (1<<14)
99#define F_BR                0x00000001
100#define F_CALL              0x00000002
101#define F_CLO               0x00000004
102#define F_COMC              0x00000008
103#define F_COMX              0x00000010
104#define F_COMX8             0x00000020
105#define F_LDP               0x00000040
106#define F_LDX               0x00000080
107#define F_RBIT              0x00000100
108#define F_RETN              0x00000200
109#define F_RSTR              0x00000400
110#define F_SBIT              0x00000800
111#define F_SETR              0x00001000
112#define F_TDO               0x00002000
114113
115#define F_OFF               (1<<15)
116#define F_REAC              (1<<16)
117#define F_SAL               (1<<17)
118#define F_SBL               (1<<18)
119#define F_SEAC              (1<<19)
120#define F_XDA               (1<<20)
114#define F_OFF               0x00004000
115#define F_REAC              0x00008000
116#define F_SAL               0x00010000
117#define F_SBL               0x00020000
118#define F_SEAC              0x00040000
119#define F_XDA               0x00080000
121120
122121
123122// supported types:
r242959r242960
133132// - 20-term output PLA(opla) at the top-left
134133// - the ALU is between the opla and mpla
135134const device_type TMS1000 = &device_creator<tms1000_cpu_device>; // 28-pin DIP, 11 R pins
136const device_type TMS1070 = &device_creator<tms1070_cpu_device>; // almost same as tms1000, just supports higher voltage
135const device_type TMS1070 = &device_creator<tms1070_cpu_device>; // same as tms1000, just supports higher voltage
137136const device_type TMS1200 = &device_creator<tms1200_cpu_device>; // 40-pin DIP, 13 R pins
138137// TMS1270 has 10 O pins, how does that work?
139138
140139// TMS1100 is nearly the same as TMS1000, some different opcodes, and with double the RAM and ROM
141140const device_type TMS1100 = &device_creator<tms1100_cpu_device>; // 28-pin DIP, 11 R pins
142const device_type TMS1170 = &device_creator<tms1170_cpu_device>; // almost same as tms1100, just supports higher voltage
143141const device_type TMS1300 = &device_creator<tms1300_cpu_device>; // 40-pin DIP, 16 R pins
144const device_type TMS1370 = &device_creator<tms1370_cpu_device>; // almost same as tms1300, just supports higher voltage
145142
146// TMS1400 follows the TMS1100, it doubles the ROM size again (4 chapters of 16 pages), and adds a 3-level callstack
147// - rotate the view and mirror the OR-mask to get the proper layout of the mpla, the default is identical to tms1100
148// - the opla size is increased from 20 to 32 terms
149const device_type TMS1400 = &device_creator<tms1400_cpu_device>; // 28-pin DIP, 11 R pins
150const device_type TMS1470 = &device_creator<tms1470_cpu_device>; // almost same as tms1400, just supports higher voltage
151
152143// TMS0980
153144// - 64x9bit RAM array at the bottom-left (set up as 144x4)
154145// - 2048x9bit ROM array at the bottom-left
r242959r242960
186177   AM_RANGE(0x000, 0x7ff) AM_ROM
187178ADDRESS_MAP_END
188179
189static ADDRESS_MAP_START(program_12bit_8, AS_PROGRAM, 8, tms1xxx_cpu_device)
190   AM_RANGE(0x000, 0xfff) AM_ROM
191ADDRESS_MAP_END
192180
193
194181static ADDRESS_MAP_START(data_64x4, AS_DATA, 8, tms1xxx_cpu_device)
195182   AM_RANGE(0x00, 0x3f) AM_RAM
196183ADDRESS_MAP_END
r242959r242960
230217   : tms1000_cpu_device(mconfig, type, name, tag, owner, clock, o_pins, r_pins, pc_bits, byte_bits, x_bits, prgwidth, program, datawidth, data, shortname, source)
231218{ }
232219
233tms1170_cpu_device::tms1170_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
234   : tms1100_cpu_device(mconfig, TMS1170, "TMS1170", tag, owner, clock, 8, 11, 6, 8, 3, 11, ADDRESS_MAP_NAME(program_11bit_8), 7, ADDRESS_MAP_NAME(data_128x4), "tms1170", __FILE__)
235{ }
236
237220tms1300_cpu_device::tms1300_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
238   : tms1100_cpu_device(mconfig, TMS1300, "TMS1300", tag, owner, clock, 8, 16, 6, 8, 3, 11, ADDRESS_MAP_NAME(program_11bit_8), 7, ADDRESS_MAP_NAME(data_128x4), "tms1300", __FILE__)
221   : tms1100_cpu_device(mconfig, TMS1300, "TMS1200", tag, owner, clock, 8, 16, 6, 8, 3, 11, ADDRESS_MAP_NAME(program_11bit_8), 7, ADDRESS_MAP_NAME(data_128x4), "tms1300", __FILE__)
239222{ }
240223
241tms1370_cpu_device::tms1370_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
242   : tms1100_cpu_device(mconfig, TMS1370, "TMS1370", tag, owner, clock, 8, 16, 6, 8, 3, 11, ADDRESS_MAP_NAME(program_11bit_8), 7, ADDRESS_MAP_NAME(data_128x4), "tms1370", __FILE__)
243{ }
244224
245
246tms1400_cpu_device::tms1400_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
247   : tms1100_cpu_device(mconfig, TMS1400, "TMS1400", tag, owner, clock, 8, 11, 6, 8, 3, 12, ADDRESS_MAP_NAME(program_12bit_8), 7, ADDRESS_MAP_NAME(data_128x4), "tms1400", __FILE__)
248{ }
249
250tms1400_cpu_device::tms1400_cpu_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, UINT8 o_pins, UINT8 r_pins, UINT8 pc_bits, UINT8 byte_bits, UINT8 x_bits, int prgwidth, address_map_constructor program, int datawidth, address_map_constructor data, const char *shortname, const char *source)
251   : tms1100_cpu_device(mconfig, type, name, tag, owner, clock, o_pins, r_pins, pc_bits, byte_bits, x_bits, prgwidth, program, datawidth, data, shortname, source)
252{ }
253
254tms1470_cpu_device::tms1470_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
255   : tms1400_cpu_device(mconfig, TMS1470, "TMS1470", tag, owner, clock, 8, 10, 6, 8, 3, 12, ADDRESS_MAP_NAME(program_12bit_8), 7, ADDRESS_MAP_NAME(data_128x4), "tms1470", __FILE__)
256{ }
257
258
259225tms0970_cpu_device::tms0970_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
260226   : tms1000_cpu_device(mconfig, TMS0970, "TMS0970", tag, owner, clock, 8, 11, 6, 8, 2, 10, ADDRESS_MAP_NAME(program_10bit_8), 6, ADDRESS_MAP_NAME(data_64x4), "tms0970", __FILE__)
261227{ }
r242959r242960
298264}
299265
300266
301static MACHINE_CONFIG_FRAGMENT(tms1400)
302
303   // microinstructions PLA, output PLA
304   MCFG_PLA_ADD("mpla", 8, 16, 30)
305   MCFG_PLA_FILEFORMAT(PLA_FMT_BERKELEY)
306   MCFG_PLA_ADD("opla", 5, 8, 32)
307   MCFG_PLA_FILEFORMAT(PLA_FMT_BERKELEY)
308MACHINE_CONFIG_END
309
310machine_config_constructor tms1400_cpu_device::device_mconfig_additions() const
311{
312   return MACHINE_CONFIG_NAME(tms1400);
313}
314
315
316267static MACHINE_CONFIG_FRAGMENT(tms0970)
317268
318269   // main opcodes PLA, microinstructions PLA, output PLA, segment PLA
r242959r242960
631582   for (int i = 0x3c; i < 0x40; i++) m_fixed_decode[i] = 0;
632583}
633584
634void tms1400_cpu_device::device_reset()
635{
636   tms1100_cpu_device::device_reset();
637585
638   // small differences in 00-3f area
639   m_fixed_decode[0x09] = F_COMX; // !
640   m_fixed_decode[0x0b] = F_TPC;
641}
642
643
644586void tms0970_cpu_device::device_reset()
645587{
646588   // common reset
r242959r242960
957899//  fixed opcode set
958900//-------------------------------------------------
959901
960// handle branches:
961// note: add(latch) and bl(branch latch) are specific to 0980 series,
962// c(chapter) bits are specific to 1100(and 1400) series
963
964902// TMS1000/common:
965903
966void tms1xxx_cpu_device::op_br()
967{
968   // BR/BL: conditional branch
969   if (!m_status)
970      return;
971
972   if (!m_clatch)
973      m_pa = m_pb;
974   m_ca = m_cb;
975   m_pc = m_opcode & m_pc_mask;
976}
977
978void tms1xxx_cpu_device::op_call()
979{
980   // CALL/CALLL: conditional call
981   if (!m_status)
982      return;
983
984   UINT8 prev_pa = m_pa;
985   if (!m_clatch)
986   {
987      m_sr = m_pc;
988      m_clatch = 1;
989      m_pa = m_pb;
990      m_cs = m_ca;
991   }
992   m_ca = m_cb;
993   m_pb = prev_pa;
994   m_pc = m_opcode & m_pc_mask;
995}
996
997void tms1xxx_cpu_device::op_retn()
998{
999   // RETN: return from subroutine
1000   if (m_clatch)
1001   {
1002      m_pc = m_sr;
1003      m_clatch = 0;
1004      m_ca = m_cs;
1005   }
1006   m_add = 0;
1007   m_bl = 0;
1008   m_pa = m_pb;
1009}
1010
1011
1012// TMS1400-specific
1013
1014void tms1400_cpu_device::op_br()
1015{
1016   // BR/BL: conditional branch
1017   if (!m_status)
1018      return;
1019   
1020   //..
1021}
1022
1023void tms1400_cpu_device::op_call()
1024{
1025   // CALL/CALLL: conditional call
1026   if (!m_status)
1027      return;
1028
1029   //..
1030}
1031
1032void tms1400_cpu_device::op_retn()
1033{
1034   // RETN: return from subroutine
1035   //..
1036}
1037
1038
1039// handle other:
1040
1041// TMS1000/common:
1042
1043904void tms1xxx_cpu_device::op_sbit()
1044905{
1045906   // SBIT: set memory bit
r242959r242960
1131992}
1132993
1133994
1134// TMS1400-specific
1135
1136void tms1xxx_cpu_device::op_tpc()
1137{
1138   // TPC: transfer page buffer to chapter buffer
1139   m_cb = m_pb & 3;
1140}
1141
1142
1143995// TMS0970-specific (and possibly child classes)
1144996void tms0970_cpu_device::op_setr()
1145997{
r242959r242960
12431095         // fetch: rom address 1/2
12441096
12451097         // execute: br/call 2/2
1246         if (m_fixed & F_BR)    op_br();
1247         if (m_fixed & F_CALL)  op_call();
1248         if (m_fixed & F_RETN)  op_retn();
1098         // note: add(latch) and bl(branch latch) are specific to 0980 series,
1099         // c(chapter) bits are specific to 1100 series
1100         if (m_status)
1101         {
1102            UINT8 new_pc = m_opcode & m_pc_mask;
12491103
1104            // BR: conditional branch
1105            if (m_fixed & F_BR)
1106            {
1107               if (m_clatch == 0)
1108                  m_pa = m_pb;
1109               m_ca = m_cb;
1110               m_pc = new_pc;
1111            }
1112
1113            // CALL: conditional call
1114            if (m_fixed & F_CALL)
1115            {
1116               UINT8 prev_pa = m_pa;
1117               if (m_clatch == 0)
1118               {
1119                  m_sr = m_pc;
1120                  m_clatch = 1;
1121                  m_pa = m_pb;
1122                  m_cs = m_ca;
1123               }
1124               m_ca = m_cb;
1125               m_pb = prev_pa;
1126               m_pc = new_pc;
1127            }
1128         }
1129
1130         // RETN: return from subroutine
1131         if (m_fixed & F_RETN)
1132         {
1133            if (m_clatch == 1)
1134            {
1135               m_pc = m_sr;
1136               m_clatch = 0;
1137               m_ca = m_cs;
1138            }
1139            m_add = 0;
1140            m_bl = 0;
1141            m_pa = m_pb;
1142         }
1143
12501144         // execute: k input valid, read ram, clear alu inputs
12511145         dynamic_output();
12521146         set_cki_bus();
r242959r242960
13221216         if (m_fixed & F_COMX8) op_comx8();
13231217         if (m_fixed & F_LDP)   op_ldp();
13241218         if (m_fixed & F_COMC)  op_comc();
1325         if (m_fixed & F_TPC)   op_tpc();
13261219         if (m_fixed & F_OFF)   op_off();
13271220         if (m_fixed & F_SEAC)  op_seac();
13281221         if (m_fixed & F_REAC)  op_reac();
trunk/src/emu/cpu/tms0980/tms0980.h
r242959r242960
106106   virtual void dynamic_output() { ; } // not used by default
107107   virtual void read_opcode();
108108
109   virtual void op_br();
110   virtual void op_call();
111   virtual void op_retn();
112
113109   virtual void op_sbit();
114110   virtual void op_rbit();
115111   virtual void op_setr();
r242959r242960
122118   virtual void op_ldp();
123119
124120   virtual void op_comc();
125   virtual void op_tpc();
126121   virtual void op_xda();
127122   virtual void op_off();
128123   virtual void op_seac();
r242959r242960
249244   virtual void op_rstr();
250245};
251246
252class tms1170_cpu_device : public tms1100_cpu_device
253{
254public:
255   tms1170_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
256};
257
258247class tms1300_cpu_device : public tms1100_cpu_device
259248{
260249public:
261250   tms1300_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
262251};
263252
264class tms1370_cpu_device : public tms1100_cpu_device
265{
266public:
267   tms1370_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
268};
269253
270
271class tms1400_cpu_device : public tms1100_cpu_device
272{
273public:
274   tms1400_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
275   tms1400_cpu_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, UINT8 o_pins, UINT8 r_pins, UINT8 pc_bits, UINT8 byte_bits, UINT8 x_bits, int prgwidth, address_map_constructor program, int datawidth, address_map_constructor data, const char *shortname, const char *source);
276
277protected:
278   // overrides
279   virtual void device_reset();
280   virtual machine_config_constructor device_mconfig_additions() const;
281
282   virtual void op_br();
283   virtual void op_call();
284   virtual void op_retn();
285
286   virtual void op_setr() { tms1xxx_cpu_device::op_setr(); } // no anomaly with MSB of X register
287   virtual void op_rstr() { tms1xxx_cpu_device::op_rstr(); } // "
288};
289
290class tms1470_cpu_device : public tms1400_cpu_device
291{
292public:
293   tms1470_cpu_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
294};
295
296
297254class tms0970_cpu_device : public tms1000_cpu_device
298255{
299256public:
r242959r242960
387344extern const device_type TMS1070;
388345extern const device_type TMS1200;
389346extern const device_type TMS1100;
390extern const device_type TMS1170;
391347extern const device_type TMS1300;
392extern const device_type TMS1370;
393extern const device_type TMS1400;
394extern const device_type TMS1470;
395348extern const device_type TMS0970;
396349extern const device_type TMS0980;
397350extern const device_type TMS0270;
trunk/src/emu/devfind.c
r242959r242960
110110      osd_printf_verbose("Optional %s '%s' not found\n", objname, m_tag);
111111   return !required;
112112}
113
114
115void finder_base::printf_warning(const char *format, ...)
116{
117    va_list argptr;
118    char buffer[1024];
119
120    /* do the output */
121    va_start(argptr, format);
122    vsnprintf(buffer, 1024, format, argptr);
123    osd_printf_warning("%s", buffer);
124    va_end(argptr);
125}
trunk/src/emu/devfind.h
r242959r242960
5757   void *find_memshare(UINT8 width, size_t &bytes, bool required);
5858   bool report_missing(bool found, const char *objname, bool required);
5959
60    void printf_warning(const char *format, ...) ATTR_PRINTF(2,3);
61
6260   // internal state
6361   finder_base *m_next;
6462   device_t &m_base;
r242959r242960
115113      this->m_target = dynamic_cast<_DeviceClass *>(device);
116114      if (device != NULL && this->m_target == NULL)
117115      {
118         this->printf_warning("Device '%s' found but is of incorrect type (actual type is %s)\n", this->m_tag, device->name());
116         void osd_printf_warning(const char *format, ...) ATTR_PRINTF(1,2);
117         osd_printf_warning("Device '%s' found but is of incorrect type (actual type is %s)\n", this->m_tag, device->name());
119118      }
120119      return this->report_missing(this->m_target != NULL, "device", _Required);
121120   }
trunk/src/emu/emu.mak
r242959r242960
5555   $(EMUOBJ)/audit.o \
5656   $(EMUOBJ)/cheat.o \
5757   $(EMUOBJ)/clifront.o \
58   $(EMUOBJ)/cliopts.o \
5958   $(EMUOBJ)/config.o \
6059   $(EMUOBJ)/crsshair.o \
6160   $(EMUOBJ)/debugger.o \
r242959r242960
116115   $(EMUOBJ)/timer.o \
117116   $(EMUOBJ)/uiinput.o \
118117   $(EMUOBJ)/ui/ui.o \
118   $(EMUOBJ)/ui/swlist.o \
119119   $(EMUOBJ)/ui/menu.o \
120120   $(EMUOBJ)/ui/mainmenu.o \
121121   $(EMUOBJ)/ui/miscmenu.o \
122   $(EMUOBJ)/ui/barcode.o \
123   $(EMUOBJ)/ui/devopt.o \
122   $(EMUOBJ)/ui/selgame.o \
124123   $(EMUOBJ)/ui/filemngr.o \
125124   $(EMUOBJ)/ui/filesel.o \
126125   $(EMUOBJ)/ui/imgcntrl.o \
127126   $(EMUOBJ)/ui/imginfo.o \
128   $(EMUOBJ)/ui/inputmap.o \
129   $(EMUOBJ)/ui/selgame.o \
130   $(EMUOBJ)/ui/slotopt.o \
131   $(EMUOBJ)/ui/swlist.o \
127   $(EMUOBJ)/ui/barcode.o \
132128   $(EMUOBJ)/ui/tapectrl.o \
133129   $(EMUOBJ)/ui/viewgfx.o \
134130   $(EMUOBJ)/validity.o \
r242959r242960
148144   $(EMUOBJ)/debug/textbuf.o \
149145   $(EMUOBJ)/profiler.o \
150146   $(EMUOBJ)/webengine.o \
147   $(OSDOBJ)/osdcore.o \
148   $(OSDOBJ)/osdepend.o \
151149   $(OSDOBJ)/osdnet.o \
152150   $(OSDOBJ)/modules/sound/none.o \
153151   $(OSDOBJ)/modules/debugger/none.o \
trunk/src/emu/emucore.c
r242959r242960
11/***************************************************************************
22
3    emucore.c
3    mamecore.c
44
55    Simple core functions that are defined in emucore.h and which may
66    need to be accessed by other MAME-related tools.
r242959r242960
1111****************************************************************************/
1212
1313#include "emu.h"
14#include "emucore.h"
15#include "osdcore.h"
1614
17emu_fatalerror::emu_fatalerror(const char *format, ...)
18: code(0)
19{
20    if (format == NULL)
21    {
22        text[0] = '\0';
23    }
24    else
25    {
26        va_list ap;
27        va_start(ap, format);
28        vsprintf(text, format, ap);
29        va_end(ap);
30    }
31    osd_break_into_debugger(text);
32}
33
34emu_fatalerror::emu_fatalerror(const char *format, va_list ap)
35: code(0)
36{
37    if (format == NULL)
38    {
39        text[0] = '\0';
40    }
41    else
42    {
43        vsprintf(text, format, ap);
44    }
45    osd_break_into_debugger(text);
46}
47
48emu_fatalerror::emu_fatalerror(int _exitcode, const char *format, ...)
49: code(_exitcode)
50{
51    if (format == NULL)
52    {
53        text[0] = '\0';
54    }
55    else
56    {
57        va_list ap;
58        va_start(ap, format);
59        vsprintf(text, format, ap);
60        va_end(ap);
61    }
62}
63
64emu_fatalerror::emu_fatalerror(int _exitcode, const char *format, va_list ap)
65: code(_exitcode)
66{
67    if (format == NULL)
68    {
69        text[0] = '\0';
70    }
71    else
72    {
73        vsprintf(text, format, ap);
74    }
75}
76
77
7815void report_bad_cast(const std::type_info &src_type, const std::type_info &dst_type)
7916{
8017   throw emu_fatalerror("Error: bad downcast<> or device<>.  Tried to convert a %s to a %s, which are incompatible.\n",
r242959r242960
8623   throw emu_fatalerror("Error: bad downcast<> or device<>.  Tried to convert the device %s (%s) of type %s to a %s, which are incompatible.\n",
8724         dev->tag(), dev->name(), src_type.name(), dst_type.name());
8825}
89
90void fatalerror(const char *format, ...)
91{
92    va_list ap;
93    va_start(ap, format);
94    emu_fatalerror error(format, ap);
95    va_end(ap);
96    throw error;
97}
98
99void fatalerror_exitcode(running_machine &machine, int exitcode, const char *format, ...)
100{
101    va_list ap;
102    va_start(ap, format);
103    emu_fatalerror error(exitcode, format, ap);
104    va_end(ap);
105    throw error;
106}
trunk/src/emu/emucore.h
r242959r242960
289289class emu_fatalerror : public emu_exception
290290{
291291public:
292   emu_fatalerror(const char *format, ...) ATTR_PRINTF(2,3);
293   emu_fatalerror(const char *format, va_list ap);
294   emu_fatalerror(int _exitcode, const char *format, ...) ATTR_PRINTF(3,4);
295   emu_fatalerror(int _exitcode, const char *format, va_list ap);
292   emu_fatalerror(const char *format, ...) ATTR_PRINTF(2,3)
293      : code(0)
294   {
295      if (format == NULL)
296      {
297         text[0] = '\0';
298      }
299      else
300      {
301         va_list ap;
302         va_start(ap, format);
303         vsprintf(text, format, ap);
304         va_end(ap);
305      }
306      osd_break_into_debugger(text);
307   }
296308
309   emu_fatalerror(const char *format, va_list ap)
310      : code(0)
311   {
312      if (format == NULL)
313      {
314         text[0] = '\0';
315      }
316      else
317      {
318         vsprintf(text, format, ap);
319      }
320      osd_break_into_debugger(text);
321   }
322
323   emu_fatalerror(int _exitcode, const char *format, ...) ATTR_PRINTF(3,4)
324      : code(_exitcode)
325   {
326      if (format == NULL)
327      {
328         text[0] = '\0';
329      }
330      else
331      {
332         va_list ap;
333         va_start(ap, format);
334         vsprintf(text, format, ap);
335         va_end(ap);
336      }
337   }
338
339   emu_fatalerror(int _exitcode, const char *format, va_list ap)
340      : code(_exitcode)
341   {
342      if (format == NULL)
343      {
344         text[0] = '\0';
345      }
346      else
347      {
348         vsprintf(text, format, ap);
349      }
350   }
351
297352   const char *string() const { return text; }
298353   int exitcode() const { return code; }
299354
r242959r242960
366421ATTR_NORETURN void fatalerror(const char *format, ...) ATTR_PRINTF(1,2);
367422ATTR_NORETURN void fatalerror_exitcode(running_machine &machine, int exitcode, const char *format, ...) ATTR_PRINTF(3,4);
368423
424inline void fatalerror(const char *format, ...)
425{
426   va_list ap;
427   va_start(ap, format);
428   emu_fatalerror error(format, ap);
429   va_end(ap);
430   throw error;
431}
432
433inline void fatalerror_exitcode(running_machine &machine, int exitcode, const char *format, ...)
434{
435   va_list ap;
436   va_start(ap, format);
437   emu_fatalerror error(exitcode, format, ap);
438   va_end(ap);
439   throw error;
440}
441
442
443
369444//**************************************************************************
370445//  INLINE FUNCTIONS
371446//**************************************************************************
trunk/src/emu/emuopts.c
r242959r242960
150150
151151   // debugging options
152152   { NULL,                                              NULL,        OPTION_HEADER,     "CORE DEBUGGING OPTIONS" },
153    { OPTION_VERBOSE ";v",                               "0",         OPTION_BOOLEAN,    "display additional diagnostic information" },
154    { OPTION_LOG,                                        "0",         OPTION_BOOLEAN,    "generate an error.log file" },
155    { OPTION_OSLOG,                                      "0",         OPTION_BOOLEAN,    "output error.log data to the system debugger" },
156    { OPTION_DEBUG ";d",                                 "0",         OPTION_BOOLEAN,    "enable/disable debugger" },
157153   { OPTION_UPDATEINPAUSE,                              "0",         OPTION_BOOLEAN,    "keep calling video updates while in pause" },
158154   { OPTION_DEBUGSCRIPT,                                NULL,        OPTION_STRING,     "script for debugger" },
159155
r242959r242960
191187//-------------------------------------------------
192188
193189emu_options::emu_options()
194: core_options()
195190{
196   add_entries(emu_options::s_option_entries);
191   add_entries(s_option_entries);
192   add_osd_options();
197193}
198194
199195
r242959r242960
508504   }
509505}
510506
507
511508//-------------------------------------------------
509//  device_option - return the value of the
510//  device-specific option
511//-------------------------------------------------
512
513const char *emu_options::device_option(device_image_interface &image)
514{
515   return value(image.instance_name());
516}
517
518
519//-------------------------------------------------
512520//  parse_one_ini - parse a single INI file
513521//-------------------------------------------------
514522
trunk/src/emu/emuopts.h
r242959r242960
1515
1616#include "options.h"
1717
18
1819//**************************************************************************
1920//  CONSTANTS
2021//**************************************************************************
r242959r242960
153154#define OPTION_MOUSE_DEVICE         "mouse_device"
154155
155156// core debugging options
156#define OPTION_LOG                  "log"
157#define OPTION_DEBUG                "debug"
158#define OPTION_VERBOSE              "verbose"
159#define OPTION_OSLOG                "oslog"
160157#define OPTION_UPDATEINPAUSE        "update_in_pause"
161158#define OPTION_DEBUGSCRIPT          "debugscript"
162159
r242959r242960
191188struct game_driver;
192189
193190
194class emu_options : public core_options
191class emu_options : public osd_options
195192{
196193   static const UINT32 OPTION_FLAG_DEVICE = 0x80000000;
197194
r242959r242960
318315   bool joystick_contradictory() const { return bool_value(OPTION_JOYSTICK_CONTRADICTORY); }
319316   int coin_impulse() const { return int_value(OPTION_COIN_IMPULSE); }
320317
321    // core debugging options
322    bool log() const { return bool_value(OPTION_LOG); }
323    bool debug() const { return bool_value(OPTION_DEBUG); }
324    bool verbose() const { return bool_value(OPTION_VERBOSE); }
325    bool oslog() const { return bool_value(OPTION_OSLOG); }
318   // core debugging options
326319   const char *debug_script() const { return value(OPTION_DEBUGSCRIPT); }
327320   bool update_in_pause() const { return bool_value(OPTION_UPDATEINPAUSE); }
328321
r242959r242960
349342   const char *http_path() const { return value(OPTION_HTTP_PATH); }
350343   bool console() const { return bool_value(OPTION_CONSOLE); }
351344
352   // FIXME: Couriersud: This should be in image_device_exit
345   // device-specific options
346   const char *device_option(device_image_interface &image);
347
353348   void remove_device_options();
354349
355350   const char *main_value(astring &buffer, const char *option) const;
356351   const char *sub_value(astring &buffer, const char *name, const char *subname) const;
357   bool add_slot_options(bool isfirst);
358
359352private:
360353   // device-specific option handling
361354   void add_device_options(bool isfirst);
355   bool add_slot_options(bool isfirst);
362356   void update_slot_options();
363357
364358   // INI parsing helper
trunk/src/emu/image.c
r242959r242960
210210   for (device_image_interface *image = iter.first(); image != NULL; image = iter.next())
211211   {
212212      /* is an image specified for this image */
213      image_name = machine.options().value(image->instance_name());
213      image_name = machine.options().device_option(*image);
214214
215215      if ((image_name != NULL) && (image_name[0] != '\0'))
216216      {
trunk/src/emu/imagedev/floppy.c
r242959r242960
162162      fif_list(NULL)
163163{
164164   extension_list[0] = '\0';
165   m_err = IMAGE_ERROR_INVALIDIMAGE;
166165}
167166
168167//-------------------------------------------------
trunk/src/emu/ioport.c
r242959r242960
9999#include "uiinput.h"
100100#include "debug/debugcon.h"
101101
102#include "osdepend.h"
103
104102#include <ctype.h>
105103#include <time.h>
106104
trunk/src/emu/luaengine.c
r242959r242960
6868   {
6969      const char *msg = lua_tostring(m_lua_state, -1);
7070      if (msg == NULL) msg = "(error object is not a string)";
71      lua_writestringerror("%s\n", msg);
71      luai_writestringerror("%s\n", msg);
7272      lua_pop(m_lua_state, 1);
7373      /* force a complete garbage collection in case of errors */
7474      lua_gc(m_lua_state, LUA_GCCOLLECT, 0);
r242959r242960
360360   } else if (strcmp(hookname, "frame") == 0) {
361361      hook_frame_cb.set(L, 1);
362362   } else {
363      lua_writestringerror("%s", "Unknown hook name, aborting.\n");
363      luai_writestringerror("%s", "Unknown hook name, aborting.\n");
364364   }
365365}
366366
r242959r242960
948948         lua_getglobal(m_lua_state, "print");
949949         lua_insert(m_lua_state, 1);
950950         if (lua_pcall(m_lua_state, lua_gettop(m_lua_state) - 1, 0, 0) != LUA_OK)
951            lua_writestringerror("%s\n", lua_pushfstring(m_lua_state,
951            luai_writestringerror("%s\n", lua_pushfstring(m_lua_state,
952952            "error calling " LUA_QL("print") " (%s)",
953953            lua_tostring(m_lua_state, -1)));
954954      }
trunk/src/emu/machine.c
r242959r242960
106106//  RUNNING MACHINE
107107//**************************************************************************
108108
109osd_interface &running_machine::osd() const
110{
111    return m_manager.osd();
112}
113
114109//-------------------------------------------------
115110//  running_machine - constructor
116111//-------------------------------------------------
trunk/src/emu/machine.h
r242959r242960
1919
2020#include <time.h>
2121
22// forward declaration instead of osdepend.h
23class osd_interface;
2422
23
2524//**************************************************************************
2625//  CONSTANTS
2726//**************************************************************************
r242959r242960
158157   const machine_config &config() const { return m_config; }
159158   device_t &root_device() const { return m_config.root_device(); }
160159   const game_driver &system() const { return m_system; }
161   osd_interface &osd() const;
160   osd_interface &osd() const { return m_manager.osd(); }
162161   machine_manager &manager() const { return m_manager; }
163162   resource_pool &respool() { return m_respool; }
164163   device_scheduler &scheduler() { return m_scheduler; }
trunk/src/emu/machine/atahle.c
r242959r242960
8282   m_buffer.resize(sector_length());
8383   save_item(NAME(m_buffer));
8484   save_item(NAME(m_buffer_offset));
85   save_item(NAME(m_buffer_size));
8685   save_item(NAME(m_error));
8786   save_item(NAME(m_feature));
8887   save_item(NAME(m_sector_count));
trunk/src/emu/machine/idehd.c
r242959r242960
179179   ata_hle_device::device_start();
180180
181181   save_item(NAME(m_can_identify_device));
182   save_item(NAME(m_num_cylinders));
183   save_item(NAME(m_num_sectors));
184   save_item(NAME(m_num_heads));
185
186182   save_item(NAME(m_cur_lba));
187183   save_item(NAME(m_sectors_until_int));
188184   save_item(NAME(m_master_password_enable));
trunk/src/emu/mame.c
r242959r242960
9292
9393machine_manager* machine_manager::m_manager = NULL;
9494
95osd_interface &machine_manager::osd() const
96{
97    return m_osd;
98}
99
100
10195machine_manager* machine_manager::instance(emu_options &options,osd_interface &osd)
10296{
10397   if(!m_manager)
trunk/src/emu/mame.h
r242959r242960
2222
2323#include "webengine.h"
2424
25class osd_interface;
2625
2726//**************************************************************************
2827//    CONSTANTS
r242959r242960
8988   static machine_manager *instance();
9089   ~machine_manager();
9190
92   osd_interface &osd() const;
91   osd_interface &osd() const { return m_osd; }
9392   emu_options &options() const { return m_options; }
9493   web_engine *web() { return &m_web; }
9594   lua_engine *lua() { return &m_lua; }
trunk/src/emu/netlist/analog/nld_bjt.c
r242959r242960
7575   connect(m_RB.m_P, m_BC_dummy.m_P);
7676   connect(m_RC.m_P, m_BC_dummy.m_N);
7777
78   save(NLNAME(m_state_on));
78   save(NAME(m_state_on));
7979
8080   m_RB.set(netlist().gmin(), 0.0, 0.0);
8181   m_RC.set(netlist().gmin(), 0.0, 0.0);
trunk/src/emu/netlist/analog/nld_ms_direct.h
r242959r242960
6969   {
7070      //delete[] m_A[k];
7171   }
72    for (int k = 0; k < N(); k++)
73    {
74        nl_free(m_terms[k]);
75        nl_free(m_row_ops[k]);
76    }
77    nl_free(m_row_ops[N()]);
78    //delete[] m_last_RHS;
72   //delete[] m_last_RHS;
7973   //delete[] m_RHS;
80   nl_free_array(m_terms);
81   nl_free_array(m_rails_temp);
74   delete[] m_terms;
75   delete[] m_rails_temp;
8276   //delete[] m_row_ops;
8377
8478}
r242959r242960
458452, m_dim(size)
459453, m_lp_fact(0)
460454{
461   m_terms = nl_alloc_array(terms_t *, N());
462   m_rails_temp = nl_alloc_array(terms_t, N());
455   m_terms = new terms_t *[N()];
456   m_rails_temp = new terms_t[N()];
463457
464458   for (int k = 0; k < N(); k++)
465459   {
466      m_terms[k] = nl_alloc(terms_t);
460      m_terms[k] = new terms_t;
467461      m_row_ops[k] = vector_ops_t::create_ops(k);
468462   }
469463   m_row_ops[N()] = vector_ops_t::create_ops(N());
r242959r242960
475469, m_dim(size)
476470, m_lp_fact(0)
477471{
478    m_terms = nl_alloc_array(terms_t *, N());
479    m_rails_temp = nl_alloc_array(terms_t, N());
472    m_terms = new terms_t *[N()];
473    m_rails_temp = new terms_t[N()];
480474
481475    for (int k = 0; k < N(); k++)
482476    {
483        m_terms[k] = nl_alloc(terms_t);
477        m_terms[k] = new terms_t;
484478        m_row_ops[k] = vector_ops_t::create_ops(k);
485479    }
486480    m_row_ops[N()] = vector_ops_t::create_ops(N());
trunk/src/emu/netlist/analog/nld_solver.c
r242959r242960
4444   switch (size)
4545   {
4646      case 1:
47         return nl_alloc(vector_ops_impl_t<1>);
47         return new vector_ops_impl_t<1>();
4848      case 2:
49         return nl_alloc(vector_ops_impl_t<2>);
49         return new vector_ops_impl_t<2>();
5050      case 3:
51         return nl_alloc(vector_ops_impl_t<3>);
51         return new vector_ops_impl_t<3>();
5252      case 4:
53         return nl_alloc(vector_ops_impl_t<4>);
53         return new vector_ops_impl_t<4>();
5454      case 5:
55         return nl_alloc(vector_ops_impl_t<5>);
55         return new vector_ops_impl_t<5>();
5656      case 6:
57         return nl_alloc(vector_ops_impl_t<6>);
57         return new vector_ops_impl_t<6>();
5858      case 7:
59         return nl_alloc(vector_ops_impl_t<7>);
59         return new vector_ops_impl_t<7>();
6060      case 8:
61         return nl_alloc(vector_ops_impl_t<8>);
61         return new vector_ops_impl_t<8>();
6262      case 9:
63         return nl_alloc(vector_ops_impl_t<9>);
63         return new vector_ops_impl_t<9>();
6464      case 10:
65         return nl_alloc(vector_ops_impl_t<10>);
65         return new vector_ops_impl_t<10>();
6666      case 11:
67         return nl_alloc(vector_ops_impl_t<11>);
67         return new vector_ops_impl_t<11>();
6868      case 12:
69         return nl_alloc(vector_ops_impl_t<12>);
69         return new vector_ops_impl_t<12>();
7070      default:
71         return nl_alloc(vector_ops_impl_t<0>, size);
71         return new vector_ops_impl_t<0>(size);
7272   }
7373}
7474
r242959r242960
9191      m_term[i]->m_Idr1 = &m_Idr[i];
9292      m_other_curanalog[i] = &m_term[i]->m_otherterm->net().as_analog().m_cur_Analog;
9393   }
94
95   m_ops = vector_ops_t::create_ops(m_gt.count());
9496}
9597
9698// ----------------------------------------------------------------------------------------
r242959r242960
110112ATTR_COLD netlist_matrix_solver_t::~netlist_matrix_solver_t()
111113{
112114   for (int i = 0; i < m_inps.count(); i++)
113      global_free(m_inps[i]);
115      delete m_inps[i];
114116}
115117
116118ATTR_COLD void netlist_matrix_solver_t::setup(netlist_analog_net_t::list_t &nets)
r242959r242960
174176
175177                  if (net_proxy_output == NULL)
176178                  {
177                     net_proxy_output = nl_alloc(netlist_analog_output_t);
179                     net_proxy_output = new netlist_analog_output_t();
178180                     net_proxy_output->init_object(*this, this->name() + "." + pstring::sprintf("m%d", m_inps.count()));
179181                     m_inps.add(net_proxy_output);
180182                     net_proxy_output->m_proxied_net = &p->net().as_analog();
r242959r242960
378380   while (e != NULL)
379381   {
380382      netlist_matrix_solver_t * const *en = m_mat_solvers.next(e);
381      global_free(*e);
383      delete *e;
382384      e = en;
383385   }
384386
r242959r242960
433435netlist_matrix_solver_t * NETLIB_NAME(solver)::create_solver(int size, const int gs_threshold, const bool use_specific)
434436{
435437   if (use_specific && m_N == 1)
436      return nl_alloc(netlist_matrix_solver_direct1_t, m_params);
438      return new netlist_matrix_solver_direct1_t(m_params);
437439   else if (use_specific && m_N == 2)
438      return nl_alloc(netlist_matrix_solver_direct2_t, m_params);
440      return new netlist_matrix_solver_direct2_t(m_params);
439441   else
440442   {
441       typedef netlist_matrix_solver_gauss_seidel_t<m_N,_storage_N> solver_N;
442443      if (size >= gs_threshold)
443         return nl_alloc(solver_N, m_params, size);
444         return new netlist_matrix_solver_gauss_seidel_t<m_N,_storage_N>(m_params, size);
444445      else
445         return nl_alloc(solver_N, m_params, size);
446         return new netlist_matrix_solver_direct_t<m_N, _storage_N>(m_params, size);
446447   }
447448}
448449
trunk/src/emu/netlist/analog/nld_solver.h
r242959r242960
8888   vector_ops_impl_t(int size)
8989   : vector_ops_t(size)
9090   {
91      nl_assert(m_N == 0);
91      assert(m_N == 0);
9292   }
9393
9494   virtual ~vector_ops_impl_t() {}
r242959r242960
155155   NETLIST_PREVENT_COPYING(terms_t)
156156
157157   public:
158   ATTR_COLD terms_t() : m_railstart(0)
158   ATTR_COLD terms_t() : m_railstart(0), m_ops(NULL)
159159   {}
160160
161161   ATTR_COLD void clear()
r242959r242960
175175   ATTR_HOT inline double *go() { return m_go; }
176176   ATTR_HOT inline double *Idr() { return m_Idr; }
177177   ATTR_HOT inline double **other_curanalog() { return m_other_curanalog; }
178   ATTR_HOT vector_ops_t *ops() { return m_ops; }
178179
179180   ATTR_COLD void set_pointers();
180181
r242959r242960
187188   plinearlist_t<double> m_gt;
188189   plinearlist_t<double> m_Idr;
189190   plinearlist_t<double *> m_other_curanalog;
191   vector_ops_t * m_ops;
190192};
191193
192194class netlist_matrix_solver_t : public netlist_device_t
trunk/src/emu/netlist/devices/net_lib.c
r242959r242960
4949
5050#include "net_lib.h"
5151#include "nld_system.h"
52#include "../nl_factory.h"
5352
5453NETLIST_START(diode_models)
5554   NET_MODEL(".model 1N914 D(Is=2.52n Rs=.568 N=1.752 Cjo=4p M=.4 tt=20n Iave=200m Vpk=75 mfg=OnSemi type=silicon)")
r242959r242960
6564
6665
6766#define xstr(s) # s
68#define ENTRY1(_nic, _name, _defparam) factory.register_device<_nic>( # _name, xstr(_nic), _defparam );
67#define ENTRY1(_nic, _name, _defparam) register_device<_nic>( # _name, xstr(_nic), _defparam );
6968#define ENTRY(_nic, _name, _defparam) ENTRY1(NETLIB_NAME(_nic), _name, _defparam)
7069
71void nl_initialize_factory(netlist_factory_t &factory)
70netlist_factory_t::netlist_factory_t()
7271{
72}
73
74netlist_factory_t::~netlist_factory_t()
75{
76   for (net_device_t_base_factory * const *e = m_list.first(); e != NULL; e = m_list.next(e))
77   {
78      net_device_t_base_factory *p = *e;
79      delete p;
80   }
81   m_list.clear();
82}
83
84void netlist_factory_t::initialize()
85{
7386   ENTRY(R,                    RES,                    "R")
7487   ENTRY(POT,                  POT,                    "R")
7588   ENTRY(C,                    CAP,                    "C")
r242959r242960
149162   ENTRY(NE555_dip,            NE555_DIP,              "-")
150163}
151164
165netlist_device_t *netlist_factory_t::new_device_by_classname(const pstring &classname, netlist_setup_t &setup) const
166{
167   for (net_device_t_base_factory * const *e = m_list.first(); e != NULL; e = m_list.next(e))
168   {
169      net_device_t_base_factory *p = *e;
170      if (strcmp(p->classname(), classname) == 0)
171      {
172         netlist_device_t *ret = p->Create();
173         return ret;
174      }
175      p++;
176   }
177   setup.netlist().error("Class %s not found!\n", classname.cstr());
178   return NULL; // appease code analysis
179}
180
181netlist_device_t *netlist_factory_t::new_device_by_name(const pstring &name, netlist_setup_t &setup) const
182{
183   net_device_t_base_factory *f = factory_by_name(name, setup);
184   return f->Create();
185}
186
187net_device_t_base_factory * netlist_factory_t::factory_by_name(const pstring &name, netlist_setup_t &setup) const
188{
189   for (net_device_t_base_factory * const *e = m_list.first(); e != NULL; e = m_list.next(e))
190   {
191      net_device_t_base_factory *p = *e;
192      if (strcmp(p->name(), name) == 0)
193      {
194         return p;
195      }
196      p++;
197   }
198   setup.netlist().error("Class %s not found!\n", name.cstr());
199   return NULL; // appease code analysis
200}
trunk/src/emu/netlist/devices/net_lib.h
r242959r242960
9999NETLIST_EXTERNAL(diode_models);
100100NETLIST_EXTERNAL(bjt_models);
101101
102void nl_initialize_factory(netlist_factory_t &factory);
103
104102#endif
trunk/src/emu/netlist/devices/nld_4020.c
r242959r242960
5151   register_output("Q13", m_Q[12]);
5252   register_output("Q14", m_Q[13]);
5353
54   save(NLNAME(m_cnt));
54   save(NAME(m_cnt));
5555}
5656
5757NETLIB_RESET(4020_sub)
trunk/src/emu/netlist/devices/nld_74107.c
r242959r242960
1111   register_output("Q", m_Q);
1212   register_output("QQ", m_QQ);
1313
14   save(NLNAME(m_Q1));
15   save(NLNAME(m_Q2));
16   save(NLNAME(m_F));
14   save(NAME(m_Q1));
15   save(NAME(m_Q2));
16   save(NAME(m_F));
1717}
1818
1919NETLIB_RESET(74107Asub)
trunk/src/emu/netlist/devices/nld_74123.c
r242959r242960
3232   connect(m_RN.m_P, m_RP.m_N);
3333   connect(m_CV, m_RN.m_P);
3434
35   save(NLNAME(m_last_trig));
36   save(NLNAME(m_state));
37   save(NLNAME(m_KP));
35   save(NAME(m_last_trig));
36   save(NAME(m_state));
37   save(NAME(m_KP));
3838
3939   m_KP = 1.0 / (1.0 + exp(m_K.Value()));
4040}
trunk/src/emu/netlist/devices/nld_74153.c
r242959r242960
2222
2323   m_chan = 0;
2424
25   save(NLNAME(m_chan));
25   save(NAME(m_chan));
2626}
2727
2828NETLIB_RESET(74153sub)
trunk/src/emu/netlist/devices/nld_7448.c
r242959r242960
7878   register_output("f", m_f);
7979   register_output("g", m_g);
8080
81   save(NLNAME(m_state));
81   save(NAME(m_state));
8282}
8383
8484NETLIB_RESET(7448_sub)
r242959r242960
9898
9999NETLIB_FUNC_VOID(7448_sub, update_outputs, (UINT8 v))
100100{
101   nl_assert(v<16);
101   assert(v<16);
102102   if (v != m_state)
103103   {
104104      // max transfer time is 100 NS */
trunk/src/emu/netlist/devices/nld_7474.c
r242959r242960
7676   register_output("Q",   m_Q);
7777   register_output("QQ",  m_QQ);
7878
79   save(NLNAME(m_nextD));
79   save(NAME(m_nextD));
8080}
8181
8282NETLIB_RESET(7474sub)
trunk/src/emu/netlist/devices/nld_7483.c
r242959r242960
2323   register_output("S4", m_S4);
2424   register_output("C4", m_C4);
2525
26   save(NLNAME(m_lastr));
26   save(NAME(m_lastr));
2727}
2828
2929NETLIB_RESET(7483)
trunk/src/emu/netlist/devices/nld_7490.c
r242959r242960
1919   register_output("QC", m_Q[2]);
2020   register_output("QD", m_Q[3]);
2121
22   save(NLNAME(m_cnt));
23   save(NLNAME(m_last_A));
24   save(NLNAME(m_last_B));
22   save(NAME(m_cnt));
23   save(NAME(m_last_A));
24   save(NAME(m_last_B));
2525
2626}
2727
trunk/src/emu/netlist/devices/nld_7493.c
r242959r242960
4040   register_input("CLK", m_I);
4141   register_output("Q", m_Q);
4242
43   save(NLNAME(m_reset));
43   save(NAME(m_reset));
4444}
4545
4646NETLIB_RESET(7493ff)
trunk/src/emu/netlist/devices/nld_74ls629.c
r242959r242960
4949
5050   reset();
5151
52   save(NLNAME(m_enableq));
53   save(NLNAME(m_inc));
54   save(NLNAME(m_out));
52   save(NAME(m_enableq));
53   save(NAME(m_inc));
54   save(NAME(m_out));
5555}
5656
5757NETLIB_RESET(SN74LS629clk)
trunk/src/emu/netlist/devices/nld_9316.c
r242959r242960
7373   register_output("QD", m_QD);
7474   register_output("RC", m_RC);
7575
76   save(NLNAME(m_cnt.ref()));
77   save(NLNAME(m_loadq.ref()));
78   save(NLNAME(m_ent.ref()));
76   save(NAME(m_cnt.ref()));
77   save(NAME(m_loadq.ref()));
78   save(NAME(m_ent.ref()));
7979}
8080
8181NETLIB_RESET(9316_sub)
trunk/src/emu/netlist/devices/nld_ne555.c
r242959r242960
4242   connect(m_R2.m_N, m_R3.m_P);
4343   connect(m_RDIS.m_N, m_R3.m_N);
4444
45   save(NLNAME(m_last_out));
45   save(NAME(m_last_out));
4646}
4747
4848NETLIB_RESET(NE555)
trunk/src/emu/netlist/devices/nld_signal.h
r242959r242960
4444      {
4545         register_input(sIN[i], m_i[i]);
4646      }
47      save(NLNAME(m_active));
47      save(NAME(m_active));
4848   }
4949
5050   ATTR_COLD void reset()
r242959r242960
118118      register_input("A", m_i[0]);
119119      register_input("B", m_i[1]);
120120
121      save(NLNAME(m_active));
121      save(NAME(m_active));
122122   }
123123
124124   ATTR_COLD void reset()
trunk/src/emu/netlist/devices/nld_system.h
r242959r242960
198198   ATTR_COLD nld_a_to_d_proxy(netlist_input_t &in_proxied)
199199         : netlist_device_t()
200200   {
201      nl_assert(in_proxied.family() == LOGIC);
201      assert(in_proxied.family() == LOGIC);
202202      m_I.m_logic_family = in_proxied.m_logic_family;
203203   }
204204
r242959r242960
240240   ATTR_COLD nld_base_d_to_a_proxy(netlist_output_t &out_proxied)
241241         : netlist_device_t()
242242   {
243      nl_assert(out_proxied.family() == LOGIC);
243      assert(out_proxied.family() == LOGIC);
244244      m_logic_family = out_proxied.m_logic_family;
245245   }
246246
trunk/src/emu/netlist/devices/nld_truthtable.h
r242959r242960
5050      {
5151         nl_util::pstring_list io = nl_util::split(ttline,"|");
5252         // checks
53         nl_assert(io.count() == 2);
53         assert(io.count() == 2);
5454         nl_util::pstring_list inout = nl_util::split(io[0], ",");
55         nl_assert(inout.count() == m_num_bits);
55         assert(inout.count() == m_num_bits);
5656         nl_util::pstring_list out = nl_util::split(io[1], ",");
57         nl_assert(out.count() == m_NO);
57         assert(out.count() == m_NO);
5858
5959         for (int i=0; i < m_NI; i++)
6060         {
r242959r242960
133133      {
134134         nl_util::pstring_list io = nl_util::split(ttline,"|");
135135         // checks
136         nl_assert(io.count() == 3);
136         assert(io.count() == 3);
137137         nl_util::pstring_list inout = nl_util::split(io[0], ",");
138         nl_assert(inout.count() == m_num_bits);
138         assert(inout.count() == m_num_bits);
139139         nl_util::pstring_list out = nl_util::split(io[1], ",");
140         nl_assert(out.count() == m_NO);
140         assert(out.count() == m_NO);
141141         nl_util::pstring_list times = nl_util::split(io[2], ",");
142         nl_assert(times.count() == m_NO);
142         assert(times.count() == m_NO);
143143
144144         UINT16 val = 0;
145145         UINT8 tindex[m_NO];
trunk/src/emu/netlist/netlist.mak
r242959r242960
2626   $(NETLISTOBJ)/nl_base.o \
2727   $(NETLISTOBJ)/nl_parser.o \
2828   $(NETLISTOBJ)/nl_setup.o \
29   $(NETLISTOBJ)/nl_factory.o \
3029   $(NETLISTOBJ)/pstring.o \
3130   $(NETLISTOBJ)/pstate.o \
3231   $(NETLISTOBJ)/analog/nld_bjt.o \
trunk/src/emu/netlist/nl_base.c
r242959r242960
99#include "pstring.h"
1010#include "nl_util.h"
1111
12#include <stdlib.h> // FIXME: only included for atof
13
1412const netlist_time netlist_time::zero = netlist_time::from_raw(0);
1513
1614netlist_logic_family_desc_t netlist_family_TTL =
r242959r242960
152150   {
153151      if (!m_nets[i]->isRailNet())
154152      {
155         global_free(m_nets[i]);
153         delete m_nets[i];
156154      }
157155   }
158156
r242959r242960
166164ATTR_COLD void netlist_base_t::save_register()
167165{
168166   save(static_cast<pstate_callback_t &>(m_queue), "m_queue");
169   save(NLNAME(m_time));
167   save(NAME(m_time));
170168   netlist_object_t::save_register();
171169}
172170
r242959r242960
531529
532530ATTR_COLD void netlist_net_t::register_railterminal(netlist_output_t &mr)
533531{
534   nl_assert(m_railterminal == NULL);
532   assert(m_railterminal == NULL);
535533   m_railterminal = &mr;
536534}
537535
r242959r242960
547545
548546ATTR_COLD void netlist_net_t::save_register()
549547{
550   save(NLNAME(m_time));
551   save(NLNAME(m_active));
552   save(NLNAME(m_in_queue));
553   save(NLNAME(m_cur_Analog));
554   save(NLNAME(m_cur_Q));
555   save(NLNAME(m_new_Q));
548   save(NAME(m_time));
549   save(NAME(m_active));
550   save(NAME(m_in_queue));
551   save(NAME(m_cur_Analog));
552   save(NAME(m_cur_Q));
553   save(NAME(m_new_Q));
556554   netlist_object_t::save_register();
557555}
558556
r242959r242960
571569ATTR_HOT ATTR_ALIGN inline void netlist_net_t::update_devs()
572570{
573571   //assert(m_num_cons != 0);
574   nl_assert(this->isRailNet());
572   assert(this->isRailNet());
575573
576574   const UINT32 masks[4] = { 1, 5, 3, 1 };
577575   const UINT32 mask = masks[ (m_cur_Q  << 1) | m_new_Q ];
r242959r242960
709707
710708ATTR_COLD void netlist_analog_net_t::save_register()
711709{
712   save(NLNAME(m_DD_n_m_1));
713   save(NLNAME(m_h_n_m_1));
710   save(NAME(m_DD_n_m_1));
711   save(NAME(m_h_n_m_1));
714712   netlist_net_t::save_register();
715713}
716714
r242959r242960
805803
806804ATTR_COLD void netlist_terminal_t::save_register()
807805{
808   save(NLNAME(m_Idr1));
809   save(NLNAME(m_go1));
810   save(NLNAME(m_gt1));
806   save(NAME(m_Idr1));
807   save(NAME(m_go1));
808   save(NAME(m_gt1));
811809   netlist_core_terminal_t::save_register();
812810}
813811
trunk/src/emu/netlist/nl_base.h
r242959r242960
444444   ATTR_HOT inline const state_e state() const { return m_state; }
445445   ATTR_HOT inline void set_state(const state_e astate)
446446   {
447      nl_assert(astate != STATE_NONEX);
447      assert(astate != STATE_NONEX);
448448      m_state = astate;
449449   }
450450
r242959r242960
453453protected:
454454   ATTR_COLD virtual void save_register()
455455   {
456      save(NLNAME(m_state));
456      save(NAME(m_state));
457457      netlist_owned_object_t::save_register();
458458   }
459459
r242959r242960
710710    */
711711   ATTR_COLD inline netlist_sig_t &Q_state_ptr()
712712   {
713      nl_assert(family() == LOGIC);
713      assert(family() == LOGIC);
714714      return m_cur_Q;
715715   }
716716
r242959r242960
738738
739739   ATTR_HOT inline const double Q_Analog() const
740740   {
741      //nl_assert(object_type(SIGNAL_MASK) == SIGNAL_ANALOG);
742      nl_assert(family() == ANALOG);
741      //assert(object_type(SIGNAL_MASK) == SIGNAL_ANALOG);
742      assert(family() == ANALOG);
743743      return m_cur_Analog;
744744   }
745745
746746   ATTR_COLD inline double &Q_Analog_state_ptr()
747747   {
748      //nl_assert(object_type(SIGNAL_MASK) == SIGNAL_ANALOG);
749      nl_assert(family() == ANALOG);
748      //assert(object_type(SIGNAL_MASK) == SIGNAL_ANALOG);
749      assert(family() == ANALOG);
750750      return m_cur_Analog;
751751   }
752752
r242959r242960
883883protected:
884884   ATTR_COLD virtual void save_register()
885885   {
886      save(NLNAME(m_param));
886      save(NAME(m_param));
887887      netlist_param_t::save_register();
888888   }
889889
r242959r242960
905905protected:
906906   ATTR_COLD virtual void save_register()
907907   {
908      save(NLNAME(m_param));
908      save(NAME(m_param));
909909      netlist_param_t::save_register();
910910   }
911911
r242959r242960
988988
989989   ATTR_HOT inline const netlist_sig_t INPLOGIC(const netlist_logic_input_t &inp) const
990990   {
991      nl_assert(inp.state() != netlist_input_t::STATE_INP_PASSIVE);
991      assert(inp.state() != netlist_input_t::STATE_INP_PASSIVE);
992992      return inp.Q();
993993   }
994994
r242959r242960
12621262
12631263ATTR_HOT inline netlist_logic_net_t & RESTRICT netlist_net_t::as_logic()
12641264{
1265   nl_assert(family() == LOGIC);
1265   assert(family() == LOGIC);
12661266   return static_cast<netlist_logic_net_t &>(*this);
12671267}
12681268
12691269ATTR_HOT inline const netlist_logic_net_t & RESTRICT netlist_net_t::as_logic() const
12701270{
1271    nl_assert(family() == LOGIC);
1271   assert(family() == LOGIC);
12721272   return static_cast<const netlist_logic_net_t &>(*this);
12731273}
12741274
12751275ATTR_HOT inline netlist_analog_net_t & RESTRICT netlist_net_t::as_analog()
12761276{
1277    nl_assert(family() == ANALOG);
1277   assert(family() == ANALOG);
12781278   return static_cast<netlist_analog_net_t &>(*this);
12791279}
12801280
12811281ATTR_HOT inline const netlist_analog_net_t & RESTRICT netlist_net_t::as_analog() const
12821282{
1283   nl_assert(family() == ANALOG);
1283   assert(family() == ANALOG);
12841284   return static_cast<const netlist_analog_net_t &>(*this);
12851285}
12861286
r242959r242960
13701370   }
13711371}
13721372
1373
1374// -----------------------------------------------------------------------------
1375// net_dev class factory
1376// -----------------------------------------------------------------------------
1377
1378class net_device_t_base_factory
1379{
1380   NETLIST_PREVENT_COPYING(net_device_t_base_factory)
1381public:
1382   ATTR_COLD net_device_t_base_factory(const pstring &name, const pstring &classname,
1383         const pstring &def_param)
1384   : m_name(name), m_classname(classname), m_def_param(def_param)
1385   {}
1386
1387   ATTR_COLD virtual ~net_device_t_base_factory() {}
1388
1389   ATTR_COLD virtual netlist_device_t *Create() const = 0;
1390
1391   ATTR_COLD const pstring &name() const { return m_name; }
1392   ATTR_COLD const pstring &classname() const { return m_classname; }
1393   ATTR_COLD const pstring &param_desc() const { return m_def_param; }
1394   ATTR_COLD const nl_util::pstring_list term_param_list();
1395   ATTR_COLD const nl_util::pstring_list def_params();
1396
1397protected:
1398   pstring m_name;                             /* device name */
1399   pstring m_classname;                        /* device class name */
1400   pstring m_def_param;                        /* default parameter */
1401};
1402
1403template <class C>
1404class net_device_t_factory : public net_device_t_base_factory
1405{
1406   NETLIST_PREVENT_COPYING(net_device_t_factory)
1407public:
1408   ATTR_COLD net_device_t_factory(const pstring &name, const pstring &classname,
1409         const pstring &def_param)
1410   : net_device_t_base_factory(name, classname, def_param) { }
1411
1412   ATTR_COLD netlist_device_t *Create() const
1413   {
1414      netlist_device_t *r = new C();
1415      //r->init(setup, name);
1416      return r;
1417   }
1418};
1419
1420class netlist_factory_t
1421{
1422public:
1423   typedef plinearlist_t<net_device_t_base_factory *> list_t;
1424
1425   ATTR_COLD netlist_factory_t();
1426   ATTR_COLD ~netlist_factory_t();
1427
1428   ATTR_COLD void initialize();
1429
1430   template<class _C>
1431   ATTR_COLD void register_device(const pstring &name, const pstring &classname,
1432         const pstring &def_param)
1433   {
1434      m_list.add(new net_device_t_factory< _C >(name, classname, def_param) );
1435   }
1436
1437   ATTR_COLD netlist_device_t *new_device_by_classname(const pstring &classname, netlist_setup_t &setup) const;
1438   ATTR_COLD netlist_device_t *new_device_by_name(const pstring &name, netlist_setup_t &setup) const;
1439   ATTR_COLD net_device_t_base_factory * factory_by_name(const pstring &name, netlist_setup_t &setup) const;
1440
1441   const list_t &list() { return m_list; }
1442
1443private:
1444   list_t m_list;
1445
1446};
1447
1448
13731449#endif /* NLBASE_H_ */
trunk/src/emu/netlist/nl_config.h
r242959r242960
1010
1111/* FIXME: at some time, make it compile on it's own */
1212
13#include "osdcore.h"
14#include "corealloc.h"
15#include <math.h>
16#include <exception>
17#include <typeinfo>
13#include "emu.h"
1814
1915//============================================================
2016//  SETUP
r242959r242960
106102#define end_timing(v)           do { } while (0)
107103#endif
108104
109// this macro passes an item followed by a string version of itself as two consecutive parameters
110#define NLNAME(x) x, #x
111105
112106//============================================================
113//  Exceptions
114//============================================================
115
116// emu_fatalerror is a generic fatal exception that provides an error string
117class nl_fatalerror : public std::exception
118{
119public:
120    nl_fatalerror(const char *format, ...) ATTR_PRINTF(2,3)
121    {
122        char text[1024];
123        va_list ap;
124        va_start(ap, format);
125        vsprintf(text, format, ap);
126        va_end(ap);
127        osd_printf_error("%s\n", text);
128    }
129    nl_fatalerror(const char *format, va_list ap)
130    {
131        char text[1024];
132        vsprintf(text, format, ap);
133        osd_printf_error("%s\n", text);
134    }
135};
136
137//============================================================
138//  Memory allocation
139//============================================================
140
141#define nl_alloc(T, ...)        global_alloc(T(__VA_ARGS__))
142#define nl_alloc_array(T, N)    global_alloc_array(T, N)
143
144#define nl_free(_ptr)           global_free(_ptr)
145#define nl_free_array(_ptr)     global_free_array(_ptr)
146
147
148//============================================================
149//  Asserts
150//============================================================
151
152#ifdef MAME_DEBUG
153#define nl_assert(x)               do { if (!(x)) throw nl_fatalerror("assert: %s:%d: %s", __FILE__, __LINE__, #x); } while (0)
154#define nl_assert_always(x, msg)   do { if (!(x)) throw nl_fatalerror("Fatal error: %s\nCaused by assert: %s:%d: %s", msg, __FILE__, __LINE__, #x); } while (0)
155#else
156#define nl_assert(x)               do { } while (0)
157//#define assert_always(x, msg)   do { if (!(x)) throw emu_fatalerror("Fatal error: %s (%s:%d)", msg, __FILE__, __LINE__); } while (0)
158#define nl_assert_always(x, msg)   do { } while (0)
159#endif
160
161//============================================================
162107//  Compiling standalone
163108//============================================================
164109
165110// Compiling without mame ?
166111
167112#ifndef ATTR_HOT
168#warning ATTR_HOT not defined
113//#warning ATTR_HOT not defined
169114
170115// standard C includes
171116#include <math.h>
r242959r242960
187132#define UNEXPECTED
188133#define ATTR_UNUSED             __attribute__((__unused__))
189134
135// this macro passes an item followed by a string version of itself as two consecutive parameters
136#define NAME(x) x, #x
137
190138/* 8-bit values */
191139typedef unsigned char                       UINT8;
192140typedef signed char                         INT8;
r242959r242960
212160#endif
213161#endif
214162
163#ifdef MAME_DEBUG
164#define assert(x)               do { if (!(x)) throw emu_fatalerror("assert: %s:%d: %s", __FILE__, __LINE__, #x); } while (0)
165#define assert_always(x, msg)   do { if (!(x)) throw emu_fatalerror("Fatal error: %s\nCaused by assert: %s:%d: %s", msg, __FILE__, __LINE__, #x); } while (0)
166#else
167#define assert(x)               do { } while (0)
168//#define assert_always(x, msg)   do { if (!(x)) throw emu_fatalerror("Fatal error: %s (%s:%d)", msg, __FILE__, __LINE__); } while (0)
169#define assert_always(x, msg)   do { } while (0)
170#endif
171
215172/* U64 and S64 are used to wrap long integer constants. */
216173#if defined(__GNUC__) || defined(_MSC_VER)
217174#define U64(val) val##ULL
trunk/src/emu/netlist/nl_dice_compat.h
r242959r242960
1313 * -------------------------------------------------------------------- */
1414
1515//#define CHIP(_n, _t) netlist.register_dev(NET_NEW(_t ## _dip), _n);
16#define CHIP(_n, _t) setup.register_dev( nL_alloc(nld_ ## _t ## _dip()), _n);
16#define CHIP(_n, _t) setup.register_dev( new nld_ ## _t ## _dip(), _n);
1717
1818#define CONNECTION( ... ) CONNECTIONY( CONNECTIONX( __VA_ARGS__ ) )
1919#define CONNECTIONY(_a) _a
trunk/src/emu/netlist/nl_factory.c
r242959r242960
1// license:GPL-2.0+
2// copyright-holders:Couriersud
3/***************************************************************************
4
5    nl_factory.c
6
7    Discrete netlist implementation.
8
9****************************************************************************
10
11    Couriersud reserves the right to license the code under a less restrictive
12    license going forward.
13
14    Copyright Nicola Salmoria and the MAME team
15    All rights reserved.
16
17    Redistribution and use of this code or any derivative works are permitted
18    provided that the following conditions are met:
19
20    * Redistributions may not be sold, nor may they be used in a commercial
21    product or activity.
22
23    * Redistributions that are modified from the original source must include the
24    complete source code, including the source code for all components used by a
25    binary built from the modified sources. However, as a special exception, the
26    source code distributed need not include anything that is normally distributed
27    (in either source or binary form) with the major components (compiler, kernel,
28    and so on) of the operating system on which the executable runs, unless that
29    component itself accompanies the executable.
30
31    * Redistributions must reproduce the above copyright notice, this list of
32    conditions and the following disclaimer in the documentation and/or other
33    materials provided with the distribution.
34
35    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
37    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
38    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
39    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
40    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
41    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
42    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
43    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
44    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
45    POSSIBILITY OF SUCH DAMAGE.
46
47
48****************************************************************************/
49
50#include "nl_factory.h"
51#include "nl_setup.h"
52
53netlist_factory_t::netlist_factory_t()
54{
55}
56
57netlist_factory_t::~netlist_factory_t()
58{
59   for (net_device_t_base_factory * const *e = m_list.first(); e != NULL; e = m_list.next(e))
60   {
61      net_device_t_base_factory *p = *e;
62      global_free(p);
63   }
64   m_list.clear();
65}
66
67netlist_device_t *netlist_factory_t::new_device_by_classname(const pstring &classname, netlist_setup_t &setup) const
68{
69   for (net_device_t_base_factory * const *e = m_list.first(); e != NULL; e = m_list.next(e))
70   {
71      net_device_t_base_factory *p = *e;
72      if (strcmp(p->classname(), classname) == 0)
73      {
74         netlist_device_t *ret = p->Create();
75         return ret;
76      }
77      p++;
78   }
79   setup.netlist().error("Class %s not found!\n", classname.cstr());
80   return NULL; // appease code analysis
81}
82
83netlist_device_t *netlist_factory_t::new_device_by_name(const pstring &name, netlist_setup_t &setup) const
84{
85   net_device_t_base_factory *f = factory_by_name(name, setup);
86   return f->Create();
87}
88
89net_device_t_base_factory * netlist_factory_t::factory_by_name(const pstring &name, netlist_setup_t &setup) const
90{
91   for (net_device_t_base_factory * const *e = m_list.first(); e != NULL; e = m_list.next(e))
92   {
93      net_device_t_base_factory *p = *e;
94      if (strcmp(p->name(), name) == 0)
95      {
96         return p;
97      }
98      p++;
99   }
100   setup.netlist().error("Class %s not found!\n", name.cstr());
101   return NULL; // appease code analysis
102}
trunk/src/emu/netlist/nl_factory.h
r242959r242960
1// license:GPL-2.0+
2// copyright-holders:Couriersud
3/*
4 * nl_factory.h
5 *
6 *
7 */
8
9#ifndef NLFACTORY_H_
10#define NLFACTORY_H_
11
12#include "nl_config.h"
13#include "plists.h"
14#include "nl_base.h"
15#if 0
16#include "nl_time.h"
17#include "nl_util.h"
18#include "pstate.h"
19#endif
20#include "pstring.h"
21
22// -----------------------------------------------------------------------------
23// net_dev class factory
24// -----------------------------------------------------------------------------
25
26class net_device_t_base_factory
27{
28   NETLIST_PREVENT_COPYING(net_device_t_base_factory)
29public:
30   ATTR_COLD net_device_t_base_factory(const pstring &name, const pstring &classname,
31         const pstring &def_param)
32   : m_name(name), m_classname(classname), m_def_param(def_param)
33   {}
34
35   ATTR_COLD virtual ~net_device_t_base_factory() {}
36
37   ATTR_COLD virtual netlist_device_t *Create() const = 0;
38
39   ATTR_COLD const pstring &name() const { return m_name; }
40   ATTR_COLD const pstring &classname() const { return m_classname; }
41   ATTR_COLD const pstring &param_desc() const { return m_def_param; }
42   ATTR_COLD const nl_util::pstring_list term_param_list();
43   ATTR_COLD const nl_util::pstring_list def_params();
44
45protected:
46   pstring m_name;                             /* device name */
47   pstring m_classname;                        /* device class name */
48   pstring m_def_param;                        /* default parameter */
49};
50
51template <class C>
52class net_device_t_factory : public net_device_t_base_factory
53{
54   NETLIST_PREVENT_COPYING(net_device_t_factory)
55public:
56   ATTR_COLD net_device_t_factory(const pstring &name, const pstring &classname,
57         const pstring &def_param)
58   : net_device_t_base_factory(name, classname, def_param) { }
59
60   ATTR_COLD netlist_device_t *Create() const
61   {
62      netlist_device_t *r = nl_alloc(C);
63      //r->init(setup, name);
64      return r;
65   }
66};
67
68class netlist_factory_t
69{
70public:
71   typedef plinearlist_t<net_device_t_base_factory *> list_t;
72
73   ATTR_COLD netlist_factory_t();
74   ATTR_COLD ~netlist_factory_t();
75
76   template<class _C>
77   ATTR_COLD void register_device(const pstring &name, const pstring &classname,
78         const pstring &def_param)
79   {
80      m_list.add(nl_alloc(net_device_t_factory< _C >, name, classname, def_param));
81   }
82
83   ATTR_COLD netlist_device_t *new_device_by_classname(const pstring &classname, netlist_setup_t &setup) const;
84   ATTR_COLD netlist_device_t *new_device_by_name(const pstring &name, netlist_setup_t &setup) const;
85   ATTR_COLD net_device_t_base_factory * factory_by_name(const pstring &name, netlist_setup_t &setup) const;
86
87   const list_t &list() { return m_list; }
88
89private:
90   list_t m_list;
91
92};
93
94
95#endif /* NLFACTORY_H_ */
trunk/src/emu/netlist/nl_lists.h
r242959r242960
5959      }
6060      *i = e;
6161      inc_stat(m_prof_sort);
62      nl_assert(m_end - m_list < _Size);
62      assert(m_end - m_list < _Size);
6363   }
6464
6565   ATTR_HOT inline const entry_t *pop()
trunk/src/emu/netlist/nl_setup.c
r242959r242960
1414#include "analog/nld_solver.h"
1515#include "analog/nld_twoterm.h"
1616
17//FIXME: we need a nl_getenv
18#include <stdlib.h>
19
2017static NETLIST_START(base)
2118   TTL_INPUT(ttlhigh, 1)
2219   TTL_INPUT(ttllow, 0)
r242959r242960
4138
4239void netlist_setup_t::init()
4340{
44   nl_initialize_factory(factory());
41   m_factory.initialize();
4542   NETLIST_NAME(base)(*this);
4643}
4744
r242959r242960
381378
382379nld_base_d_to_a_proxy *netlist_setup_t::get_d_a_proxy(netlist_output_t &out)
383380{
384   nl_assert(out.isFamily(netlist_terminal_t::LOGIC));
381   assert(out.isFamily(netlist_terminal_t::LOGIC));
385382
386383   //printf("proxy for %s\n", out.name().cstr());;
387384   netlist_logic_output_t &out_cast = dynamic_cast<netlist_logic_output_t &>(out);
r242959r242960
390387   if (proxy == NULL)
391388   {
392389      // create a new one ...
393      proxy = nl_alloc(nld_d_to_a_proxy ,out);
390      proxy = new nld_d_to_a_proxy(out);
394391      pstring x = pstring::sprintf("proxy_da_%s_%d", out.name().cstr(), m_proxy_cnt);
395392      m_proxy_cnt++;
396393
r242959r242960
419416{
420417   if (out.isFamily(netlist_terminal_t::ANALOG) && in.isFamily(netlist_terminal_t::LOGIC))
421418   {
422      nld_a_to_d_proxy *proxy = nl_alloc(nld_a_to_d_proxy, in);
419      nld_a_to_d_proxy *proxy = new nld_a_to_d_proxy(in);
423420      pstring x = pstring::sprintf("proxy_ad_%s_%d", in.name().cstr(), m_proxy_cnt);
424421      m_proxy_cnt++;
425422
r242959r242960
455452   else if (inp.isFamily(netlist_terminal_t::LOGIC))
456453   {
457454      NL_VERBOSE_OUT(("connect_terminal_input: connecting proxy\n"));
458      nld_a_to_d_proxy *proxy = nl_alloc(nld_a_to_d_proxy, inp);
455      nld_a_to_d_proxy *proxy = new nld_a_to_d_proxy(inp);
459456      pstring x = pstring::sprintf("proxy_ad_%s_%d", inp.name().cstr(), m_proxy_cnt);
460457      m_proxy_cnt++;
461458
r242959r242960
502499
503500void netlist_setup_t::connect_terminals(netlist_core_terminal_t &t1, netlist_core_terminal_t &t2)
504501{
505   //nl_assert(in.isType(netlist_terminal_t::TERMINAL));
506   //nl_assert(out.isType(netlist_terminal_t::TERMINAL));
502   //assert(in.isType(netlist_terminal_t::TERMINAL));
503   //assert(out.isType(netlist_terminal_t::TERMINAL));
507504
508505   if (t1.has_net() && t2.has_net())
509506   {
r242959r242960
523520   else
524521   {
525522      NL_VERBOSE_OUT(("adding net ...\n"));
526      netlist_analog_net_t *anet =  nl_alloc(netlist_analog_net_t);
523      netlist_analog_net_t *anet =  new netlist_analog_net_t();
527524      t1.set_net(*anet);
528525      //m_netlist.solver()->m_nets.add(anet);
529526      // FIXME: Nets should have a unique name
r242959r242960
686683
687684void netlist_setup_t::start_devices()
688685{
689    //FIXME: we need a nl_getenv
690686   if (getenv("NL_LOGS"))
691687   {
692688      NL_VERBOSE_OUT(("Creating dynamic logs ...\n"));
trunk/src/emu/netlist/nl_setup.h
r242959r242960
1111#define NLSETUP_H_
1212
1313#include "nl_base.h"
14#include "nl_factory.h"
1514
1615//============================================================
1716//  MACROS / inline netlist definitions
trunk/src/emu/netlist/plists.h
r242959r242960
2828      if (m_num_elements == 0)
2929         m_list = NULL;
3030      else
31         m_list = nl_alloc_array(_ListClass, m_num_elements);
31         m_list = new _ListClass[m_num_elements];
3232      m_count = 0;
3333   }
3434
r242959r242960
3838      if (m_num_elements == 0)
3939         m_list = NULL;
4040      else
41         m_list = nl_alloc_array(_ListClass, m_num_elements);
41         m_list = new _ListClass[m_num_elements];
4242      m_count = 0;
4343      for (int i=0; i<rhs.count(); i++)
4444      {
r242959r242960
6060   ATTR_COLD ~plinearlist_t()
6161   {
6262      if (m_list != NULL)
63          nl_free_array(m_list);
63         delete[] m_list;
6464      m_list = NULL;
6565   }
6666
r242959r242960
108108
109109   ATTR_HOT inline void remove_at(const int pos)
110110   {
111      nl_assert((pos>=0) && (pos<m_count));
111      assert((pos>=0) && (pos<m_count));
112112      m_count--;
113113      for (int i = pos; i < m_count; i++)
114114      {
r242959r242960
118118
119119   ATTR_HOT inline void swap(const int pos1, const int pos2)
120120   {
121      nl_assert((pos1>=0) && (pos1<m_count));
122      nl_assert((pos2>=0) && (pos2<m_count));
121      assert((pos1>=0) && (pos1<m_count));
122      assert((pos2>=0) && (pos2<m_count));
123123      _ListClass tmp = m_list[pos1];
124124      m_list[pos1] = m_list[pos2];
125125      m_list[pos2] =tmp;
r242959r242960
157157   {
158158      for (_ListClass *i = m_list; i < m_list + m_count; i++)
159159      {
160         nl_free(*i);
160         delete *i;
161161      }
162162      clear();
163163   }
164164
165165private:
166   ATTR_COLD void resize(const int new_size)
166   ATTR_HOT inline void resize(const int new_size)
167167   {
168168      int cnt = count();
169169      if (new_size > 0)
170170      {
171         _ListClass *m_new = nl_alloc_array(_ListClass, new_size);
171         _ListClass *m_new = new _ListClass[new_size];
172172         _ListClass *pd = m_new;
173173
174174         if (cnt > new_size)
r242959r242960
176176         for (_ListClass *ps = m_list; ps < m_list + cnt; ps++, pd++)
177177            *pd = *ps;
178178         if (m_list != NULL)
179            nl_free_array(m_list);
179            delete[] m_list;
180180         m_list = m_new;
181181         m_count = cnt;
182182      }
183183      else
184184      {
185185         if (m_list != NULL)
186             nl_free_array(m_list);
186            delete[] m_list;
187187         m_list = NULL;
188188         m_count = 0;
189189      }
r242959r242960
331331            }
332332            p = p->m_next;
333333         }
334         nl_assert_always(false, "element not found");
334         assert_always(false, "element not found");
335335      }
336336   }
337337
r242959r242960
357357      _ListClass **p = &m_head;
358358      while (*p != &elem)
359359      {
360         nl_assert(*p != NULL);
360         assert(*p != NULL);
361361         p = &((*p)->m_next);
362362      }
363363      (*p) = elem.m_next;
trunk/src/emu/netlist/pstate.c
r242959r242960
2727   };
2828
2929   NL_VERBOSE_OUT(("SAVE: <%s> %s(%d) %p\n", fullname.cstr(), ts[dt].cstr(), size, ptr));
30   pstate_entry_t *p = nl_alloc(pstate_entry_t, stname, dt, owner, size, count, ptr, is_ptr);
30   pstate_entry_t *p = new pstate_entry_t(stname, dt, owner, size, count, ptr, is_ptr);
3131   m_save.add(p);
3232}
3333
r242959r242960
6060      if (m_save[i]->m_dt == DT_CUSTOM)
6161         m_save[i]->m_callback->on_post_load();
6262}
63
64template<> ATTR_COLD void pstate_manager_t::save_item(pstate_callback_t &state, const void *owner, const pstring &stname)
65{
66    //save_state_ptr(stname, DT_CUSTOM, 0, 1, &state);
67    pstate_entry_t *p = nl_alloc(pstate_entry_t, stname, owner, &state);
68    m_save.add(p);
69    state.register_state(*this, stname);
70}
trunk/src/emu/netlist/pstate.h
r242959r242960
145145   pstate_entry_t::list_t m_save;
146146};
147147
148template<> ATTR_COLD void pstate_manager_t::save_item(pstate_callback_t &state, const void *owner, const pstring &stname);
148template<> ATTR_COLD inline void pstate_manager_t::save_item(pstate_callback_t &state, const void *owner, const pstring &stname)
149{
150   //save_state_ptr(stname, DT_CUSTOM, 0, 1, &state);
151   pstate_entry_t *p = new pstate_entry_t(stname, owner, &state);
152   m_save.add(p);
153   state.register_state(*this, stname);
154}
149155
150156template<> ATTR_COLD inline void pstate_manager_t::save_item(netlist_time &nlt, const void *owner, const pstring &stname)
151157{
trunk/src/emu/netlist/pstring.c
r242959r242960
55
66#include "pstring.h"
77#include <cstdio>
8#include <stdlib.h>
98
109
1110// The following will work on linux, however not on Windows ....
r242959r242960
1413//pstring::str_t *pstring::m_zero = new(pstring::m_pool, 0) pstring::str_t(0);
1514
1615pblockpool pstring::m_pool;
16
1717pstring::str_t pstring::m_zero;
1818
1919/*
trunk/src/emu/render.h
r242959r242960
4646#ifndef __RENDER_H__
4747#define __RENDER_H__
4848
49//#include "osdepend.h"
49#include "osdepend.h"
5050
5151#include <math.h>
5252
trunk/src/emu/rendfont.c
r242959r242960
1414#include "emuopts.h"
1515#include <zlib.h>
1616
17#include "osdepend.h"
1817#include "uismall.fh"
1918
2019
trunk/src/emu/rendfont.h
r242959r242960
1313
1414#include "render.h"
1515
16// forward instead of include
17class osd_font;
1816
1917//**************************************************************************
2018//  TYPE DEFINITIONS
r242959r242960
9391   dynamic_array<glyph> m_glyphs[256];     // array of glyph subtables
9492   dynamic_array<char> m_rawdata;          // pointer to the raw data for the font
9593   UINT64              m_rawsize;          // size of the raw font data
96   osd_font            *m_osdfont;          // handle to the OSD font
94   osd_font            m_osdfont;          // handle to the OSD font
9795
9896   // constants
9997   static const int CACHED_CHAR_SIZE       = 12;
trunk/src/emu/rendutil.h
r242959r242960
1212#ifndef __RENDUTIL_H__
1313#define __RENDUTIL_H__
1414
15#include "osdepend.h"
1516#include "render.h"
1617
1718#include <math.h>
trunk/src/emu/sound/qs1000.c
r242959r242960
244244
245245   m_cpu->i8051_set_serial_rx_callback(read8_delegate(FUNC(qs1000_device::data_to_i8052),this));
246246
247   save_item(NAME(m_serial_data_in));
248   save_item(NAME(m_wave_regs));
249   
250   for (int i = 0; i < QS1000_CHANNELS; i++)
251   {
252      save_item(NAME(m_channels[i].m_acc), i);
253      save_item(NAME(m_channels[i].m_adpcm_signal), i);
254      save_item(NAME(m_channels[i].m_start), i);
255      save_item(NAME(m_channels[i].m_addr), i);
256      save_item(NAME(m_channels[i].m_adpcm_addr), i);
257      save_item(NAME(m_channels[i].m_loop_start), i);
258      save_item(NAME(m_channels[i].m_loop_end), i);
259      save_item(NAME(m_channels[i].m_freq), i);
260      save_item(NAME(m_channels[i].m_flags), i);
261      save_item(NAME(m_channels[i].m_regs), i);
262      save_item(NAME(m_channels[i].m_adpcm.m_signal), i);
263      save_item(NAME(m_channels[i].m_adpcm.m_step), i);
264   }
247   // TODO: register state for saving
265248}
266249
267250
trunk/src/emu/sound/tiaintf.c
r242959r242960
3030void tia_device::device_start()
3131{
3232   m_channel = stream_alloc(0, 1, clock());
33   m_chip = tia_sound_init(this, clock(), clock(), 16);
33   m_chip = tia_sound_init(clock(), clock(), 16);
3434   assert_always(m_chip != NULL, "Error creating TIA chip");
3535}
3636
trunk/src/emu/sound/tiasound.c
r242959r242960
526526   }
527527}
528528
529static void tia_save_state(device_t *device, tia *tia)
530{
531   device->save_item(NAME(tia->AUDC));
532   device->save_item(NAME(tia->AUDF));
533   device->save_item(NAME(tia->AUDV));
534   device->save_item(NAME(tia->Outvol));
535   device->save_item(NAME(tia->P4));
536   device->save_item(NAME(tia->P5));
537   device->save_item(NAME(tia->P9));
538   device->save_item(NAME(tia->Div_n_cnt));
539   device->save_item(NAME(tia->Div_n_max));
540   device->save_item(NAME(tia->Div_3_cnt));
541   device->save_item(NAME(tia->Samp_n_cnt));
542   device->save_item(NAME(tia->oversampling));
543}
544
545529/*****************************************************************************/
546530/* Module:  tia_sh_start()                                                   */
547531/* Purpose: to handle the power-up initialization functions                  */
r242959r242960
557541/*                                                                           */
558542/*****************************************************************************/
559543
560void *tia_sound_init(device_t *device, int clock, int sample_rate, int gain)
544void *tia_sound_init(int clock, int sample_rate, int gain)
561545{
562546   struct tia *chip;
563547   int chan;
r242959r242960
597581      chip->P5[chan] = 0;
598582      chip->P9[chan] = 0;
599583   }
600   
601   tia_save_state(device, chip);
602584
603585   return chip;
604586}
trunk/src/emu/sound/tiasound.h
r242959r242960
3737#ifndef __TIASOUND_H__
3838#define __TIASOUND_H__
3939
40void *tia_sound_init(device_t *device, int clock, int sample_rate, int gain);
40void *tia_sound_init(int clock, int sample_rate, int gain);
4141void tia_sound_free(void *chip);
4242void tia_process (void *chip, stream_sample_t *buffer, int length);
4343void tia_write(void *chip, offs_t offset, UINT8 data);
trunk/src/emu/ui/barcode.c
r242959r242960
5656      const char *new_barcode;
5757
5858      // selected device
59      item_append(current_display_name(), "", current_display_flags(), ITEMREF_SELECT_READER);
59      item_append(current_display_name().cstr(), "", current_display_flags(), ITEMREF_SELECT_READER);
6060
6161      // append the "New Barcode" item
6262      if (get_selection() == ITEMREF_NEW_BARCODE)
trunk/src/emu/ui/devopt.c
r242959r242960
1/*********************************************************************
2
3    ui/devopt.c
4
5    Internal menu for the device configuration.
6
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10*********************************************************************/
11
12#include "emu.h"
13#include "ui/ui.h"
14#include "ui/devopt.h"
15
16/*-------------------------------------------------
17 ui_device_config - handle the game information
18 menu
19 -------------------------------------------------*/
20
21ui_menu_device_config::ui_menu_device_config(running_machine &machine, render_container *container, device_slot_interface *slot, device_slot_option *option) : ui_menu(machine, container)
22{
23   astring tmp_tag;
24   tmp_tag.cpy(slot->device().tag()).cat(":").cat(option->name());
25   m_option = option;
26   m_owner = slot;
27   m_mounted = false;
28
29   device_iterator deviter(machine.config().root_device());
30   for (device_t *device = deviter.first(); device != NULL; device = deviter.next())
31   {
32      if (strcmp(device->tag(), tmp_tag.cstr()) == 0)
33      {
34         m_mounted = true;
35         break;
36      }
37   }
38}
39
40void ui_menu_device_config::populate()
41{
42   astring string;
43   device_t *dev;
44
45   string.printf("[This option is%s currently mounted in the running system]\n\n", m_mounted ? "" : " NOT");
46   string.catprintf("Option: %s\n", m_option->name());
47
48   dev = const_cast<machine_config &>(machine().config()).device_add(&machine().config().root_device(), m_option->name(), m_option->devtype(), 0);
49     
50   string.catprintf("Device: %s\n", dev->name());
51   if (!m_mounted)
52      string.cat("\nIf you select this option, the following items will be enabled:\n");
53   else
54      string.cat("\nThe selected option enables the following items:\n");
55
56   // loop over all CPUs
57   execute_interface_iterator execiter(*dev);
58   if (execiter.count() > 0)
59   {
60      string.cat("* CPU:\n");
61      tagmap_t<UINT8> exectags;
62      for (device_execute_interface *exec = execiter.first(); exec != NULL; exec = execiter.next())
63      {
64         if (exectags.add(exec->device().tag(), 1, FALSE) == TMERR_DUPLICATE)
65            continue;
66
67         // get cpu specific clock that takes internal multiplier/dividers into account
68         int clock = exec->device().clock();
69         
70         // count how many identical CPUs we have
71         int count = 1;
72         const char *name = exec->device().name();
73         execute_interface_iterator execinneriter(*dev);
74         for (device_execute_interface *scan = execinneriter.first(); scan != NULL; scan = execinneriter.next())
75         {
76            if (exec->device().type() == scan->device().type() && strcmp(name, scan->device().name()) == 0 && exec->device().clock() == scan->device().clock())
77               if (exectags.add(scan->device().tag(), 1, FALSE) != TMERR_DUPLICATE)
78                  count++;
79         }
80         
81         // if more than one, prepend a #x in front of the CPU name
82         if (count > 1)
83            string.catprintf("  %d" UTF8_MULTIPLY, count);
84         else
85            string.cat("  ");
86         string.cat(name);
87         
88         // display clock in kHz or MHz
89         if (clock >= 1000000)
90            string.catprintf(" %d.%06d" UTF8_NBSP "MHz\n", clock / 1000000, clock % 1000000);
91         else
92            string.catprintf(" %d.%03d" UTF8_NBSP "kHz\n", clock / 1000, clock % 1000);
93      }
94   }
95   
96   // display screen information
97   screen_device_iterator scriter(*dev);
98   if (scriter.count() > 0)
99   {
100      string.cat("* Video:\n");
101      for (screen_device *screen = scriter.first(); screen != NULL; screen = scriter.next())
102      {
103         string.catprintf("  Screen '%s': ", screen->tag());
104         
105         if (screen->screen_type() == SCREEN_TYPE_VECTOR)
106            string.cat("Vector\n");
107         else
108         {
109            const rectangle &visarea = screen->visible_area();
110           
111            string.catprintf("%d " UTF8_MULTIPLY " %d (%s) %f" UTF8_NBSP "Hz\n",
112                         visarea.width(), visarea.height(),
113                         (machine().system().flags & ORIENTATION_SWAP_XY) ? "V" : "H",
114                         ATTOSECONDS_TO_HZ(screen->frame_period().attoseconds));
115         }
116      }
117   }
118   
119   // loop over all sound chips
120   sound_interface_iterator snditer(*dev);
121   if (snditer.count() > 0)
122   {
123      string.cat("* Sound:\n");
124      tagmap_t<UINT8> soundtags;
125      for (device_sound_interface *sound = snditer.first(); sound != NULL; sound = snditer.next())
126      {
127         if (soundtags.add(sound->device().tag(), 1, FALSE) == TMERR_DUPLICATE)
128            continue;
129         
130         // count how many identical sound chips we have
131         int count = 1;
132         sound_interface_iterator sndinneriter(*dev);
133         for (device_sound_interface *scan = sndinneriter.first(); scan != NULL; scan = sndinneriter.next())
134         {
135            if (sound->device().type() == scan->device().type() && sound->device().clock() == scan->device().clock())
136               if (soundtags.add(scan->device().tag(), 1, FALSE) != TMERR_DUPLICATE)
137                  count++;
138         }
139         // if more than one, prepend a #x in front of the CPU name
140         if (count > 1)
141            string.catprintf("  %d" UTF8_MULTIPLY, count);
142         else
143            string.cat("  ");
144         string.cat(sound->device().name());
145         
146         // display clock in kHz or MHz
147         int clock = sound->device().clock();
148         if (clock >= 1000000)
149            string.catprintf(" %d.%06d" UTF8_NBSP "MHz\n", clock / 1000000, clock % 1000000);
150         else if (clock != 0)
151            string.catprintf(" %d.%03d" UTF8_NBSP "kHz\n", clock / 1000, clock % 1000);
152         else
153            string.cat("\n");
154      }
155   }
156   
157   int input = 0, input_mj = 0, input_hana = 0, input_gamble = 0, input_analog = 0, input_adjust = 0;
158   int dips = 0, confs = 0;
159   astring errors, dips_opt, confs_opt;
160   ioport_list portlist;
161   device_iterator iptiter(*dev);
162   for (device_t *iptdev = iptiter.first(); iptdev != NULL; iptdev = iptiter.next())
163      portlist.append(*iptdev, errors);
164
165   // check if the device adds inputs to the system
166   for (ioport_port *port = portlist.first(); port != NULL; port = port->next())
167      for (ioport_field *field = port->first_field(); field != NULL; field = field->next())
168      {
169         if (field->type() >= IPT_MAHJONG_FIRST && field->type() < IPT_MAHJONG_LAST)
170            input_mj++;
171         else if (field->type() >= IPT_HANAFUDA_FIRST && field->type() < IPT_HANAFUDA_LAST)
172            input_hana++;
173         else if (field->type() >= IPT_GAMBLING_FIRST && field->type() < IPT_GAMBLING_LAST)
174            input_gamble++;
175         else if (field->type() >= IPT_ANALOG_FIRST && field->type() < IPT_ANALOG_LAST)
176            input_analog++;
177         else if (field->type() == IPT_ADJUSTER)
178            input_adjust++;
179         else if (field->type() >= IPT_START1 && field->type() < IPT_UI_FIRST)
180            input++;
181         else if (field->type() == IPT_DIPSWITCH)
182         {
183            dips++;
184            dips_opt.cat("  ").cat(field->name());
185            for (ioport_setting *setting = field->first_setting(); setting != NULL; setting = setting->next())
186            {
187               if (setting->value() == field->defvalue())
188               {
189                  dips_opt.catprintf("    [default: %s]\n", setting->name());
190                  break;
191               }
192            }
193         }
194         else if (field->type() == IPT_CONFIG)
195         {
196            confs++;
197            confs_opt.cat("  ").cat(field->name());
198            for (ioport_setting *setting = field->first_setting(); setting != NULL; setting = setting->next())
199            {
200               if (setting->value() == field->defvalue())
201               {
202                  confs_opt.catprintf("    [default: %s]\n", setting->name());
203                  break;
204               }
205            }
206         }
207      }
208
209   if (dips)
210      string.cat("* Dispwitch settings:\n").cat(dips_opt);
211   if (confs)
212      string.cat("* Configuration settings:\n").cat(confs_opt);
213   if (input + input_mj + input_hana + input_gamble + input_analog + input_adjust)
214      string.cat("* Input device(s):\n");
215   if (input)
216      string.catprintf("  Player inputs    [%d inputs]\n", input);
217   if (input_mj)
218      string.catprintf("  Mahjong inputs    [%d inputs]\n", input_mj);
219   if (input_hana)
220      string.catprintf("  Hanafuda inputs    [%d inputs]\n", input_hana);
221   if (input_gamble)
222      string.catprintf("  Gambling inputs    [%d inputs]\n", input_gamble);
223   if (input_analog)
224      string.catprintf("  Analog inputs    [%d inputs]\n", input_analog);
225   if (input_adjust)
226      string.catprintf("  Adjuster inputs    [%d inputs]\n", input_adjust);
227
228   image_interface_iterator imgiter(*dev);
229   if (imgiter.count() > 0)
230   {
231      string.cat("* Media Options:\n");
232      for (const device_image_interface *imagedev = imgiter.first(); imagedev != NULL; imagedev = imgiter.next())
233         string.catprintf("  %s    [tag: %s]\n", imagedev->image_type_name(), imagedev->device().tag());
234   }
235   
236   slot_interface_iterator slotiter(*dev);
237   if (slotiter.count() > 0)
238   {
239      string.cat("* Slot Options:\n");
240      for (const device_slot_interface *slot = slotiter.first(); slot != NULL; slot = slotiter.next())
241         string.catprintf("  %s    [default: %s]\n", slot->device().tag(), slot->default_option() ? slot->default_option() : "----");
242   }
243
244   if ((execiter.count() + scriter.count() + snditer.count() + imgiter.count() + slotiter.count() + input + input_mj + input_hana + input_gamble + input_analog + input_adjust) == 0)
245      string.cat("[None]\n");
246
247   const_cast<machine_config &>(machine().config()).device_remove(&machine().config().root_device(), m_option->name());
248   item_append(string, NULL, MENU_FLAG_MULTILINE, NULL);
249}
250
251void ui_menu_device_config::handle()
252{
253   /* process the menu */
254   process(0);
255}
256
257ui_menu_device_config::~ui_menu_device_config()
258{
259}
trunk/src/emu/ui/devopt.h
r242959r242960
1/***************************************************************************
2
3    ui/devopt.h
4 
5    Internal menu for the device configuration.
6 
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10***************************************************************************/
11
12#pragma once
13
14#ifndef __UI_DEVOPT_H__
15#define __UI_DEVOPT_H__
16
17class ui_menu_device_config : public ui_menu {
18public:
19   ui_menu_device_config(running_machine &machine, render_container *container, device_slot_interface *slot, device_slot_option *option);
20   virtual ~ui_menu_device_config();
21   virtual void populate();
22   virtual void handle();
23
24private:
25   device_slot_interface *m_owner;
26   device_slot_option *m_option;
27   bool m_mounted;
28};
29
30
31#endif  /* __UI_DEVOPT_H__ */
trunk/src/emu/ui/filemngr.c
r242959r242960
5959}
6060
6161
62void ui_menu_file_manager::fill_image_line(device_image_interface *img, astring &instance, astring &filename)
63{
64   // get the image type/id
65   instance.printf("%s (%s)", img->instance_name(), img->brief_instance_name());
66   
67   // get the base name
68   if (img->basename() != NULL)
69   {
70      filename.cpy(img->basename());
71     
72      // if the image has been loaded through softlist, also show the loaded part
73      if (img->part_entry() != NULL)
74      {
75         const software_part *tmp = img->part_entry();
76         if (tmp->name() != NULL)
77         {
78            filename.cat(" (");
79            filename.cat(tmp->name());
80            // also check if this part has a specific part_id (e.g. "Map Disc", "Bonus Disc", etc.), and in case display it
81            if (img->get_feature("part_id") != NULL)
82            {
83               filename.cat(": ");
84               filename.cat(img->get_feature("part_id"));
85            }
86            filename.cat(")");
87         }
88      }
89   }
90   else
91      filename.cpy("---");
92}
93
9462//-------------------------------------------------
9563//  populate
9664//-------------------------------------------------
9765
9866void ui_menu_file_manager::populate()
9967{
100   astring buffer, tmp_inst, tmp_name;
101   bool first_entry = true;
102   astring prev_owner;
68   astring buffer;
69   astring tmp_name;
10370
10471   // cycle through all devices for this system
105   device_iterator iter(machine().root_device());
106   tagmap_t<UINT8> devtags;
107   for (device_t *dev = iter.first(); dev != NULL; dev = iter.next())
72   image_interface_iterator iter(machine().root_device());
73   for (device_image_interface *image = iter.first(); image != NULL; image = iter.next())
10874   {
109      bool tag_appended = false;
110      if (devtags.add(dev->tag(), 1, FALSE) == TMERR_DUPLICATE)
111         continue;
75      // get the image type/id
76      buffer.printf(
77         "%s (%s)",
78         image->device().name(), image->brief_instance_name());
11279
113      // check whether it owns an image interface
114      image_interface_iterator subiter(*dev);
115      if (subiter.count() > 0)
116      {         
117         // if so, cycle through all its image interfaces
118         image_interface_iterator subiter(*dev);
119         for (device_image_interface *scan = subiter.first(); scan != NULL; scan = subiter.next())
80      // get the base name
81      if (image->basename() != NULL)
82      {
83         tmp_name.cpy(image->basename());
84
85         // if the image has been loaded through softlist, also show the loaded part
86         if (image->part_entry() != NULL)
12087         {
121            // if it is a children device, and not something further down the device tree, we want it in the menu!
122            if (strcmp(scan->device().owner()->tag(), dev->tag()) == 0)
123               if (devtags.add(scan->device().tag(), 1, FALSE) != TMERR_DUPLICATE)
88            const software_part *tmp = image->part_entry();
89            if (tmp->name() != NULL)
90            {
91               tmp_name.cat(" (");
92               tmp_name.cat(tmp->name());
93               // also check if this part has a specific part_id (e.g. "Map Disc", "Bonus Disc", etc.), and in case display it
94               if (image->get_feature("part_id") != NULL)
12495               {
125                  // check whether we already had some devices with the same owner: if not, output the owner tag!
126                  if (!tag_appended)
127                  {
128                     if (first_entry)
129                        first_entry = false;
130                     else
131                        item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
132                     buffer.printf("[root%s]", dev->tag());
133                     item_append(buffer, NULL, 0, NULL);
134                     tag_appended = true;
135                  }
136                  // finally, append the image interface to the menu
137                  fill_image_line(scan, tmp_inst, tmp_name);
138                  item_append(tmp_inst, tmp_name, 0, (void *) scan);
96                  tmp_name.cat(": ");
97                  tmp_name.cat(image->get_feature("part_id"));
13998               }
99               tmp_name.cat(")");
100            }
140101         }
141102      }
103      else
104         tmp_name.cpy("---");
105
106      // record the menu item
107      item_append(buffer, tmp_name.cstr(), 0, (void *) image);
142108   }
143109   item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
144110   item_append("Reset",  NULL, 0, (void *)1);
trunk/src/emu/ui/filemngr.h
r242959r242960
2525   virtual void populate();
2626   virtual void handle();
2727   virtual void custom_render(void *selectedref, float top, float bottom, float x, float y, float x2, float y2);
28
29   void fill_image_line(device_image_interface *img, astring &instance, astring &filename);
3028};
3129
3230#endif  /* __UI_FILEMNGR_H__ */
trunk/src/emu/ui/imginfo.c
r242959r242960
4242
4343void ui_menu_image_info::populate()
4444{
45   item_append(machine().system().description, NULL, MENU_FLAG_DISABLE, NULL);
46   item_append("", NULL, MENU_FLAG_DISABLE, NULL);
47
48   image_interface_iterator iter(machine().root_device());
49   for (device_image_interface *image = iter.first(); image != NULL; image = iter.next())
50         image_info(image);
45   astring tempstring;
46   image_info_astring(machine(), tempstring);
47   item_append(tempstring, NULL, MENU_FLAG_MULTILINE, NULL);
5148}
5249
5350
r242959r242960
6360
6461
6562//-------------------------------------------------
66//  image_info - display image info for a specific
67//  image interface device
63//  stripspace
6864//-------------------------------------------------
6965
70void ui_menu_image_info::image_info(device_image_interface *image)
66static char *stripspace(const char *src)
7167{
72   if (image->exists())
68   static char buff[512];
69   if( src )
7370   {
74      // display device type and filename
75      item_append(image->brief_instance_name(), image->basename(), 0, NULL);
71      char *dst;
72      while( *src && isspace(*src) )
73         src++;
74      strcpy(buff, src);
75      dst = buff + strlen(buff);
76      while( dst >= buff && isspace(*--dst) )
77         *dst = '\0';
78      return buff;
79   }
80   return NULL;
81}
7682
77      // if image has been loaded through softlist, let's add some more info
78      if (image->software_entry())
83
84//-------------------------------------------------
85//  strip_extension
86//-------------------------------------------------
87
88static char *strip_extension(const char *filename)
89{
90   char *newname;
91   char *c;
92
93   // NULL begets NULL
94   if (!filename)
95      return NULL;
96
97   // allocate space for it
98   newname = (char *) malloc(strlen(filename) + 1);
99   if (!newname)
100      return NULL;
101
102   // copy in the name
103   strcpy(newname, filename);
104
105   // search backward for a period, failing if we hit a slash or a colon
106   for (c = newname + strlen(newname) - 1; c >= newname; c--)
107   {
108      // if we hit a period, NULL terminate and break
109      if (*c == '.')
79110      {
80         astring string;
111         *c = 0;
112         break;
113      }
81114
82         // display long filename
83         item_append(image->longname(), "", MENU_FLAG_DISABLE, NULL);
84         
85         // display manufacturer and year
86         string.catprintf("%s, %s", image->manufacturer(), image->year());
87         item_append(string, "", MENU_FLAG_DISABLE, NULL);
115      // if we hit a slash or colon just stop
116      if (*c == '\\' || *c == '/' || *c == ':')
117         break;
118   }
88119
89         // display supported information, if available
90         switch (image->supported())
120   return newname;
121}
122
123
124//-------------------------------------------------
125//  image_info_astring - populate an allocated
126//  string with the image info text
127//-------------------------------------------------
128
129void ui_menu_image_info::image_info_astring(running_machine &machine, astring &string)
130{
131   string.printf("%s\n\n", machine.system().description);
132
133#if 0
134   if (mess_ram_size > 0)
135   {
136      char buf2[RAM_STRING_BUFLEN];
137      string.catprintf("RAM: %s\n\n", ram_string(buf2, mess_ram_size));
138   }
139#endif
140
141   image_interface_iterator iter(machine.root_device());
142   for (device_image_interface *image = iter.first(); image != NULL; image = iter.next())
143   {
144      const char *name = image->filename();
145      if (name != NULL)
146      {
147         const char *base_filename;
148         const char *info;
149         char *base_filename_noextension;
150
151         base_filename = image->basename();
152         base_filename_noextension = strip_extension(base_filename);
153
154         // display device type and filename
155         string.catprintf("%s: %s\n", image->device().name(), base_filename);
156
157         // display long filename, if present and doesn't correspond to name
158         info = image->longname();
159         if (info && (!base_filename_noextension || core_stricmp(info, base_filename_noextension)))
160            string.catprintf("%s\n", info);
161
162         // display manufacturer, if available
163         info = image->manufacturer();
164         if (info != NULL)
91165         {
92            case SOFTWARE_SUPPORTED_NO:
93               item_append("Not supported", "", MENU_FLAG_DISABLE, NULL);
94               break;
95            case SOFTWARE_SUPPORTED_PARTIAL:
96               item_append("Partially supported", "", MENU_FLAG_DISABLE, NULL);
97               break;
98            default:
99               break;
166            string.catprintf("%s", info);
167            info = stripspace(image->year());
168            if (info && *info)
169               string.catprintf(", %s", info);
170            string.catprintf("\n");
100171         }
172
173         // display supported information, if available
174         switch(image->supported()) {
175            case SOFTWARE_SUPPORTED_NO : string.catprintf("Not supported\n"); break;
176            case SOFTWARE_SUPPORTED_PARTIAL : string.catprintf("Partially supported\n"); break;
177            default : break;
178         }
179
180         if (base_filename_noextension != NULL)
181            free(base_filename_noextension);
101182      }
183      else
184      {
185         string.catprintf("%s: ---\n", image->device().name());
186      }
102187   }
103   else
104      item_append(image->brief_instance_name(), "[empty]", 0, NULL);
105   item_append("", NULL, MENU_FLAG_DISABLE, NULL);
106188}
trunk/src/emu/ui/imginfo.h
r242959r242960
2323   virtual void handle();
2424
2525private:
26   void image_info(device_image_interface *image);
26   void image_info_astring(running_machine &machine, astring &string);
2727};
2828
2929#endif // __UI_IMGINFO_H__
trunk/src/emu/ui/inputmap.c
r242959r242960
1/*********************************************************************
2
3    ui/inputmap.c
4
5    Internal menus for input mappings.
6
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10*********************************************************************/
11
12#include "emu.h"
13
14#include "uiinput.h"
15#include "ui/ui.h"
16#include "ui/inputmap.h"
17
18
19/***************************************************************************
20    CONSTANTS
21***************************************************************************/
22
23#define MAX_PHYSICAL_DIPS       10
24#define MAX_INPUT_PORTS         32
25#define MAX_BITS_PER_PORT       32
26
27/* DIP switch rendering parameters */
28#define DIP_SWITCH_HEIGHT       0.05f
29#define DIP_SWITCH_SPACING      0.01
30#define SINGLE_TOGGLE_SWITCH_FIELD_WIDTH 0.025f
31#define SINGLE_TOGGLE_SWITCH_WIDTH 0.020f
32/* make the switch 80% of the width space and 1/2 of the switch height */
33#define PERCENTAGE_OF_HALF_FIELD_USED 0.80f
34#define SINGLE_TOGGLE_SWITCH_HEIGHT ((DIP_SWITCH_HEIGHT / 2) * PERCENTAGE_OF_HALF_FIELD_USED)
35
36
37
38/*-------------------------------------------------
39    menu_input_groups_populate - populate the
40    input groups menu
41-------------------------------------------------*/
42
43ui_menu_input_groups::ui_menu_input_groups(running_machine &machine, render_container *container) : ui_menu(machine, container)
44{
45}
46
47void ui_menu_input_groups::populate()
48{
49   int player;
50
51   /* build up the menu */
52   item_append("User Interface", NULL, 0, (void *)(IPG_UI + 1));
53   for (player = 0; player < MAX_PLAYERS; player++)
54   {
55      char buffer[40];
56      sprintf(buffer, "Player %d Controls", player + 1);
57      item_append(buffer, NULL, 0, (void *)(FPTR)(IPG_PLAYER1 + player + 1));
58   }
59   item_append("Other Controls", NULL, 0, (void *)(FPTR)(IPG_OTHER + 1));
60}
61
62ui_menu_input_groups::~ui_menu_input_groups()
63{
64}
65
66/*-------------------------------------------------
67    menu_input_groups - handle the input groups
68    menu
69-------------------------------------------------*/
70
71void ui_menu_input_groups::handle()
72{
73   /* process the menu */
74   const ui_menu_event *menu_event = process(0);
75   if (menu_event != NULL && menu_event->iptkey == IPT_UI_SELECT)
76      ui_menu::stack_push(auto_alloc_clear(machine(), ui_menu_input_general(machine(), container, int((long long)(menu_event->itemref)-1))));
77}
78
79
80
81/*-------------------------------------------------
82    menu_input_general - handle the general
83    input menu
84-------------------------------------------------*/
85
86ui_menu_input_general::ui_menu_input_general(running_machine &machine, render_container *container, int _group) : ui_menu_input(machine, container)
87{
88   group = _group;
89}
90
91void ui_menu_input_general::populate()
92{
93   input_item_data *itemlist = NULL;
94   int suborder[SEQ_TYPE_TOTAL];
95   astring tempstring;
96   int sortorder = 1;
97
98   /* create a mini lookup table for sort order based on sequence type */
99   suborder[SEQ_TYPE_STANDARD] = 0;
100   suborder[SEQ_TYPE_DECREMENT] = 1;
101   suborder[SEQ_TYPE_INCREMENT] = 2;
102
103   /* iterate over the input ports and add menu items */
104   for (input_type_entry *entry = machine().ioport().first_type(); entry != NULL; entry = entry->next())
105
106      /* add if we match the group and we have a valid name */
107      if (entry->group() == group && entry->name() != NULL && entry->name()[0] != 0)
108      {
109         input_seq_type seqtype;
110
111         /* loop over all sequence types */
112         sortorder++;
113         for (seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; seqtype++)
114         {
115            /* build an entry for the standard sequence */
116            input_item_data *item = (input_item_data *)m_pool_alloc(sizeof(*item));
117            memset(item, 0, sizeof(*item));
118            item->ref = entry;
119            if(pollingitem && pollingref == entry && pollingseq == seqtype)
120               pollingitem = item;
121            item->seqtype = seqtype;
122            item->seq = machine().ioport().type_seq(entry->type(), entry->player(), seqtype);
123            item->defseq = &entry->defseq(seqtype);
124            item->sortorder = sortorder * 4 + suborder[seqtype];
125            item->type = ioport_manager::type_is_analog(entry->type()) ? (INPUT_TYPE_ANALOG + seqtype) : INPUT_TYPE_DIGITAL;
126            item->name = entry->name();
127            item->owner_name = NULL;
128            item->next = itemlist;
129            itemlist = item;
130
131            /* stop after one, unless we're analog */
132            if (item->type == INPUT_TYPE_DIGITAL)
133               break;
134         }
135      }
136
137   /* sort and populate the menu in a standard fashion */
138   populate_and_sort(itemlist);
139}
140
141ui_menu_input_general::~ui_menu_input_general()
142{
143}
144
145/*-------------------------------------------------
146    menu_input_specific - handle the game-specific
147    input menu
148-------------------------------------------------*/
149
150ui_menu_input_specific::ui_menu_input_specific(running_machine &machine, render_container *container) : ui_menu_input(machine, container)
151{
152}
153
154void ui_menu_input_specific::populate()
155{
156   input_item_data *itemlist = NULL;
157   ioport_field *field;
158   ioport_port *port;
159   int suborder[SEQ_TYPE_TOTAL];
160   astring tempstring;
161
162   /* create a mini lookup table for sort order based on sequence type */
163   suborder[SEQ_TYPE_STANDARD] = 0;
164   suborder[SEQ_TYPE_DECREMENT] = 1;
165   suborder[SEQ_TYPE_INCREMENT] = 2;
166
167   /* iterate over the input ports and add menu items */
168   for (port = machine().ioport().first_port(); port != NULL; port = port->next())
169      for (field = port->first_field(); field != NULL; field = field->next())
170      {
171         const char *name = field->name();
172
173         /* add if we match the group and we have a valid name */
174         if (name != NULL && field->enabled() &&
175            ((field->type() == IPT_OTHER && field->name() != NULL) || machine().ioport().type_group(field->type(), field->player()) != IPG_INVALID))
176         {
177            input_seq_type seqtype;
178            UINT32 sortorder;
179
180            /* determine the sorting order */
181            if (field->type() >= IPT_START1 && field->type() < IPT_ANALOG_LAST)
182            {
183               sortorder = (field->type() << 2) | (field->player() << 12);
184               if (strcmp(field->device().tag(), ":"))
185                  sortorder |= 0x10000;
186            }
187            else
188               sortorder = field->type() | 0xf000;
189
190            /* loop over all sequence types */
191            for (seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; seqtype++)
192            {
193               /* build an entry for the standard sequence */
194               input_item_data *item = (input_item_data *)m_pool_alloc(sizeof(*item));
195               memset(item, 0, sizeof(*item));
196               item->ref = field;
197               item->seqtype = seqtype;
198               if(pollingitem && pollingref == field && pollingseq == seqtype)
199                  pollingitem = item;
200               item->seq = field->seq(seqtype);
201               item->defseq = &field->defseq(seqtype);
202               item->sortorder = sortorder + suborder[seqtype];
203               item->type = field->is_analog() ? (INPUT_TYPE_ANALOG + seqtype) : INPUT_TYPE_DIGITAL;
204               item->name = name;
205               item->owner_name = field->device().tag();
206               item->next = itemlist;
207               itemlist = item;
208
209               /* stop after one, unless we're analog */
210               if (item->type == INPUT_TYPE_DIGITAL)
211                  break;
212            }
213         }
214      }
215
216   /* sort and populate the menu in a standard fashion */
217   populate_and_sort(itemlist);
218}
219
220ui_menu_input_specific::~ui_menu_input_specific()
221{
222}
223
224/*-------------------------------------------------
225    menu_input - display a menu for inputs
226-------------------------------------------------*/
227ui_menu_input::ui_menu_input(running_machine &machine, render_container *container) : ui_menu(machine, container)
228{
229   pollingitem = 0;
230   pollingref = 0;
231   pollingseq = SEQ_TYPE_STANDARD;
232}
233
234ui_menu_input::~ui_menu_input()
235{
236}
237
238/*-------------------------------------------------
239    toggle_none_default - toggle between "NONE"
240    and the default item
241-------------------------------------------------*/
242
243void ui_menu_input::toggle_none_default(input_seq &selected_seq, input_seq &original_seq, const input_seq &selected_defseq)
244{
245   /* if we used to be "none", toggle to the default value */
246   if (original_seq.length() == 0)
247      selected_seq = selected_defseq;
248
249   /* otherwise, toggle to "none" */
250   else
251      selected_seq.reset();
252}
253
254void ui_menu_input::handle()
255{
256   input_item_data *seqchangeditem = NULL;
257   const ui_menu_event *menu_event;
258   int invalidate = false;
259
260   /* process the menu */
261   menu_event = process((pollingitem != NULL) ? UI_MENU_PROCESS_NOKEYS : 0);
262
263   /* if we are polling, handle as a special case */
264   if (pollingitem != NULL)
265   {
266      input_item_data *item = pollingitem;
267      input_seq newseq;
268
269      /* if UI_CANCEL is pressed, abort */
270      if (ui_input_pressed(machine(), IPT_UI_CANCEL))
271      {
272         pollingitem = NULL;
273         record_next = false;
274         toggle_none_default(item->seq, starting_seq, *item->defseq);
275         seqchangeditem = item;
276      }
277
278      /* poll again; if finished, update the sequence */
279      if (machine().input().seq_poll())
280      {
281         pollingitem = NULL;
282         record_next = true;
283         item->seq = machine().input().seq_poll_final();
284         seqchangeditem = item;
285      }
286   }
287
288   /* otherwise, handle the events */
289   else if (menu_event != NULL && menu_event->itemref != NULL)
290   {
291      input_item_data *item = (input_item_data *)menu_event->itemref;
292      switch (menu_event->iptkey)
293      {
294         /* an item was selected: begin polling */
295         case IPT_UI_SELECT:
296            pollingitem = item;
297            last_sortorder = item->sortorder;
298            starting_seq = item->seq;
299            machine().input().seq_poll_start((item->type == INPUT_TYPE_ANALOG) ? ITEM_CLASS_ABSOLUTE : ITEM_CLASS_SWITCH, record_next ? &item->seq : NULL);
300            invalidate = true;
301            break;
302
303         /* if the clear key was pressed, reset the selected item */
304         case IPT_UI_CLEAR:
305            toggle_none_default(item->seq, item->seq, *item->defseq);
306            record_next = false;
307            seqchangeditem = item;
308            break;
309      }
310
311      /* if the selection changed, reset the "record next" flag */
312      if (item->sortorder != last_sortorder)
313         record_next = false;
314      last_sortorder = item->sortorder;
315   }
316
317   /* if the sequence changed, update it */
318   if (seqchangeditem != NULL)
319   {
320      update_input(seqchangeditem);
321
322      /* invalidate the menu to force an update */
323      invalidate = true;
324   }
325
326   /* if the menu is invalidated, clear it now */
327   if (invalidate)
328   {
329      pollingref = NULL;
330      if (pollingitem != NULL)
331      {
332         pollingref = pollingitem->ref;
333         pollingseq = pollingitem->seqtype;
334      }
335      reset(UI_MENU_RESET_REMEMBER_POSITION);
336   }
337}
338
339void ui_menu_input_general::update_input(struct input_item_data *seqchangeditem)
340{
341   const input_type_entry *entry = (const input_type_entry *)seqchangeditem->ref;
342   machine().ioport().set_type_seq(entry->type(), entry->player(), seqchangeditem->seqtype, seqchangeditem->seq);
343}
344
345void ui_menu_input_specific::update_input(struct input_item_data *seqchangeditem)
346{
347   ioport_field::user_settings settings;
348
349   ((ioport_field *)seqchangeditem->ref)->get_user_settings(settings);
350   settings.seq[seqchangeditem->seqtype] = seqchangeditem->seq;
351   ((ioport_field *)seqchangeditem->ref)->set_user_settings(settings);
352}
353
354
355/*-------------------------------------------------
356    menu_input_compare_items - compare two
357    items for quicksort
358-------------------------------------------------*/
359
360int ui_menu_input::compare_items(const void *i1, const void *i2)
361{
362   const input_item_data * const *data1 = (const input_item_data * const *)i1;
363   const input_item_data * const *data2 = (const input_item_data * const *)i2;
364   if ((*data1)->sortorder < (*data2)->sortorder)
365      return -1;
366   if ((*data1)->sortorder > (*data2)->sortorder)
367      return 1;
368   return 0;
369}
370
371
372/*-------------------------------------------------
373    menu_input_populate_and_sort - take a list
374    of input_item_data objects and build up the
375    menu from them
376-------------------------------------------------*/
377
378void ui_menu_input::populate_and_sort(input_item_data *itemlist)
379{
380   const char *nameformat[INPUT_TYPE_TOTAL] = { 0 };
381   input_item_data **itemarray, *item;
382   int numitems = 0, curitem;
383   astring text;
384   astring subtext;
385   astring prev_owner;
386   bool first_entry = true;
387
388   /* create a mini lookup table for name format based on type */
389   nameformat[INPUT_TYPE_DIGITAL] = "%s";
390   nameformat[INPUT_TYPE_ANALOG] = "%s Analog";
391   nameformat[INPUT_TYPE_ANALOG_INC] = "%s Analog Inc";
392   nameformat[INPUT_TYPE_ANALOG_DEC] = "%s Analog Dec";
393
394   /* first count the number of items */
395   for (item = itemlist; item != NULL; item = item->next)
396      numitems++;
397
398   /* now allocate an array of items and fill it up */
399   itemarray = (input_item_data **)m_pool_alloc(sizeof(*itemarray) * numitems);
400   for (item = itemlist, curitem = 0; item != NULL; item = item->next)
401      itemarray[curitem++] = item;
402
403   /* sort it */
404   qsort(itemarray, numitems, sizeof(*itemarray), compare_items);
405
406   /* build the menu */
407   for (curitem = 0; curitem < numitems; curitem++)
408   {
409      UINT32 flags = 0;
410
411      /* generate the name of the item itself, based off the base name and the type */
412      item = itemarray[curitem];
413      assert(nameformat[item->type] != NULL);
414
415      if (item->owner_name && strcmp(item->owner_name, prev_owner.cstr()) != 0)
416      {
417         if (first_entry)
418            first_entry = false;
419         else
420            item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
421         text.printf("[root%s]", item->owner_name);
422         item_append(text, NULL, 0, NULL);
423         prev_owner.cpy(item->owner_name);
424      }
425
426      text.printf(nameformat[item->type], item->name);
427
428      /* if we're polling this item, use some spaces with left/right arrows */
429      if (pollingref == item->ref)
430      {
431         subtext.cpy("   ");
432         flags |= MENU_FLAG_LEFT_ARROW | MENU_FLAG_RIGHT_ARROW;
433      }
434
435      /* otherwise, generate the sequence name and invert it if different from the default */
436      else
437      {
438         machine().input().seq_name(subtext, item->seq);
439         flags |= (item->seq != *item->defseq) ? MENU_FLAG_INVERT : 0;
440      }
441
442      /* add the item */
443      item_append(text, subtext, flags, item);
444   }
445}
446
447
448/*-------------------------------------------------
449    menu_settings_dip_switches - handle the DIP
450    switches menu
451-------------------------------------------------*/
452
453ui_menu_settings_dip_switches::ui_menu_settings_dip_switches(running_machine &machine, render_container *container) : ui_menu_settings(machine, container, IPT_DIPSWITCH)
454{
455}
456
457ui_menu_settings_dip_switches::~ui_menu_settings_dip_switches()
458{
459}
460
461/*-------------------------------------------------
462    menu_settings_driver_config - handle the
463    driver config menu
464-------------------------------------------------*/
465
466ui_menu_settings_driver_config::ui_menu_settings_driver_config(running_machine &machine, render_container *container) : ui_menu_settings(machine, container, IPT_CONFIG)
467{
468}
469
470ui_menu_settings_driver_config::~ui_menu_settings_driver_config()
471{
472}
473
474/*-------------------------------------------------
475    menu_settings_common - handle one of the
476    switches menus
477-------------------------------------------------*/
478
479void ui_menu_settings::handle()
480{
481   // process the menu
482   const ui_menu_event *menu_event = process(0);
483
484   // handle events
485   if (menu_event != NULL && menu_event->itemref != NULL)
486   {
487      // reset
488      if ((FPTR)menu_event->itemref == 1)
489      {
490         if (menu_event->iptkey == IPT_UI_SELECT)
491            machine().schedule_hard_reset();
492      }
493      // actual settings
494      else
495      {
496         ioport_field *field = (ioport_field *)menu_event->itemref;
497         ioport_field::user_settings settings;
498         int changed = false;
499         
500         switch (menu_event->iptkey)
501         {
502            /* if selected, reset to default value */
503            case IPT_UI_SELECT:
504               field->get_user_settings(settings);
505               settings.value = field->defvalue();
506               field->set_user_settings(settings);
507               changed = true;
508               break;
509               
510            /* left goes to previous setting */
511            case IPT_UI_LEFT:
512               field->select_previous_setting();
513               changed = true;
514               break;
515               
516            /* right goes to next setting */
517            case IPT_UI_RIGHT:
518               field->select_next_setting();
519               changed = true;
520               break;
521         }
522         
523         /* if anything changed, rebuild the menu, trying to stay on the same field */
524         if (changed)
525            reset(UI_MENU_RESET_REMEMBER_REF);
526      }
527   }
528}
529
530
531/*-------------------------------------------------
532    menu_settings_populate - populate one of the
533    switches menus
534-------------------------------------------------*/
535
536ui_menu_settings::ui_menu_settings(running_machine &machine, render_container *container, UINT32 _type) : ui_menu(machine, container)
537{
538   type = _type;
539}
540
541void ui_menu_settings::populate()
542{
543   ioport_field *field;
544   ioport_port *port;
545   dip_descriptor **diplist_tailptr;
546   astring prev_owner;
547   bool first_entry = true;
548
549   /* reset the dip switch tracking */
550   dipcount = 0;
551   diplist = NULL;
552   diplist_tailptr = &diplist;
553
554   /* loop over input ports and set up the current values */
555   for (port = machine().ioport().first_port(); port != NULL; port = port->next())
556      for (field = port->first_field(); field != NULL; field = field->next())
557         if (field->type() == type && field->enabled())
558         {
559            UINT32 flags = 0;
560            astring name;
561
562            /* set the left/right flags appropriately */
563            if (field->has_previous_setting())
564               flags |= MENU_FLAG_LEFT_ARROW;
565            if (field->has_next_setting())
566               flags |= MENU_FLAG_RIGHT_ARROW;
567
568            /* add the menu item */
569            if (strcmp(field->device().tag(), prev_owner.cstr()) != 0)
570            {
571               if (first_entry)
572                  first_entry = false;
573               else
574                  item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
575               name.printf("[root%s]", field->device().tag());
576               item_append(name, NULL, 0, NULL);
577               prev_owner.cpy(field->device().tag());
578            }
579
580            name.cpy(field->name());
581
582            item_append(name, field->setting_name(), flags, (void *)field);
583
584            /* for DIP switches, build up the model */
585            if (type == IPT_DIPSWITCH && field->first_diplocation() != NULL)
586            {
587               const ioport_diplocation *diploc;
588               ioport_field::user_settings settings;
589               UINT32 accummask = field->mask();
590
591               /* get current settings */
592               field->get_user_settings(settings);
593
594               /* iterate over each bit in the field */
595               for (diploc = field->first_diplocation(); diploc != NULL; diploc = diploc->next())
596               {
597                  UINT32 mask = accummask & ~(accummask - 1);
598                  dip_descriptor *dip;
599
600                  /* find the matching switch name */
601                  for (dip = diplist; dip != NULL; dip = dip->next)
602                     if (strcmp(dip->name, diploc->name()) == 0)
603                        break;
604
605                  /* allocate new if none */
606                  if (dip == NULL)
607                  {
608                     dip = (dip_descriptor *)m_pool_alloc(sizeof(*dip));
609                     dip->next = NULL;
610                     dip->name = diploc->name();
611                     dip->mask = dip->state = 0;
612                     *diplist_tailptr = dip;
613                     diplist_tailptr = &dip->next;
614                     dipcount++;
615                  }
616
617                  /* apply the bits */
618                  dip->mask |= 1 << (diploc->number() - 1);
619                  if (((settings.value & mask) != 0 && !diploc->inverted()) || ((settings.value & mask) == 0 && diploc->inverted()))
620                     dip->state |= 1 << (diploc->number() - 1);
621
622                  /* clear the relevant bit in the accumulated mask */
623                  accummask &= ~mask;
624               }
625            }
626         }
627   if (type == IPT_DIPSWITCH)
628      custombottom = dipcount ? dipcount * (DIP_SWITCH_HEIGHT + DIP_SWITCH_SPACING) + DIP_SWITCH_SPACING : 0;
629   
630   item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
631   item_append("Reset",  NULL, 0, (void *)1);
632}
633
634ui_menu_settings::~ui_menu_settings()
635{
636}
637
638/*-------------------------------------------------
639    menu_settings_custom_render - perform our special
640    rendering
641-------------------------------------------------*/
642
643void ui_menu_settings_dip_switches::custom_render(void *selectedref, float top, float bottom, float x1, float y1, float x2, float y2)
644{
645   // catch if no diploc has to be drawn
646   if (bottom == 0)
647      return;
648
649   // add borders
650   y1 = y2 + UI_BOX_TB_BORDER;
651   y2 = y1 + bottom;
652
653   // draw extra menu area
654   machine().ui().draw_outlined_box(container, x1, y1, x2, y2, UI_BACKGROUND_COLOR);
655   y1 += (float)DIP_SWITCH_SPACING;
656
657   // iterate over DIP switches
658   for (dip_descriptor *dip = diplist; dip != NULL; dip = dip->next)
659   {
660      const ioport_diplocation *diploc;
661      UINT32 selectedmask = 0;
662     
663      // determine the mask of selected bits
664      if ((FPTR)selectedref != 1)
665      {
666         ioport_field *field = (ioport_field *)selectedref;
667         
668         if (field != NULL && field->first_diplocation() != NULL)
669            for (diploc = field->first_diplocation(); diploc != NULL; diploc = diploc->next())
670               if (strcmp(dip->name, diploc->name()) == 0)
671                  selectedmask |= 1 << (diploc->number() - 1);
672      }
673     
674      // draw one switch
675      custom_render_one(x1, y1, x2, y1 + DIP_SWITCH_HEIGHT, dip, selectedmask);
676      y1 += (float)(DIP_SWITCH_SPACING + DIP_SWITCH_HEIGHT);
677   }
678}
679
680
681/*-------------------------------------------------
682    menu_settings_custom_render_one - draw a single
683    DIP switch
684-------------------------------------------------*/
685
686void ui_menu_settings_dip_switches::custom_render_one(float x1, float y1, float x2, float y2, const dip_descriptor *dip, UINT32 selectedmask)
687{
688   float switch_field_width = SINGLE_TOGGLE_SWITCH_FIELD_WIDTH * container->manager().ui_aspect();
689   float switch_width = SINGLE_TOGGLE_SWITCH_WIDTH * container->manager().ui_aspect();
690   int numtoggles, toggle;
691   float switch_toggle_gap;
692   float y1_off, y1_on;
693
694   /* determine the number of toggles in the DIP */
695   numtoggles = 32 - count_leading_zeros(dip->mask);
696
697   /* center based on the number of switches */
698   x1 += (x2 - x1 - numtoggles * switch_field_width) / 2;
699
700   /* draw the dip switch name */
701   machine().ui().draw_text_full(  container,
702                  dip->name,
703                  0,
704                  y1 + (DIP_SWITCH_HEIGHT - UI_TARGET_FONT_HEIGHT) / 2,
705                  x1 - machine().ui().get_string_width(" "),
706                  JUSTIFY_RIGHT,
707                  WRAP_NEVER,
708                  DRAW_NORMAL,
709                  UI_TEXT_COLOR,
710                  PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA),
711                  NULL ,
712                  NULL);
713
714   /* compute top and bottom for on and off positions */
715   switch_toggle_gap = ((DIP_SWITCH_HEIGHT/2) - SINGLE_TOGGLE_SWITCH_HEIGHT)/2;
716   y1_off = y1 + UI_LINE_WIDTH + switch_toggle_gap;
717   y1_on = y1 + DIP_SWITCH_HEIGHT/2 + switch_toggle_gap;
718
719   /* iterate over toggles */
720   for (toggle = 0; toggle < numtoggles; toggle++)
721   {
722      float innerx1;
723
724      /* first outline the switch */
725      machine().ui().draw_outlined_box(container, x1, y1, x1 + switch_field_width, y2, UI_BACKGROUND_COLOR);
726
727      /* compute x1/x2 for the inner filled in switch */
728      innerx1 = x1 + (switch_field_width - switch_width) / 2;
729
730      /* see if the switch is actually used */
731      if (dip->mask & (1 << toggle))
732      {
733         float innery1 = (dip->state & (1 << toggle)) ? y1_on : y1_off;
734         container->add_rect(innerx1, innery1, innerx1 + switch_width, innery1 + SINGLE_TOGGLE_SWITCH_HEIGHT,
735                        (selectedmask & (1 << toggle)) ? UI_DIPSW_COLOR : UI_TEXT_COLOR,
736                        PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA));
737      }
738      else
739      {
740         container->add_rect(innerx1, y1_off, innerx1 + switch_width, y1_on + SINGLE_TOGGLE_SWITCH_HEIGHT,
741                        UI_UNAVAILABLE_COLOR,
742                        PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA));
743      }
744
745      /* advance to the next switch */
746      x1 += switch_field_width;
747   }
748}
749
750
751/*-------------------------------------------------
752    menu_analog - handle the analog settings menu
753-------------------------------------------------*/
754
755void ui_menu_analog::handle()
756{
757   /* process the menu */
758   const ui_menu_event *menu_event = process(UI_MENU_PROCESS_LR_REPEAT);
759
760   /* handle events */
761   if (menu_event != NULL && menu_event->itemref != NULL)
762   {
763      analog_item_data *data = (analog_item_data *)menu_event->itemref;
764      int newval = data->cur;
765
766      switch (menu_event->iptkey)
767      {
768         /* if selected, reset to default value */
769         case IPT_UI_SELECT:
770            newval = data->defvalue;
771            break;
772
773         /* left decrements */
774         case IPT_UI_LEFT:
775            newval -= machine().input().code_pressed(KEYCODE_LSHIFT) ? 10 : 1;
776            break;
777
778         /* right increments */
779         case IPT_UI_RIGHT:
780            newval += machine().input().code_pressed(KEYCODE_LSHIFT) ? 10 : 1;
781            break;
782      }
783
784      /* clamp to range */
785      if (newval < data->min)
786         newval = data->min;
787      if (newval > data->max)
788         newval = data->max;
789
790      /* if things changed, update */
791      if (newval != data->cur)
792      {
793         ioport_field::user_settings settings;
794
795         /* get the settings and set the new value */
796         data->field->get_user_settings(settings);
797         switch (data->type)
798         {
799            case ANALOG_ITEM_KEYSPEED:      settings.delta = newval;        break;
800            case ANALOG_ITEM_CENTERSPEED:   settings.centerdelta = newval;  break;
801            case ANALOG_ITEM_REVERSE:       settings.reverse = newval;      break;
802            case ANALOG_ITEM_SENSITIVITY:   settings.sensitivity = newval;  break;
803         }
804         data->field->set_user_settings(settings);
805
806         /* rebuild the menu */
807         reset(UI_MENU_RESET_REMEMBER_POSITION);
808      }
809   }
810}
811
812
813/*-------------------------------------------------
814    menu_analog_populate - populate the analog
815    settings menu
816-------------------------------------------------*/
817
818ui_menu_analog::ui_menu_analog(running_machine &machine, render_container *container) : ui_menu(machine, container)
819{
820}
821
822void ui_menu_analog::populate()
823{
824   ioport_field *field;
825   ioport_port *port;
826   astring text;
827   astring subtext;
828   astring prev_owner;
829   bool first_entry = true;
830
831   /* loop over input ports and add the items */
832   for (port = machine().ioport().first_port(); port != NULL; port = port->next())
833      for (field = port->first_field(); field != NULL; field = field->next())
834         if (field->is_analog() && field->enabled())
835         {
836            ioport_field::user_settings settings;
837            int use_autocenter = false;
838            int type;
839
840            /* based on the type, determine if we enable autocenter */
841            switch (field->type())
842            {
843               case IPT_POSITIONAL:
844               case IPT_POSITIONAL_V:
845                  if (field->analog_wraps())
846                     break;
847
848               case IPT_AD_STICK_X:
849               case IPT_AD_STICK_Y:
850               case IPT_AD_STICK_Z:
851               case IPT_PADDLE:
852               case IPT_PADDLE_V:
853               case IPT_PEDAL:
854               case IPT_PEDAL2:
855               case IPT_PEDAL3:
856                  use_autocenter = true;
857                  break;
858
859               default:
860                  break;
861            }
862
863            /* get the user settings */
864            field->get_user_settings(settings);
865
866            /* iterate over types */
867            for (type = 0; type < ANALOG_ITEM_COUNT; type++)
868               if (type != ANALOG_ITEM_CENTERSPEED || use_autocenter)
869               {
870                  analog_item_data *data;
871                  UINT32 flags = 0;
872                  astring name;
873                  if (strcmp(field->device().tag(), prev_owner.cstr()) != 0)
874                  {
875                     if (first_entry)
876                        first_entry = false;
877                     else
878                        item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
879                     name.printf("[root%s]", field->device().tag());
880                     item_append(name, NULL, 0, NULL);
881                     prev_owner.cpy(field->device().tag());
882                  }
883
884                  name.cpy(field->name());
885                 
886                  /* allocate a data item for tracking what this menu item refers to */
887                  data = (analog_item_data *)m_pool_alloc(sizeof(*data));
888                  data->field = field;
889                  data->type = type;
890
891                  /* determine the properties of this item */
892                  switch (type)
893                  {
894                     default:
895                     case ANALOG_ITEM_KEYSPEED:
896                        text.printf("%s Digital Speed", name.cstr());
897                        subtext.printf("%d", settings.delta);
898                        data->min = 0;
899                        data->max = 255;
900                        data->cur = settings.delta;
901                        data->defvalue = field->delta();
902                        break;
903
904                     case ANALOG_ITEM_CENTERSPEED:
905                        text.printf("%s Autocenter Speed", name.cstr());
906                        subtext.printf("%d", settings.centerdelta);
907                        data->min = 0;
908                        data->max = 255;
909                        data->cur = settings.centerdelta;
910                        data->defvalue = field->centerdelta();
911                        break;
912
913                     case ANALOG_ITEM_REVERSE:
914                        text.printf("%s Reverse", name.cstr());
915                        subtext.cpy(settings.reverse ? "On" : "Off");
916                        data->min = 0;
917                        data->max = 1;
918                        data->cur = settings.reverse;
919                        data->defvalue = field->analog_reverse();
920                        break;
921
922                     case ANALOG_ITEM_SENSITIVITY:
923                        text.printf("%s Sensitivity", name.cstr());
924                        subtext.printf("%d", settings.sensitivity);
925                        data->min = 1;
926                        data->max = 255;
927                        data->cur = settings.sensitivity;
928                        data->defvalue = field->sensitivity();
929                        break;
930                  }
931
932                  /* put on arrows */
933                  if (data->cur > data->min)
934                     flags |= MENU_FLAG_LEFT_ARROW;
935                  if (data->cur < data->max)
936                     flags |= MENU_FLAG_RIGHT_ARROW;
937
938                  /* append a menu item */
939                  item_append(text, subtext, flags, data);
940               }
941         }
942}
943
944ui_menu_analog::~ui_menu_analog()
945{
946}
trunk/src/emu/ui/inputmap.h
r242959r242960
1/***************************************************************************
2
3    ui/inputmap.h
4
5    Internal menus for input mappings.
6
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10***************************************************************************/
11
12#pragma once
13
14#ifndef __UI_INPUTMAP_H__
15#define __UI_INPUTMAP_H__
16
17//#include "drivenum.h"
18
19class ui_menu_input_groups : public ui_menu {
20public:
21   ui_menu_input_groups(running_machine &machine, render_container *container);
22   virtual ~ui_menu_input_groups();
23   virtual void populate();
24   virtual void handle();
25};
26
27class ui_menu_input : public ui_menu {
28public:
29   ui_menu_input(running_machine &machine, render_container *container);
30   virtual ~ui_menu_input();
31   virtual void handle();
32
33protected:
34   enum {
35      INPUT_TYPE_DIGITAL = 0,
36      INPUT_TYPE_ANALOG = 1,
37      INPUT_TYPE_ANALOG_DEC = INPUT_TYPE_ANALOG + SEQ_TYPE_DECREMENT,
38      INPUT_TYPE_ANALOG_INC = INPUT_TYPE_ANALOG + SEQ_TYPE_INCREMENT,
39      INPUT_TYPE_TOTAL = INPUT_TYPE_ANALOG + SEQ_TYPE_TOTAL
40   };
41
42   /* internal input menu item data */
43   struct input_item_data {
44      input_item_data *   next;               /* pointer to next item in the list */
45      const void *        ref;                /* reference to type description for global inputs or field for game inputs */
46      input_seq_type      seqtype;            /* sequence type */
47      input_seq           seq;                /* copy of the live sequence */
48      const input_seq *   defseq;             /* pointer to the default sequence */
49      const char *        name;               /* pointer to the base name of the item */
50      const char *        owner_name;         /* pointer to the name of the owner of the item */
51      UINT32              sortorder;          /* sorting information */
52      UINT8               type;               /* type of port */
53   };
54
55   void populate_and_sort(struct input_item_data *itemlist);
56   virtual void update_input(struct input_item_data *seqchangeditem) = 0;
57   void toggle_none_default(input_seq &selected_seq, input_seq &original_seq, const input_seq &selected_defseq);
58
59protected:
60   const void *        pollingref;
61   input_seq_type      pollingseq;
62   input_item_data *   pollingitem;
63
64private:
65   UINT16              last_sortorder;
66   bool                record_next;
67   input_seq           starting_seq;
68
69   static int compare_items(const void *i1, const void *i2);
70};
71
72class ui_menu_input_general : public ui_menu_input {
73public:
74   ui_menu_input_general(running_machine &machine, render_container *container, int group);
75   virtual ~ui_menu_input_general();
76   virtual void populate();
77
78protected:
79   int group;
80   virtual void update_input(struct input_item_data *seqchangeditem);
81};
82
83class ui_menu_input_specific : public ui_menu_input {
84public:
85   ui_menu_input_specific(running_machine &machine, render_container *container);
86   virtual ~ui_menu_input_specific();
87   virtual void populate();
88
89protected:
90   virtual void update_input(struct input_item_data *seqchangeditem);
91};
92
93class ui_menu_settings : public ui_menu {
94public:
95   ui_menu_settings(running_machine &machine, render_container *container, UINT32 type);
96   virtual ~ui_menu_settings();
97   virtual void populate();
98   virtual void handle();
99
100protected:
101   /* DIP switch descriptor */
102   struct dip_descriptor {
103      dip_descriptor *    next;
104      const char *        name;
105      UINT32              mask;
106      UINT32              state;
107   };
108
109   dip_descriptor *    diplist;
110   int dipcount;
111   int type;
112};
113
114class ui_menu_settings_dip_switches : public ui_menu_settings {
115public:
116   ui_menu_settings_dip_switches(running_machine &machine, render_container *container);
117   virtual ~ui_menu_settings_dip_switches();
118
119   virtual void custom_render(void *selectedref, float top, float bottom, float x, float y, float x2, float y2);
120private:
121   void custom_render_one(float x1, float y1, float x2, float y2, const dip_descriptor *dip, UINT32 selectedmask);
122};
123
124class ui_menu_settings_driver_config : public ui_menu_settings {
125public:
126   ui_menu_settings_driver_config(running_machine &machine, render_container *container);
127   virtual ~ui_menu_settings_driver_config();
128};
129
130class ui_menu_analog : public ui_menu {
131public:
132   ui_menu_analog(running_machine &machine, render_container *container);
133   virtual ~ui_menu_analog();
134   virtual void populate();
135   virtual void handle();
136
137private:
138   enum {
139      ANALOG_ITEM_KEYSPEED = 0,
140      ANALOG_ITEM_CENTERSPEED,
141      ANALOG_ITEM_REVERSE,
142      ANALOG_ITEM_SENSITIVITY,
143      ANALOG_ITEM_COUNT
144   };
145
146   /* internal analog menu item data */
147   struct analog_item_data {
148      ioport_field *field;
149      int                 type;
150      int                 min, max;
151      int                 cur;
152      int                 defvalue;
153   };
154};
155
156#endif  /* __UI_INPUTMAP_H__ */
trunk/src/emu/ui/mainmenu.c
r242959r242960
1919#include "ui/filemngr.h"
2020#include "ui/filesel.h"
2121#include "ui/barcode.h"
22#include "ui/imginfo.h"
23#include "ui/inputmap.h"
22#include "ui/tapectrl.h"
2423#include "ui/mainmenu.h"
2524#include "ui/miscmenu.h"
25#include "ui/imginfo.h"
2626#include "ui/selgame.h"
27#include "ui/slotopt.h"
28#include "ui/tapectrl.h"
2927#include "audit.h"
3028#include "crsshair.h"
3129#include <ctype.h>
trunk/src/emu/ui/miscmenu.c
r242959r242960
2323#include "ui/miscmenu.h"
2424#include "ui/filemngr.h"
2525
26#include "osdepend.h"
2726
27/***************************************************************************
28    CONSTANTS
29***************************************************************************/
30
31#define MAX_PHYSICAL_DIPS       10
32#define MAX_INPUT_PORTS         32
33#define MAX_BITS_PER_PORT       32
34
35/* DIP switch rendering parameters */
36#define DIP_SWITCH_HEIGHT       0.05f
37#define DIP_SWITCH_SPACING      0.01
38#define SINGLE_TOGGLE_SWITCH_FIELD_WIDTH 0.025f
39#define SINGLE_TOGGLE_SWITCH_WIDTH 0.020f
40/* make the switch 80% of the width space and 1/2 of the switch height */
41#define PERCENTAGE_OF_HALF_FIELD_USED 0.80f
42#define SINGLE_TOGGLE_SWITCH_HEIGHT ((DIP_SWITCH_HEIGHT / 2) * PERCENTAGE_OF_HALF_FIELD_USED)
43
2844/*-------------------------------------------------
2945    ui_slider_ui_handler - pushes the slider
3046    menu on the stack and hands off to the
r242959r242960
92108
93109
94110/*-------------------------------------------------
111    ui_slot_get_current_option - returns
112-------------------------------------------------*/
113device_slot_option *ui_menu_slot_devices::slot_get_current_option(device_slot_interface *slot)
114{
115   const char *current;
116   if (slot->fixed())
117   {
118      current = slot->default_option();
119   }
120   else
121   {
122      astring temp;
123      current = machine().options().main_value(temp, slot->device().tag() + 1);
124   }
125
126   return slot->option(current);
127}
128
129/*-------------------------------------------------
130    ui_slot_get_current_index - returns
131-------------------------------------------------*/
132int ui_menu_slot_devices::slot_get_current_index(device_slot_interface *slot)
133{
134   const device_slot_option *current = slot_get_current_option(slot);
135
136   if (current != NULL)
137   {
138      int val = 0;
139      for (const device_slot_option *option = slot->first_option(); option != NULL; option = option->next())
140      {
141         if (option == current)
142            return val;
143
144         if (option->selectable())
145            val++;
146      }
147   }
148
149   return -1;
150}
151
152/*-------------------------------------------------
153    ui_slot_get_length - returns
154-------------------------------------------------*/
155int ui_menu_slot_devices::slot_get_length(device_slot_interface *slot)
156{
157   int val = 0;
158   for (const device_slot_option *option = slot->first_option(); option != NULL; option = option->next())
159      if (option->selectable())
160         val++;
161
162   return val;
163}
164
165/*-------------------------------------------------
166    ui_slot_get_next - returns
167-------------------------------------------------*/
168const char *ui_menu_slot_devices::slot_get_next(device_slot_interface *slot)
169{
170   int idx = slot_get_current_index(slot);
171   if (idx < 0)
172      idx = 0;
173   else
174      idx++;
175
176   if (idx >= slot_get_length(slot))
177      return "";
178
179   return slot_get_option(slot, idx);
180}
181
182/*-------------------------------------------------
183    ui_slot_get_prev - returns
184-------------------------------------------------*/
185const char *ui_menu_slot_devices::slot_get_prev(device_slot_interface *slot)
186{
187   int idx = slot_get_current_index(slot);
188   if (idx < 0)
189      idx = slot_get_length(slot) - 1;
190   else
191      idx--;
192
193   if (idx < 0)
194      return "";
195
196   return slot_get_option(slot, idx);
197}
198
199/*-------------------------------------------------
200    ui_slot_get_option - returns
201-------------------------------------------------*/
202const char *ui_menu_slot_devices::slot_get_option(device_slot_interface *slot, int index)
203{
204   if (index >= 0)
205   {
206      int val = 0;
207      for (const device_slot_option *option = slot->first_option(); option != NULL; option = option->next())
208      {
209         if (val == index)
210            return option->name();
211
212         if (option->selectable())
213            val++;
214      }
215   }
216
217   return "";
218}
219
220
221/*-------------------------------------------------
222    ui_set_use_natural_keyboard - specifies
223    whether the natural keyboard is active
224-------------------------------------------------*/
225
226void ui_menu_slot_devices::set_slot_device(device_slot_interface *slot, const char *val)
227{
228   astring error;
229   machine().options().set_value(slot->device().tag()+1, val, OPTION_PRIORITY_CMDLINE, error);
230   assert(!error);
231}
232
233/*-------------------------------------------------
234    menu_slot_devices_populate - populates the main
235    slot device menu
236-------------------------------------------------*/
237
238ui_menu_slot_devices::ui_menu_slot_devices(running_machine &machine, render_container *container) : ui_menu(machine, container)
239{
240}
241
242void ui_menu_slot_devices::populate()
243{
244   /* cycle through all devices for this system */
245   slot_interface_iterator iter(machine().root_device());
246   for (device_slot_interface *slot = iter.first(); slot != NULL; slot = iter.next())
247   {
248      /* record the menu item */
249      const device_slot_option *option = slot_get_current_option(slot);
250      astring opt_name;
251      if (option == NULL)
252         opt_name.cpy("------");
253      else
254      {
255         opt_name.cpy(option->name());
256         if (slot->fixed() || slot_get_length(slot) == 0)
257            opt_name.cat(" [internal]");
258      }
259
260      item_append(slot->device().tag() + 1, opt_name, (slot->fixed() || slot_get_length(slot) == 0) ? 0 : (MENU_FLAG_LEFT_ARROW | MENU_FLAG_RIGHT_ARROW), (void *)slot);
261   }
262   item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
263   item_append("Reset",  NULL, 0, (void *)1);
264}
265
266ui_menu_slot_devices::~ui_menu_slot_devices()
267{
268}
269
270/*-------------------------------------------------
271    ui_menu_slot_devices - menu that
272-------------------------------------------------*/
273
274void ui_menu_slot_devices::handle()
275{
276   /* process the menu */
277   const ui_menu_event *menu_event = process(0);
278
279   if (menu_event != NULL && menu_event->itemref != NULL)
280   {
281      if ((FPTR)menu_event->itemref == 1 && menu_event->iptkey == IPT_UI_SELECT)
282         machine().schedule_hard_reset();
283      else if (menu_event->iptkey == IPT_UI_LEFT || menu_event->iptkey == IPT_UI_RIGHT)
284      {
285         device_slot_interface *slot = (device_slot_interface *)menu_event->itemref;
286         const char *val = (menu_event->iptkey == IPT_UI_LEFT) ? slot_get_prev(slot) : slot_get_next(slot);
287         set_slot_device(slot, val);
288         reset(UI_MENU_RESET_REMEMBER_REF);
289      }
290   }
291}
292
293/*-------------------------------------------------
95294    ui_menu_bios_selection - populates the main
96295    bios selection menu
97296-------------------------------------------------*/
r242959r242960
227426   }
228427}
229428
429/*-------------------------------------------------
430    menu_input_groups_populate - populate the
431    input groups menu
432-------------------------------------------------*/
230433
434ui_menu_input_groups::ui_menu_input_groups(running_machine &machine, render_container *container) : ui_menu(machine, container)
435{
436}
437
438void ui_menu_input_groups::populate()
439{
440   int player;
441
442   /* build up the menu */
443   item_append("User Interface", NULL, 0, (void *)(IPG_UI + 1));
444   for (player = 0; player < MAX_PLAYERS; player++)
445   {
446      char buffer[40];
447      sprintf(buffer, "Player %d Controls", player + 1);
448      item_append(buffer, NULL, 0, (void *)(FPTR)(IPG_PLAYER1 + player + 1));
449   }
450   item_append("Other Controls", NULL, 0, (void *)(FPTR)(IPG_OTHER + 1));
451}
452
453ui_menu_input_groups::~ui_menu_input_groups()
454{
455}
456
231457/*-------------------------------------------------
458    menu_input_groups - handle the input groups
459    menu
460-------------------------------------------------*/
461
462void ui_menu_input_groups::handle()
463{
464   /* process the menu */
465   const ui_menu_event *menu_event = process(0);
466   if (menu_event != NULL && menu_event->iptkey == IPT_UI_SELECT)
467      ui_menu::stack_push(auto_alloc_clear(machine(), ui_menu_input_general(machine(), container, int((long long)(menu_event->itemref)-1))));
468}
469
470
471
472/*-------------------------------------------------
473    menu_input_general - handle the general
474    input menu
475-------------------------------------------------*/
476
477ui_menu_input_general::ui_menu_input_general(running_machine &machine, render_container *container, int _group) : ui_menu_input(machine, container)
478{
479   group = _group;
480}
481
482void ui_menu_input_general::populate()
483{
484   input_item_data *itemlist = NULL;
485   int suborder[SEQ_TYPE_TOTAL];
486   astring tempstring;
487   int sortorder = 1;
488
489   /* create a mini lookup table for sort order based on sequence type */
490   suborder[SEQ_TYPE_STANDARD] = 0;
491   suborder[SEQ_TYPE_DECREMENT] = 1;
492   suborder[SEQ_TYPE_INCREMENT] = 2;
493
494   /* iterate over the input ports and add menu items */
495   for (input_type_entry *entry = machine().ioport().first_type(); entry != NULL; entry = entry->next())
496
497      /* add if we match the group and we have a valid name */
498      if (entry->group() == group && entry->name() != NULL && entry->name()[0] != 0)
499      {
500         input_seq_type seqtype;
501
502         /* loop over all sequence types */
503         sortorder++;
504         for (seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; seqtype++)
505         {
506            /* build an entry for the standard sequence */
507            input_item_data *item = (input_item_data *)m_pool_alloc(sizeof(*item));
508            memset(item, 0, sizeof(*item));
509            item->ref = entry;
510            if(pollingitem && pollingref == entry && pollingseq == seqtype)
511               pollingitem = item;
512            item->seqtype = seqtype;
513            item->seq = machine().ioport().type_seq(entry->type(), entry->player(), seqtype);
514            item->defseq = &entry->defseq(seqtype);
515            item->sortorder = sortorder * 4 + suborder[seqtype];
516            item->type = ioport_manager::type_is_analog(entry->type()) ? (INPUT_TYPE_ANALOG + seqtype) : INPUT_TYPE_DIGITAL;
517            item->name = entry->name();
518            item->owner_name = NULL;
519            item->next = itemlist;
520            itemlist = item;
521
522            /* stop after one, unless we're analog */
523            if (item->type == INPUT_TYPE_DIGITAL)
524               break;
525         }
526      }
527
528   /* sort and populate the menu in a standard fashion */
529   populate_and_sort(itemlist);
530}
531
532ui_menu_input_general::~ui_menu_input_general()
533{
534}
535
536/*-------------------------------------------------
537    menu_input_specific - handle the game-specific
538    input menu
539-------------------------------------------------*/
540
541ui_menu_input_specific::ui_menu_input_specific(running_machine &machine, render_container *container) : ui_menu_input(machine, container)
542{
543}
544
545void ui_menu_input_specific::populate()
546{
547   input_item_data *itemlist = NULL;
548   ioport_field *field;
549   ioport_port *port;
550   int suborder[SEQ_TYPE_TOTAL];
551   astring tempstring;
552
553   /* create a mini lookup table for sort order based on sequence type */
554   suborder[SEQ_TYPE_STANDARD] = 0;
555   suborder[SEQ_TYPE_DECREMENT] = 1;
556   suborder[SEQ_TYPE_INCREMENT] = 2;
557
558   /* iterate over the input ports and add menu items */
559   for (port = machine().ioport().first_port(); port != NULL; port = port->next())
560      for (field = port->first_field(); field != NULL; field = field->next())
561      {
562         const char *name = field->name();
563
564         /* add if we match the group and we have a valid name */
565         if (name != NULL && field->enabled() &&
566            ((field->type() == IPT_OTHER && field->name() != NULL) || machine().ioport().type_group(field->type(), field->player()) != IPG_INVALID))
567         {
568            input_seq_type seqtype;
569            UINT32 sortorder;
570
571            /* determine the sorting order */
572            if (field->type() >= IPT_START1 && field->type() < IPT_ANALOG_LAST)
573            {
574               sortorder = (field->type() << 2) | (field->player() << 12);
575               if (strcmp(field->device().tag(), ":"))
576                  sortorder |= 0x10000;
577            }
578            else
579               sortorder = field->type() | 0xf000;
580
581            /* loop over all sequence types */
582            for (seqtype = SEQ_TYPE_STANDARD; seqtype < SEQ_TYPE_TOTAL; seqtype++)
583            {
584               /* build an entry for the standard sequence */
585               input_item_data *item = (input_item_data *)m_pool_alloc(sizeof(*item));
586               memset(item, 0, sizeof(*item));
587               item->ref = field;
588               item->seqtype = seqtype;
589               if(pollingitem && pollingref == field && pollingseq == seqtype)
590                  pollingitem = item;
591               item->seq = field->seq(seqtype);
592               item->defseq = &field->defseq(seqtype);
593               item->sortorder = sortorder + suborder[seqtype];
594               item->type = field->is_analog() ? (INPUT_TYPE_ANALOG + seqtype) : INPUT_TYPE_DIGITAL;
595               item->name = name;
596               item->owner_name = field->device().tag();
597               item->next = itemlist;
598               itemlist = item;
599
600               /* stop after one, unless we're analog */
601               if (item->type == INPUT_TYPE_DIGITAL)
602                  break;
603            }
604         }
605      }
606
607   /* sort and populate the menu in a standard fashion */
608   populate_and_sort(itemlist);
609}
610
611ui_menu_input_specific::~ui_menu_input_specific()
612{
613}
614
615/*-------------------------------------------------
616    menu_input - display a menu for inputs
617-------------------------------------------------*/
618ui_menu_input::ui_menu_input(running_machine &machine, render_container *container) : ui_menu(machine, container)
619{
620   pollingitem = 0;
621   pollingref = 0;
622   pollingseq = SEQ_TYPE_STANDARD;
623}
624
625ui_menu_input::~ui_menu_input()
626{
627}
628
629/*-------------------------------------------------
630    toggle_none_default - toggle between "NONE"
631    and the default item
632-------------------------------------------------*/
633
634void ui_menu_input::toggle_none_default(input_seq &selected_seq, input_seq &original_seq, const input_seq &selected_defseq)
635{
636   /* if we used to be "none", toggle to the default value */
637   if (original_seq.length() == 0)
638      selected_seq = selected_defseq;
639
640   /* otherwise, toggle to "none" */
641   else
642      selected_seq.reset();
643}
644
645void ui_menu_input::handle()
646{
647   input_item_data *seqchangeditem = NULL;
648   const ui_menu_event *menu_event;
649   int invalidate = false;
650
651   /* process the menu */
652   menu_event = process((pollingitem != NULL) ? UI_MENU_PROCESS_NOKEYS : 0);
653
654   /* if we are polling, handle as a special case */
655   if (pollingitem != NULL)
656   {
657      input_item_data *item = pollingitem;
658      input_seq newseq;
659
660      /* if UI_CANCEL is pressed, abort */
661      if (ui_input_pressed(machine(), IPT_UI_CANCEL))
662      {
663         pollingitem = NULL;
664         record_next = false;
665         toggle_none_default(item->seq, starting_seq, *item->defseq);
666         seqchangeditem = item;
667      }
668
669      /* poll again; if finished, update the sequence */
670      if (machine().input().seq_poll())
671      {
672         pollingitem = NULL;
673         record_next = true;
674         item->seq = machine().input().seq_poll_final();
675         seqchangeditem = item;
676      }
677   }
678
679   /* otherwise, handle the events */
680   else if (menu_event != NULL && menu_event->itemref != NULL)
681   {
682      input_item_data *item = (input_item_data *)menu_event->itemref;
683      switch (menu_event->iptkey)
684      {
685         /* an item was selected: begin polling */
686         case IPT_UI_SELECT:
687            pollingitem = item;
688            last_sortorder = item->sortorder;
689            starting_seq = item->seq;
690            machine().input().seq_poll_start((item->type == INPUT_TYPE_ANALOG) ? ITEM_CLASS_ABSOLUTE : ITEM_CLASS_SWITCH, record_next ? &item->seq : NULL);
691            invalidate = true;
692            break;
693
694         /* if the clear key was pressed, reset the selected item */
695         case IPT_UI_CLEAR:
696            toggle_none_default(item->seq, item->seq, *item->defseq);
697            record_next = false;
698            seqchangeditem = item;
699            break;
700      }
701
702      /* if the selection changed, reset the "record next" flag */
703      if (item->sortorder != last_sortorder)
704         record_next = false;
705      last_sortorder = item->sortorder;
706   }
707
708   /* if the sequence changed, update it */
709   if (seqchangeditem != NULL)
710   {
711      update_input(seqchangeditem);
712
713      /* invalidate the menu to force an update */
714      invalidate = true;
715   }
716
717   /* if the menu is invalidated, clear it now */
718   if (invalidate)
719   {
720      pollingref = NULL;
721      if (pollingitem != NULL)
722      {
723         pollingref = pollingitem->ref;
724         pollingseq = pollingitem->seqtype;
725      }
726      reset(UI_MENU_RESET_REMEMBER_POSITION);
727   }
728}
729
730void ui_menu_input_general::update_input(struct input_item_data *seqchangeditem)
731{
732   const input_type_entry *entry = (const input_type_entry *)seqchangeditem->ref;
733   machine().ioport().set_type_seq(entry->type(), entry->player(), seqchangeditem->seqtype, seqchangeditem->seq);
734}
735
736void ui_menu_input_specific::update_input(struct input_item_data *seqchangeditem)
737{
738   ioport_field::user_settings settings;
739
740   ((ioport_field *)seqchangeditem->ref)->get_user_settings(settings);
741   settings.seq[seqchangeditem->seqtype] = seqchangeditem->seq;
742   ((ioport_field *)seqchangeditem->ref)->set_user_settings(settings);
743}
744
745
746/*-------------------------------------------------
747    menu_input_compare_items - compare two
748    items for quicksort
749-------------------------------------------------*/
750
751int ui_menu_input::compare_items(const void *i1, const void *i2)
752{
753   const input_item_data * const *data1 = (const input_item_data * const *)i1;
754   const input_item_data * const *data2 = (const input_item_data * const *)i2;
755   if ((*data1)->sortorder < (*data2)->sortorder)
756      return -1;
757   if ((*data1)->sortorder > (*data2)->sortorder)
758      return 1;
759   return 0;
760}
761
762
763/*-------------------------------------------------
764    menu_input_populate_and_sort - take a list
765    of input_item_data objects and build up the
766    menu from them
767-------------------------------------------------*/
768
769void ui_menu_input::populate_and_sort(input_item_data *itemlist)
770{
771   const char *nameformat[INPUT_TYPE_TOTAL] = { 0 };
772   input_item_data **itemarray, *item;
773   int numitems = 0, curitem;
774   astring text;
775   astring subtext;
776   astring prev_owner;
777   bool first_entry = true;
778
779   /* create a mini lookup table for name format based on type */
780   nameformat[INPUT_TYPE_DIGITAL] = "%s";
781   nameformat[INPUT_TYPE_ANALOG] = "%s Analog";
782   nameformat[INPUT_TYPE_ANALOG_INC] = "%s Analog Inc";
783   nameformat[INPUT_TYPE_ANALOG_DEC] = "%s Analog Dec";
784
785   /* first count the number of items */
786   for (item = itemlist; item != NULL; item = item->next)
787      numitems++;
788
789   /* now allocate an array of items and fill it up */
790   itemarray = (input_item_data **)m_pool_alloc(sizeof(*itemarray) * numitems);
791   for (item = itemlist, curitem = 0; item != NULL; item = item->next)
792      itemarray[curitem++] = item;
793
794   /* sort it */
795   qsort(itemarray, numitems, sizeof(*itemarray), compare_items);
796
797   /* build the menu */
798   for (curitem = 0; curitem < numitems; curitem++)
799   {
800      UINT32 flags = 0;
801
802      /* generate the name of the item itself, based off the base name and the type */
803      item = itemarray[curitem];
804      assert(nameformat[item->type] != NULL);
805
806      if (strcmp(item->owner_name, prev_owner.cstr()) != 0)
807      {
808         if (first_entry)
809            first_entry = false;
810         else
811            item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
812         text.printf("[root%s]", item->owner_name);
813         item_append(text, NULL, 0, NULL);
814         prev_owner.cpy(item->owner_name);
815      }
816
817      text.printf(nameformat[item->type], item->name);
818
819      /* if we're polling this item, use some spaces with left/right arrows */
820      if (pollingref == item->ref)
821      {
822         subtext.cpy("   ");
823         flags |= MENU_FLAG_LEFT_ARROW | MENU_FLAG_RIGHT_ARROW;
824      }
825
826      /* otherwise, generate the sequence name and invert it if different from the default */
827      else
828      {
829         machine().input().seq_name(subtext, item->seq);
830         flags |= (item->seq != *item->defseq) ? MENU_FLAG_INVERT : 0;
831      }
832
833      /* add the item */
834      item_append(text, subtext, flags, item);
835   }
836}
837
838
839/*-------------------------------------------------
840    menu_settings_dip_switches - handle the DIP
841    switches menu
842-------------------------------------------------*/
843
844ui_menu_settings_dip_switches::ui_menu_settings_dip_switches(running_machine &machine, render_container *container) : ui_menu_settings(machine, container, IPT_DIPSWITCH)
845{
846}
847
848ui_menu_settings_dip_switches::~ui_menu_settings_dip_switches()
849{
850}
851
852/*-------------------------------------------------
853    menu_settings_driver_config - handle the
854    driver config menu
855-------------------------------------------------*/
856
857ui_menu_settings_driver_config::ui_menu_settings_driver_config(running_machine &machine, render_container *container) : ui_menu_settings(machine, container, IPT_CONFIG)
858{
859}
860
861ui_menu_settings_driver_config::~ui_menu_settings_driver_config()
862{
863}
864
865/*-------------------------------------------------
866    menu_settings_common - handle one of the
867    switches menus
868-------------------------------------------------*/
869
870void ui_menu_settings::handle()
871{
872   // process the menu
873   const ui_menu_event *menu_event = process(0);
874
875   // handle events
876   if (menu_event != NULL && menu_event->itemref != NULL)
877   {
878      // reset
879      if ((FPTR)menu_event->itemref == 1)
880      {
881         if (menu_event->iptkey == IPT_UI_SELECT)
882            machine().schedule_hard_reset();
883      }
884      // actual settings
885      else
886      {
887         ioport_field *field = (ioport_field *)menu_event->itemref;
888         ioport_field::user_settings settings;
889         int changed = false;
890         
891         switch (menu_event->iptkey)
892         {
893            /* if selected, reset to default value */
894            case IPT_UI_SELECT:
895               field->get_user_settings(settings);
896               settings.value = field->defvalue();
897               field->set_user_settings(settings);
898               changed = true;
899               break;
900               
901            /* left goes to previous setting */
902            case IPT_UI_LEFT:
903               field->select_previous_setting();
904               changed = true;
905               break;
906               
907            /* right goes to next setting */
908            case IPT_UI_RIGHT:
909               field->select_next_setting();
910               changed = true;
911               break;
912         }
913         
914         /* if anything changed, rebuild the menu, trying to stay on the same field */
915         if (changed)
916            reset(UI_MENU_RESET_REMEMBER_REF);
917      }
918   }
919}
920
921
922/*-------------------------------------------------
923    menu_settings_populate - populate one of the
924    switches menus
925-------------------------------------------------*/
926
927ui_menu_settings::ui_menu_settings(running_machine &machine, render_container *container, UINT32 _type) : ui_menu(machine, container)
928{
929   type = _type;
930}
931
932void ui_menu_settings::populate()
933{
934   ioport_field *field;
935   ioport_port *port;
936   dip_descriptor **diplist_tailptr;
937   astring prev_owner;
938   bool first_entry = true;
939
940   /* reset the dip switch tracking */
941   dipcount = 0;
942   diplist = NULL;
943   diplist_tailptr = &diplist;
944
945   /* loop over input ports and set up the current values */
946   for (port = machine().ioport().first_port(); port != NULL; port = port->next())
947      for (field = port->first_field(); field != NULL; field = field->next())
948         if (field->type() == type && field->enabled())
949         {
950            UINT32 flags = 0;
951            astring name;
952
953            /* set the left/right flags appropriately */
954            if (field->has_previous_setting())
955               flags |= MENU_FLAG_LEFT_ARROW;
956            if (field->has_next_setting())
957               flags |= MENU_FLAG_RIGHT_ARROW;
958
959            /* add the menu item */
960            if (strcmp(field->device().tag(), prev_owner.cstr()) != 0)
961            {
962               if (first_entry)
963                  first_entry = false;
964               else
965                  item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
966               name.printf("[root%s]", field->device().tag());
967               item_append(name, NULL, 0, NULL);
968               prev_owner.cpy(field->device().tag());
969            }
970
971            name.cpy(field->name());
972
973            item_append(name, field->setting_name(), flags, (void *)field);
974
975            /* for DIP switches, build up the model */
976            if (type == IPT_DIPSWITCH && field->first_diplocation() != NULL)
977            {
978               const ioport_diplocation *diploc;
979               ioport_field::user_settings settings;
980               UINT32 accummask = field->mask();
981
982               /* get current settings */
983               field->get_user_settings(settings);
984
985               /* iterate over each bit in the field */
986               for (diploc = field->first_diplocation(); diploc != NULL; diploc = diploc->next())
987               {
988                  UINT32 mask = accummask & ~(accummask - 1);
989                  dip_descriptor *dip;
990
991                  /* find the matching switch name */
992                  for (dip = diplist; dip != NULL; dip = dip->next)
993                     if (strcmp(dip->name, diploc->name()) == 0)
994                        break;
995
996                  /* allocate new if none */
997                  if (dip == NULL)
998                  {
999                     dip = (dip_descriptor *)m_pool_alloc(sizeof(*dip));
1000                     dip->next = NULL;
1001                     dip->name = diploc->name();
1002                     dip->mask = dip->state = 0;
1003                     *diplist_tailptr = dip;
1004                     diplist_tailptr = &dip->next;
1005                     dipcount++;
1006                  }
1007
1008                  /* apply the bits */
1009                  dip->mask |= 1 << (diploc->number() - 1);
1010                  if (((settings.value & mask) != 0 && !diploc->inverted()) || ((settings.value & mask) == 0 && diploc->inverted()))
1011                     dip->state |= 1 << (diploc->number() - 1);
1012
1013                  /* clear the relevant bit in the accumulated mask */
1014                  accummask &= ~mask;
1015               }
1016            }
1017         }
1018   if (type == IPT_DIPSWITCH)
1019      custombottom = dipcount ? dipcount * (DIP_SWITCH_HEIGHT + DIP_SWITCH_SPACING) + DIP_SWITCH_SPACING : 0;
1020   
1021   item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
1022   item_append("Reset",  NULL, 0, (void *)1);
1023}
1024
1025ui_menu_settings::~ui_menu_settings()
1026{
1027}
1028
1029/*-------------------------------------------------
1030    menu_settings_custom_render - perform our special
1031    rendering
1032-------------------------------------------------*/
1033
1034void ui_menu_settings_dip_switches::custom_render(void *selectedref, float top, float bottom, float x1, float y1, float x2, float y2)
1035{
1036   // catch if no diploc has to be drawn
1037   if (bottom == 0)
1038      return;
1039
1040   // add borders
1041   y1 = y2 + UI_BOX_TB_BORDER;
1042   y2 = y1 + bottom;
1043
1044   // draw extra menu area
1045   machine().ui().draw_outlined_box(container, x1, y1, x2, y2, UI_BACKGROUND_COLOR);
1046   y1 += (float)DIP_SWITCH_SPACING;
1047
1048   // iterate over DIP switches
1049   for (dip_descriptor *dip = diplist; dip != NULL; dip = dip->next)
1050   {
1051      const ioport_diplocation *diploc;
1052      UINT32 selectedmask = 0;
1053     
1054      // determine the mask of selected bits
1055      if ((FPTR)selectedref != 1)
1056      {
1057         ioport_field *field = (ioport_field *)selectedref;
1058         
1059         if (field != NULL && field->first_diplocation() != NULL)
1060            for (diploc = field->first_diplocation(); diploc != NULL; diploc = diploc->next())
1061               if (strcmp(dip->name, diploc->name()) == 0)
1062                  selectedmask |= 1 << (diploc->number() - 1);
1063      }
1064     
1065      // draw one switch
1066      custom_render_one(x1, y1, x2, y1 + DIP_SWITCH_HEIGHT, dip, selectedmask);
1067      y1 += (float)(DIP_SWITCH_SPACING + DIP_SWITCH_HEIGHT);
1068   }
1069}
1070
1071
1072/*-------------------------------------------------
1073    menu_settings_custom_render_one - draw a single
1074    DIP switch
1075-------------------------------------------------*/
1076
1077void ui_menu_settings_dip_switches::custom_render_one(float x1, float y1, float x2, float y2, const dip_descriptor *dip, UINT32 selectedmask)
1078{
1079   float switch_field_width = SINGLE_TOGGLE_SWITCH_FIELD_WIDTH * container->manager().ui_aspect();
1080   float switch_width = SINGLE_TOGGLE_SWITCH_WIDTH * container->manager().ui_aspect();
1081   int numtoggles, toggle;
1082   float switch_toggle_gap;
1083   float y1_off, y1_on;
1084
1085   /* determine the number of toggles in the DIP */
1086   numtoggles = 32 - count_leading_zeros(dip->mask);
1087
1088   /* center based on the number of switches */
1089   x1 += (x2 - x1 - numtoggles * switch_field_width) / 2;
1090
1091   /* draw the dip switch name */
1092   machine().ui().draw_text_full(  container,
1093                  dip->name,
1094                  0,
1095                  y1 + (DIP_SWITCH_HEIGHT - UI_TARGET_FONT_HEIGHT) / 2,
1096                  x1 - machine().ui().get_string_width(" "),
1097                  JUSTIFY_RIGHT,
1098                  WRAP_NEVER,
1099                  DRAW_NORMAL,
1100                  UI_TEXT_COLOR,
1101                  PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA),
1102                  NULL ,
1103                  NULL);
1104
1105   /* compute top and bottom for on and off positions */
1106   switch_toggle_gap = ((DIP_SWITCH_HEIGHT/2) - SINGLE_TOGGLE_SWITCH_HEIGHT)/2;
1107   y1_off = y1 + UI_LINE_WIDTH + switch_toggle_gap;
1108   y1_on = y1 + DIP_SWITCH_HEIGHT/2 + switch_toggle_gap;
1109
1110   /* iterate over toggles */
1111   for (toggle = 0; toggle < numtoggles; toggle++)
1112   {
1113      float innerx1;
1114
1115      /* first outline the switch */
1116      machine().ui().draw_outlined_box(container, x1, y1, x1 + switch_field_width, y2, UI_BACKGROUND_COLOR);
1117
1118      /* compute x1/x2 for the inner filled in switch */
1119      innerx1 = x1 + (switch_field_width - switch_width) / 2;
1120
1121      /* see if the switch is actually used */
1122      if (dip->mask & (1 << toggle))
1123      {
1124         float innery1 = (dip->state & (1 << toggle)) ? y1_on : y1_off;
1125         container->add_rect(innerx1, innery1, innerx1 + switch_width, innery1 + SINGLE_TOGGLE_SWITCH_HEIGHT,
1126                        (selectedmask & (1 << toggle)) ? UI_DIPSW_COLOR : UI_TEXT_COLOR,
1127                        PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA));
1128      }
1129      else
1130      {
1131         container->add_rect(innerx1, y1_off, innerx1 + switch_width, y1_on + SINGLE_TOGGLE_SWITCH_HEIGHT,
1132                        UI_UNAVAILABLE_COLOR,
1133                        PRIMFLAG_BLENDMODE(BLENDMODE_ALPHA));
1134      }
1135
1136      /* advance to the next switch */
1137      x1 += switch_field_width;
1138   }
1139}
1140
1141
1142/*-------------------------------------------------
1143    menu_analog - handle the analog settings menu
1144-------------------------------------------------*/
1145
1146void ui_menu_analog::handle()
1147{
1148   /* process the menu */
1149   const ui_menu_event *menu_event = process(UI_MENU_PROCESS_LR_REPEAT);
1150
1151   /* handle events */
1152   if (menu_event != NULL && menu_event->itemref != NULL)
1153   {
1154      analog_item_data *data = (analog_item_data *)menu_event->itemref;
1155      int newval = data->cur;
1156
1157      switch (menu_event->iptkey)
1158      {
1159         /* if selected, reset to default value */
1160         case IPT_UI_SELECT:
1161            newval = data->defvalue;
1162            break;
1163
1164         /* left decrements */
1165         case IPT_UI_LEFT:
1166            newval -= machine().input().code_pressed(KEYCODE_LSHIFT) ? 10 : 1;
1167            break;
1168
1169         /* right increments */
1170         case IPT_UI_RIGHT:
1171            newval += machine().input().code_pressed(KEYCODE_LSHIFT) ? 10 : 1;
1172            break;
1173      }
1174
1175      /* clamp to range */
1176      if (newval < data->min)
1177         newval = data->min;
1178      if (newval > data->max)
1179         newval = data->max;
1180
1181      /* if things changed, update */
1182      if (newval != data->cur)
1183      {
1184         ioport_field::user_settings settings;
1185
1186         /* get the settings and set the new value */
1187         data->field->get_user_settings(settings);
1188         switch (data->type)
1189         {
1190            case ANALOG_ITEM_KEYSPEED:      settings.delta = newval;        break;
1191            case ANALOG_ITEM_CENTERSPEED:   settings.centerdelta = newval;  break;
1192            case ANALOG_ITEM_REVERSE:       settings.reverse = newval;      break;
1193            case ANALOG_ITEM_SENSITIVITY:   settings.sensitivity = newval;  break;
1194         }
1195         data->field->set_user_settings(settings);
1196
1197         /* rebuild the menu */
1198         reset(UI_MENU_RESET_REMEMBER_POSITION);
1199      }
1200   }
1201}
1202
1203
1204/*-------------------------------------------------
1205    menu_analog_populate - populate the analog
1206    settings menu
1207-------------------------------------------------*/
1208
1209ui_menu_analog::ui_menu_analog(running_machine &machine, render_container *container) : ui_menu(machine, container)
1210{
1211}
1212
1213void ui_menu_analog::populate()
1214{
1215   ioport_field *field;
1216   ioport_port *port;
1217   astring text;
1218   astring subtext;
1219   astring prev_owner;
1220   bool first_entry = true;
1221
1222   /* loop over input ports and add the items */
1223   for (port = machine().ioport().first_port(); port != NULL; port = port->next())
1224      for (field = port->first_field(); field != NULL; field = field->next())
1225         if (field->is_analog() && field->enabled())
1226         {
1227            ioport_field::user_settings settings;
1228            int use_autocenter = false;
1229            int type;
1230
1231            /* based on the type, determine if we enable autocenter */
1232            switch (field->type())
1233            {
1234               case IPT_POSITIONAL:
1235               case IPT_POSITIONAL_V:
1236                  if (field->analog_wraps())
1237                     break;
1238
1239               case IPT_AD_STICK_X:
1240               case IPT_AD_STICK_Y:
1241               case IPT_AD_STICK_Z:
1242               case IPT_PADDLE:
1243               case IPT_PADDLE_V:
1244               case IPT_PEDAL:
1245               case IPT_PEDAL2:
1246               case IPT_PEDAL3:
1247                  use_autocenter = true;
1248                  break;
1249
1250               default:
1251                  break;
1252            }
1253
1254            /* get the user settings */
1255            field->get_user_settings(settings);
1256
1257            /* iterate over types */
1258            for (type = 0; type < ANALOG_ITEM_COUNT; type++)
1259               if (type != ANALOG_ITEM_CENTERSPEED || use_autocenter)
1260               {
1261                  analog_item_data *data;
1262                  UINT32 flags = 0;
1263                  astring name;
1264                  if (strcmp(field->device().tag(), prev_owner.cstr()) != 0)
1265                  {
1266                     if (first_entry)
1267                        first_entry = false;
1268                     else
1269                        item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
1270                     name.printf("[root%s]", field->device().tag());
1271                     item_append(name, NULL, 0, NULL);
1272                     prev_owner.cpy(field->device().tag());
1273                  }
1274
1275                  name.cpy(field->name());
1276                 
1277                  /* allocate a data item for tracking what this menu item refers to */
1278                  data = (analog_item_data *)m_pool_alloc(sizeof(*data));
1279                  data->field = field;
1280                  data->type = type;
1281
1282                  /* determine the properties of this item */
1283                  switch (type)
1284                  {
1285                     default:
1286                     case ANALOG_ITEM_KEYSPEED:
1287                        text.printf("%s Digital Speed", name.cstr());
1288                        subtext.printf("%d", settings.delta);
1289                        data->min = 0;
1290                        data->max = 255;
1291                        data->cur = settings.delta;
1292                        data->defvalue = field->delta();
1293                        break;
1294
1295                     case ANALOG_ITEM_CENTERSPEED:
1296                        text.printf("%s Autocenter Speed", name.cstr());
1297                        subtext.printf("%d", settings.centerdelta);
1298                        data->min = 0;
1299                        data->max = 255;
1300                        data->cur = settings.centerdelta;
1301                        data->defvalue = field->centerdelta();
1302                        break;
1303
1304                     case ANALOG_ITEM_REVERSE:
1305                        text.printf("%s Reverse", name.cstr());
1306                        subtext.cpy(settings.reverse ? "On" : "Off");
1307                        data->min = 0;
1308                        data->max = 1;
1309                        data->cur = settings.reverse;
1310                        data->defvalue = field->analog_reverse();
1311                        break;
1312
1313                     case ANALOG_ITEM_SENSITIVITY:
1314                        text.printf("%s Sensitivity", name.cstr());
1315                        subtext.printf("%d", settings.sensitivity);
1316                        data->min = 1;
1317                        data->max = 255;
1318                        data->cur = settings.sensitivity;
1319                        data->defvalue = field->sensitivity();
1320                        break;
1321                  }
1322
1323                  /* put on arrows */
1324                  if (data->cur > data->min)
1325                     flags |= MENU_FLAG_LEFT_ARROW;
1326                  if (data->cur < data->max)
1327                     flags |= MENU_FLAG_RIGHT_ARROW;
1328
1329                  /* append a menu item */
1330                  item_append(text, subtext, flags, data);
1331               }
1332         }
1333}
1334
1335ui_menu_analog::~ui_menu_analog()
1336{
1337}
1338
1339/*-------------------------------------------------
2321340    menu_bookkeeping - handle the bookkeeping
2331341    information menu
2341342-------------------------------------------------*/
trunk/src/emu/ui/miscmenu.h
r242959r242960
2525   virtual void handle();
2626};
2727
28class ui_menu_slot_devices : public ui_menu {
29public:
30   ui_menu_slot_devices(running_machine &machine, render_container *container);
31   virtual ~ui_menu_slot_devices();
32   virtual void populate();
33   virtual void handle();
34
35private:
36   device_slot_option *slot_get_current_option(device_slot_interface *slot);
37   int slot_get_current_index(device_slot_interface *slot);
38   int slot_get_length(device_slot_interface *slot);
39   const char *slot_get_next(device_slot_interface *slot);
40   const char *slot_get_prev(device_slot_interface *slot);
41   const char *slot_get_option(device_slot_interface *slot, int index);
42   void set_slot_device(device_slot_interface *slot, const char *val);
43};
44
2845class ui_menu_network_devices : public ui_menu {
2946public:
3047   ui_menu_network_devices(running_machine &machine, render_container *container);
r242959r242960
3350   virtual void handle();
3451};
3552
53class ui_menu_input_groups : public ui_menu {
54public:
55   ui_menu_input_groups(running_machine &machine, render_container *container);
56   virtual ~ui_menu_input_groups();
57   virtual void populate();
58   virtual void handle();
59};
60
61class ui_menu_input : public ui_menu {
62public:
63   ui_menu_input(running_machine &machine, render_container *container);
64   virtual ~ui_menu_input();
65   virtual void handle();
66
67protected:
68   enum {
69      INPUT_TYPE_DIGITAL = 0,
70      INPUT_TYPE_ANALOG = 1,
71      INPUT_TYPE_ANALOG_DEC = INPUT_TYPE_ANALOG + SEQ_TYPE_DECREMENT,
72      INPUT_TYPE_ANALOG_INC = INPUT_TYPE_ANALOG + SEQ_TYPE_INCREMENT,
73      INPUT_TYPE_TOTAL = INPUT_TYPE_ANALOG + SEQ_TYPE_TOTAL
74   };
75
76   /* internal input menu item data */
77   struct input_item_data {
78      input_item_data *   next;               /* pointer to next item in the list */
79      const void *        ref;                /* reference to type description for global inputs or field for game inputs */
80      input_seq_type      seqtype;            /* sequence type */
81      input_seq           seq;                /* copy of the live sequence */
82      const input_seq *   defseq;             /* pointer to the default sequence */
83      const char *        name;               /* pointer to the base name of the item */
84      const char *        owner_name;         /* pointer to the name of the owner of the item */
85      UINT32              sortorder;          /* sorting information */
86      UINT8               type;               /* type of port */
87   };
88
89   void populate_and_sort(struct input_item_data *itemlist);
90   virtual void update_input(struct input_item_data *seqchangeditem) = 0;
91   void toggle_none_default(input_seq &selected_seq, input_seq &original_seq, const input_seq &selected_defseq);
92
93protected:
94   const void *        pollingref;
95   input_seq_type      pollingseq;
96   input_item_data *   pollingitem;
97
98private:
99   UINT16              last_sortorder;
100   bool                record_next;
101   input_seq           starting_seq;
102
103   static int compare_items(const void *i1, const void *i2);
104};
105
106class ui_menu_input_general : public ui_menu_input {
107public:
108   ui_menu_input_general(running_machine &machine, render_container *container, int group);
109   virtual ~ui_menu_input_general();
110   virtual void populate();
111
112protected:
113   int group;
114   virtual void update_input(struct input_item_data *seqchangeditem);
115};
116
117class ui_menu_input_specific : public ui_menu_input {
118public:
119   ui_menu_input_specific(running_machine &machine, render_container *container);
120   virtual ~ui_menu_input_specific();
121   virtual void populate();
122
123protected:
124   virtual void update_input(struct input_item_data *seqchangeditem);
125};
126
127class ui_menu_settings : public ui_menu {
128public:
129   ui_menu_settings(running_machine &machine, render_container *container, UINT32 type);
130   virtual ~ui_menu_settings();
131   virtual void populate();
132   virtual void handle();
133
134protected:
135   /* DIP switch descriptor */
136   struct dip_descriptor {
137      dip_descriptor *    next;
138      const char *        name;
139      UINT32              mask;
140      UINT32              state;
141   };
142
143   dip_descriptor *    diplist;
144   int dipcount;
145   int type;
146};
147
148class ui_menu_settings_dip_switches : public ui_menu_settings {
149public:
150   ui_menu_settings_dip_switches(running_machine &machine, render_container *container);
151   virtual ~ui_menu_settings_dip_switches();
152
153   virtual void custom_render(void *selectedref, float top, float bottom, float x, float y, float x2, float y2);
154private:
155   void custom_render_one(float x1, float y1, float x2, float y2, const dip_descriptor *dip, UINT32 selectedmask);
156};
157
158class ui_menu_settings_driver_config : public ui_menu_settings {
159public:
160   ui_menu_settings_driver_config(running_machine &machine, render_container *container);
161   virtual ~ui_menu_settings_driver_config();
162};
163
164class ui_menu_analog : public ui_menu {
165public:
166   ui_menu_analog(running_machine &machine, render_container *container);
167   virtual ~ui_menu_analog();
168   virtual void populate();
169   virtual void handle();
170
171private:
172   enum {
173      ANALOG_ITEM_KEYSPEED = 0,
174      ANALOG_ITEM_CENTERSPEED,
175      ANALOG_ITEM_REVERSE,
176      ANALOG_ITEM_SENSITIVITY,
177      ANALOG_ITEM_COUNT
178   };
179
180   /* internal analog menu item data */
181   struct analog_item_data {
182      ioport_field *field;
183      int                 type;
184      int                 min, max;
185      int                 cur;
186      int                 defvalue;
187   };
188};
189
36190class ui_menu_bookkeeping : public ui_menu {
37191public:
38192   ui_menu_bookkeeping(running_machine &machine, render_container *container);
trunk/src/emu/ui/selgame.c
r242959r242960
1717#include "cheat.h"
1818#include "uiinput.h"
1919#include "ui/selgame.h"
20#include "ui/inputmap.h"
2120#include "ui/miscmenu.h"
2221#include "audit.h"
2322#include "crsshair.h"
r242959r242960
239238               emulator_info::get_gamesnoun(),
240239               emulator_info::get_configname(),
241240               emulator_info::get_appname(),emulator_info::get_appname() );
242      item_append(txt, NULL, MENU_FLAG_MULTILINE | MENU_FLAG_REDTEXT, NULL);
241      item_append(txt.cstr(), NULL, MENU_FLAG_MULTILINE | MENU_FLAG_REDTEXT, NULL);
243242      return;
244243   }
245244
trunk/src/emu/ui/slotopt.c
r242959r242960
1/*********************************************************************
2
3    ui/slotopt.c
4
5    Internal menu for the slot options.
6
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10*********************************************************************/
11
12#include "emu.h"
13
14#include "ui/ui.h"
15#include "ui/slotopt.h"
16#include "ui/devopt.h"
17
18
19/*-------------------------------------------------
20    ui_slot_get_current_option - returns
21-------------------------------------------------*/
22device_slot_option *ui_menu_slot_devices::slot_get_current_option(device_slot_interface *slot)
23{
24   const char *current;
25   if (slot->fixed())
26   {
27      current = slot->default_option();
28   }
29   else
30   {
31      astring temp;
32      current = machine().options().main_value(temp, slot->device().tag() + 1);
33   }
34
35   return slot->option(current);
36}
37
38/*-------------------------------------------------
39    ui_slot_get_current_index - returns
40-------------------------------------------------*/
41int ui_menu_slot_devices::slot_get_current_index(device_slot_interface *slot)
42{
43   const device_slot_option *current = slot_get_current_option(slot);
44
45   if (current != NULL)
46   {
47      int val = 0;
48      for (const device_slot_option *option = slot->first_option(); option != NULL; option = option->next())
49      {
50         if (option == current)
51            return val;
52
53         if (option->selectable())
54            val++;
55      }
56   }
57
58   return -1;
59}
60
61/*-------------------------------------------------
62    ui_slot_get_length - returns
63-------------------------------------------------*/
64int ui_menu_slot_devices::slot_get_length(device_slot_interface *slot)
65{
66   int val = 0;
67   for (const device_slot_option *option = slot->first_option(); option != NULL; option = option->next())
68      if (option->selectable())
69         val++;
70
71   return val;
72}
73
74/*-------------------------------------------------
75    ui_slot_get_next - returns
76-------------------------------------------------*/
77const char *ui_menu_slot_devices::slot_get_next(device_slot_interface *slot)
78{
79   int idx = slot_get_current_index(slot);
80   if (idx < 0)
81      idx = 0;
82   else
83      idx++;
84
85   if (idx >= slot_get_length(slot))
86      return "";
87
88   return slot_get_option(slot, idx);
89}
90
91/*-------------------------------------------------
92    ui_slot_get_prev - returns
93-------------------------------------------------*/
94const char *ui_menu_slot_devices::slot_get_prev(device_slot_interface *slot)
95{
96   int idx = slot_get_current_index(slot);
97   if (idx < 0)
98      idx = slot_get_length(slot) - 1;
99   else
100      idx--;
101
102   if (idx < 0)
103      return "";
104
105   return slot_get_option(slot, idx);
106}
107
108/*-------------------------------------------------
109    ui_slot_get_option - returns
110-------------------------------------------------*/
111const char *ui_menu_slot_devices::slot_get_option(device_slot_interface *slot, int index)
112{
113   if (index >= 0)
114   {
115      int val = 0;
116      for (const device_slot_option *option = slot->first_option(); option != NULL; option = option->next())
117      {
118         if (val == index)
119            return option->name();
120
121         if (option->selectable())
122            val++;
123      }
124   }
125
126   return "";
127}
128
129
130/*-------------------------------------------------
131    ui_set_use_natural_keyboard - specifies
132    whether the natural keyboard is active
133-------------------------------------------------*/
134
135void ui_menu_slot_devices::set_slot_device(device_slot_interface *slot, const char *val)
136{
137   astring error;
138   machine().options().set_value(slot->device().tag()+1, val, OPTION_PRIORITY_CMDLINE, error);
139   assert(!error);
140}
141
142/*-------------------------------------------------
143    menu_slot_devices_populate - populates the main
144    slot device menu
145-------------------------------------------------*/
146
147ui_menu_slot_devices::ui_menu_slot_devices(running_machine &machine, render_container *container) : ui_menu(machine, container)
148{
149}
150
151void ui_menu_slot_devices::populate()
152{
153   /* cycle through all devices for this system */
154   slot_interface_iterator iter(machine().root_device());
155   for (device_slot_interface *slot = iter.first(); slot != NULL; slot = iter.next())
156   {
157      /* record the menu item */
158      const device_slot_option *option = slot_get_current_option(slot);
159      astring opt_name;
160      if (option == NULL)
161         opt_name.cpy("------");
162      else
163      {
164         opt_name.cpy(option->name());
165         if (slot->fixed() || slot_get_length(slot) == 0)
166            opt_name.cat(" [internal]");
167      }
168
169      item_append(slot->device().tag() + 1, opt_name, (slot->fixed() || slot_get_length(slot) == 0) ? 0 : (MENU_FLAG_LEFT_ARROW | MENU_FLAG_RIGHT_ARROW), (void *)slot);
170   }
171   item_append(MENU_SEPARATOR_ITEM, NULL, 0, NULL);
172   item_append("Reset",  NULL, 0, (void *)1);
173}
174
175ui_menu_slot_devices::~ui_menu_slot_devices()
176{
177}
178
179/*-------------------------------------------------
180    ui_menu_slot_devices - menu that
181-------------------------------------------------*/
182
183void ui_menu_slot_devices::handle()
184{
185   /* process the menu */
186   const ui_menu_event *menu_event = process(0);
187
188   if (menu_event != NULL && menu_event->itemref != NULL)
189   {
190      if ((FPTR)menu_event->itemref == 1 && menu_event->iptkey == IPT_UI_SELECT)
191      {
192         machine().options().add_slot_options(false);
193         machine().schedule_hard_reset();
194      }
195      else if (menu_event->iptkey == IPT_UI_LEFT || menu_event->iptkey == IPT_UI_RIGHT)
196      {
197         device_slot_interface *slot = (device_slot_interface *)menu_event->itemref;
198         const char *val = (menu_event->iptkey == IPT_UI_LEFT) ? slot_get_prev(slot) : slot_get_next(slot);
199         set_slot_device(slot, val);
200         reset(UI_MENU_RESET_REMEMBER_REF);
201      }
202      else if (menu_event->iptkey == IPT_UI_SELECT)
203      {
204         device_slot_interface *slot = (device_slot_interface *)menu_event->itemref;
205         device_slot_option *option = slot_get_current_option(slot);
206         if (option)
207            ui_menu::stack_push(auto_alloc_clear(machine(), ui_menu_device_config(machine(), container, slot, option)));
208      }
209   }
210}
trunk/src/emu/ui/slotopt.h
r242959r242960
1/***************************************************************************
2
3    ui/slotopt.h
4 
5    Internal menu for the slot options.
6 
7    Copyright Nicola Salmoria and the MAME Team.
8    Visit http://mamedev.org for licensing and usage restrictions.
9
10***************************************************************************/
11
12#pragma once
13
14#ifndef __UI_SLOTOPT_H__
15#define __UI_SLOTOPT_H__
16
17//#include "drivenum.h"
18
19class ui_menu_slot_devices : public ui_menu {
20public:
21   ui_menu_slot_devices(running_machine &machine, render_container *container);
22   virtual ~ui_menu_slot_devices();
23   virtual void populate();
24   virtual void handle();
25
26private:
27   device_slot_option *slot_get_current_option(device_slot_interface *slot);
28   int slot_get_current_index(device_slot_interface *slot);
29   int slot_get_length(device_slot_interface *slot);
30   const char *slot_get_next(device_slot_interface *slot);
31   const char *slot_get_prev(device_slot_interface *slot);
32   const char *slot_get_option(device_slot_interface *slot, int index);
33   void set_slot_device(device_slot_interface *slot, const char *val);
34};
35
36#endif  /* __UI_SLOTOPT_H__ */
trunk/src/emu/ui/tapectrl.c
r242959r242960
5858   if (current_device())
5959   {     
6060      // name of tape
61      item_append(current_display_name(), current_device()->exists() ? current_device()->filename() : "No Tape Image loaded", current_display_flags(), TAPECMD_SELECT);
61      item_append(current_display_name().cstr(), current_device()->exists() ? current_device()->filename() : "No Tape Image loaded", current_display_flags(), TAPECMD_SELECT);
6262
6363      if (current_device()->exists())
6464      {
trunk/src/emu/video.c
r242959r242960
2020
2121#include "snap.lh"
2222
23#include "osdepend.h"
2423
24
2525//**************************************************************************
2626//  DEBUGGING
2727//**************************************************************************
trunk/src/emu/webengine.c
r242959r242960
1616#include "webengine.h"
1717#include "lua.hpp"
1818
19#include "osdepend.h"
2019
20
2121//**************************************************************************
2222//  WEB ENGINE
2323//**************************************************************************
trunk/src/lib/lib.mak
r242959r242960
3939#-------------------------------------------------
4040
4141UTILOBJS = \
42   $(OSDOBJ)/osdcore.o \
4342   $(LIBOBJ)/util/astring.o \
4443   $(LIBOBJ)/util/avhuff.o \
4544   $(LIBOBJ)/util/aviio.o \
r242959r242960
481480
482481$(LIBOBJ)/portmidi/%.o: $(3RDPARTY)/portmidi/%.c | $(OSPREBUILD)
483482   @echo Compiling $<...
484   $(CC) $(CDEFS) $(PMOPTS) $(CCOMFLAGS) $(CONLYFLAGS) $(INCPATH) -I$(3RDPARTY)/portmidi/pm_common -I$(3RDPARTY)/portmidi/porttime -c $< -o $@
483   $(CC) $(CDEFS) $(PMOPTS) $(CCOMFLAGS) $(CONLYFLAGS) -I$(3RDPARTY)/portmidi/pm_common -I$(3RDPARTY)/portmidi/porttime -c $< -o $@
485484
486485ifeq ($(TARGETOS),macosx)
487486$(LIBOBJ)/portmidi/%.o: $(3RDPARTY)/portmidi/%.m | $(OSPREBUILD)
488487   @echo Objective-C compiling $<...
489   $(CC) $(CDEFS) $(COBJFLAGS) $(CCOMFLAGS) $(INCPATH) -c $< -o $@
488   $(CC) $(CDEFS) $(COBJFLAGS) $(CCOMFLAGS) -c $< -o $@
490489endif
491490
492491#-------------------------------------------------
r242959r242960
526525   $(LIBOBJ)/lua/ltablib.o \
527526   $(LIBOBJ)/lua/loadlib.o \
528527   $(LIBOBJ)/lua/linit.o \
529   $(LIBOBJ)/lua/lutf8lib.o \
530528   $(LIBOBJ)/lua/lsqlite3/lsqlite3.o \
531529
532530$(OBJ)/liblua.a: $(LUAOBJS)
r242959r242960
546544
547545$(LIBOBJ)/lua/lsqlite3/%.o: $(3RDPARTY)/lsqlite3/%.c | $(OSPREBUILD)
548546   @echo Compiling $<...
549   $(CC) $(CDEFS) $(CCOMFLAGS) $(CONLYFLAGS) -DLUA_COMPAT_ALL -I$(3RDPARTY)/lua/src -I$(3RDPARTY) $(LUA_FLAGS) -c $< -o $@
547   $(CC) $(CDEFS) $(CCOMFLAGS) $(CONLYFLAGS) -DLUA_COMPAT_ALL $(LUA_FLAGS) -c $< -o $@
550548
551549#-------------------------------------------------
552550# web library objects
trunk/src/lib/util/chd.c
r242959r242960
26652665      // advance the read pointer
26662666      m_read_done_offset += numbytes;
26672667   }
2668   catch (chd_error& err)
2669   {
2670      fprintf(stderr, "CHD error occured: %s\n", chd_file::error_string(err));
2671      m_read_error = true;
2672   }
26732668   catch (std::exception& ex)
26742669   {
26752670      fprintf(stderr, "exception occured: %s\n", ex.what());
trunk/src/lib/util/corefile.h
r242959r242960
1414#define __COREFILE_H__
1515
1616#include <stdarg.h>
17#include "osdcore.h"
1718#include "astring.h"
1819#include "coretmpl.h"
1920
trunk/src/lib/util/options.h
r242959r242960
1111#ifndef __OPTIONS_H__
1212#define __OPTIONS_H__
1313
14#include "osdcore.h"
1415#include "corefile.h"
1516#include "tagmap.h"
1617
trunk/src/mame/audio/mario.c
r242959r242960
22#include "cpu/z80/z80.h"
33#include "cpu/mcs48/mcs48.h"
44#include "sound/ay8910.h"
5#include "sound/discrete.h"
56
67#include "includes/mario.h"
78
r242959r242960
3839#define I8035_P1_W_AH(M,B,D) I8035_P1_W(M,ACTIVEHIGH_PORT_BIT(I8035_P1_R(M),B,(D)))
3940#define I8035_P2_W_AH(M,B,D) I8035_P2_W(M,ACTIVEHIGH_PORT_BIT(I8035_P2_R(M),B,(D)))
4041
41
42#if !OLD_SOUND
43
44/* ---------------------------------------------------------------------- */
45/* mario sound                                                            */
46/* ---------------------------------------------------------------------- */
47static NETLIST_START(nl_mario_snd0)
48
49    RES(R17, RES_K(27))               /* 20 according to parts list           */
50                                      /* 27 verified, 30K in schematics       */
51    CAP(C14, CAP_U(4.7))              /* verified                             */
52
53    TTL_74123(2H_A)
54    NET_C(2H_A.VCC, V5)
55    NET_C(2H_A.GND, GND)
56    NET_C(SOUND0.Q, 2H_A.B)
57    NET_C(GND, 2H_A.A)
58    NET_C(2H_A.CLRQ, ttlhigh)         /* NOT IN SCHEMATICS                    */
59    DIODE(D1, "1N4148")               /* FIXME: try to identify */
60    TTL_7404_INVERT(1H_A, 2H_A.QQ)
61    NET_C(R17.1, V5)
62    NET_C(R17.2, D1.A, C14.1)
63    NET_C(D1.K, 2H_A.RC)
64    NET_C(C14.2, 2H_A.C)
65
66    RES(R6, RES_K(4.7))               /* verified                             */
67    CAP(C3, CAP_U(10))                /* verified                             */
68
69    NET_C(1H_A.Q, R6.1)
70    NET_C(R6.2, C3.1, 1J_A.FC)
71    NET_C(R6.2, 2J_A.FC)
72    NET_C(C3.2, GND)
73
74    //#define MR_C6       CAP_N(3.9)        /* verified                           */
75
76    SN74LS629(1J_A, CAP_N(3.9))
77    NET_C(1J_A.RNG, V5)
78    NET_C(1J_A.ENQ, ttllow)
79    NET_C(GND, 1J_A.GND)
80
81    //#define MR_C17      CAP_N(22)        /* verified                            */
82
83    SN74LS629(2J_A, CAP_N(22))
84    NET_C(2J_A.RNG, V5)
85    NET_C(2J_A.ENQ, ttllow)
86    NET_C(GND, 2J_A.GND)
87
88    TTL_7486_XOR(1K_A, 1J_A.Y, 2J_A.Y)
89    TTL_7408_AND(2K_A, 2H_A.Q, 1K_A)
90NETLIST_END()
91
92/* ---------------------------------------------------------------------- */
93/* skid sound                                                            */
94/* ---------------------------------------------------------------------- */
95
96// FIXME: Diodes are 1S953
97static NETLIST_START(nl_mario_snd7)
98
99    RES(R61, RES_K(47))
100    CAP(C41, CAP_U(4.7))              /* verified                             */
101
102    TTL_74123(4L_A)
103    NET_C(4L_A.VCC, V5)
104    NET_C(4L_A.GND, GND)
105    NET_C(SOUND7.Q, 4L_A.B)
106    NET_C(GND, 4L_A.A)
107    NET_C(4L_A.CLRQ, ttlhigh)         /* NOT IN SCHEMATICS                    */
108    DIODE(D10, "1N4148")               /* FIXME: try to identify */
109    TTL_7404_INVERT(4J_A, 4L_A.Q)
110    NET_C(R61.1, V5)
111    NET_C(R61.2, D10.A, C41.1)
112    NET_C(D10.K, 4L_A.RC)
113    NET_C(C41.2, 4L_A.C)
114
115    RES(R65, RES_K(10))
116    CAP(C44, CAP_U(3.3))              /* verified                             */
117
118    SN74LS629(4K_A, CAP_U(0.022))
119    NET_C(4K_A.RNG, V5)
120    NET_C(4K_A.ENQ, ttllow)
121    NET_C(GND, 4K_A.GND)
122    NET_C(R65.1, 4J_A.Q)
123    NET_C(R65.2, 4K_A.FC, C44.1)
124    NET_C(C44.2, GND)
125
126    CD_4020(3H, 4K_B.Y, ttllow, V5, GND)
127    TTL_7404_INVERT(4J_B, 3H.Q12)
128
129    RES(R64, RES_K(20))
130    CAP(C43, CAP_U(3.3))              /* verified                             */
131
132    SN74LS629(4K_B, CAP_U(0.0047))
133    NET_C(4K_B.RNG, V5)
134    NET_C(4K_B.ENQ, ttllow)
135    NET_C(GND, 4K_B.GND)
136    NET_C(R64.1, 4J_B.Q)
137    NET_C(R64.2, 4K_B.FC, C43.1)
138    NET_C(C43.2, GND)
139
140    TTL_7486_XOR(1K_C, 3H.Q4, 4K_A.Y)
141    TTL_7408_AND(2K_C, 4L_A.Q, 1K_C)
142
143NETLIST_END()
144
145/* ---------------------------------------------------------------------- */
146/* DAC sound                                                            */
147/* ---------------------------------------------------------------------- */
148static NETLIST_START(nl_mario_dac)
149    RES(R34, RES_M(2))
150    RES(R35, RES_M(1))
151    RES(R36, RES_M(1.8))
152    LM3900(3M_1)
153    NET_C(3M_1.VM, GND)
154    NET_C(3M_1.VP, V5)
155
156    NET_C(DAC.VOUT, R34.1)
157    NET_C(3M_1.MINUS, R34.2, R35.2)
158    NET_C(3M_1.OUT, R35.1)
159    NET_C(3M_1.PLUS, R36.1)
160    NET_C(R36.2, GND)
161
162    RES(R21, RES_M(1.8))
163    RES(R23, RES_K(10))
164    RES(R25, RES_K(10))
165    RES(R37, RES_K(750))
166    RES(R38, RES_K(360))
167    RES(R39, RES_K(750))
168
169    CAP(C18, CAP_P(100))
170    CAP(C19, CAP_U(10))
171    CAP(C20, CAP_U(1))
172    CAP(C30, CAP_P(100))
173
174    LM3900(3M_2)
175    NET_C(3M_2.VM, GND)
176    NET_C(3M_2.VP, V5)
177
178    NET_C(R35.1, C20.1)
179    NET_C(C20.2, R37.1)
180    NET_C(R37.2, R38.2, C18.1, R39.2)
181
182    NET_C(C18.2, GND)
183    NET_C(R38.1, C30.2, 3M_2.MINUS)
184    NET_C(3M_2.OUT, R39.1, C30.1)
185
186    NET_C(R21.1, 3M_2.PLUS)
187    NET_C(R21.2, C19.1, R25.2, R23.1)
188    NET_C(C19.2, R23.2, GND)
189    NET_C(R25.1, V5)
190NETLIST_END()
191
192static NETLIST_START(nl_mario)
193
194    /* Standard stuff */
195
196    SOLVER(Solver, 48000)
197    PARAM(Solver.ACCURACY, 1e-8)
198    PARAM(Solver.SOR_FACTOR, 1.0)
199    PARAM(Solver.GS_THRESHOLD, 5)
200    PARAM(Solver.GS_LOOPS, 4)
201    //PARAM(Solver.LTE,     5e-2) // Default is not enough for paddle control
202    PARAM(Solver.DYNAMIC_TS,  0)
203    ANALOG_INPUT(V5, 5)
204
205    TTL_INPUT(SOUND0, 1)
206    INCLUDE(nl_mario_snd0)
207
208    TTL_INPUT(SOUND7, 1)
209    INCLUDE(nl_mario_snd7)
210
211    R2R_DAC(DAC, 3.4, 10000.0, 8)
212    NET_C(DAC.VGND, GND)
213
214    INCLUDE(nl_mario_dac)
215
216    /* ---------------------------------------------------------------------- */
217    /* mixing                                                                 */
218    /* ---------------------------------------------------------------------- */
219
220    RES(R20, RES_K(22))               /* verified                             */
221    RES(R19, RES_K(22))               /* verified                             */
222    RES(R40, RES_K(22))               /* verified                             */
223    RES(R41, RES_K(100))              /* verified                             */
224    CAP(C31, CAP_U(0.022))            /*                             */
225
226    NET_C(2K_A.Q, R20.1)
227    NET_C(GND, R19.1) //FIXME
228    NET_C(2K_C.Q, R41.1)
229
230#if 1
231    RES(DUM, RES_K(22))
232    NET_C(R39.1, DUM.1)
233    NET_C(DUM.2, GND)
234    FRONTIER(front1, R39.1, R40.1)
235#else
236    NET_C(R39.1, R40.1)
237#endif
238
239    NET_C(R20.2, R19.2, R40.2, R41.2, C31.1)
240    NET_C(C31.2, GND)
241
242    CAP(C32, CAP_U(1))                /* verified                             */
243    RES(R42, RES_K(43))               /* verified                             */
244    RES(R43, RES_K(100))              /* verified                             */
245
246    NET_C(C31.1, C32.1)
247    NET_C(C32.2, R42.1, R43.2, Q10.B)
248    //NET_C(C32.2, R42.1, R43.2)
249    NET_C(R43.1, V5)
250    NET_C(R42.2, GND)
251#if 1
252    RES(R63, RES_K(1))                /*                                      */
253    RES(R62, 150)                     /*                                      */
254
255    QBJT_EB(Q10, "2SC1815")
256
257    NET_C(R62.2, GND)
258    NET_C(R62.1, Q10.E)
259
260    NET_C(R63.1, V5)
261    NET_C(R63.2, Q10.C)
262
263    CAP(C42, CAP_U(0.1))
264    CAP(C47, CAP_U(4.7))
265    RES(VR1, RES_K(10))
266
267    NET_C(C42.1, C47.1, R62.1)
268    NET_C(C42.2, GND)
269    NET_C(C47.2, VR1.1)
270    NET_C(VR1.2, GND)
271#endif
272    /* ---------------------------------------------------------------------- */
273    /* Output                                                                 */
274    /* ---------------------------------------------------------------------- */
275
276    RES(ROUT, 1000000)
277
278    //NET_C(Q10.C, ROUT.1)
279    //NET_C(R43.2, ROUT.1)
280    NET_C(VR1.1, ROUT.1)
281
282    NET_C(GND, ROUT.2)
283
284NETLIST_END()
285
286#else
28742/****************************************************************
28843 *
28944 * Discrete Sound defines
r242959r242960
635390   DISCRETE_TASK_END()
636391
637392DISCRETE_SOUND_END
638#endif
393
639394/****************************************************************
640395 *
641396 * EA / Banking
r242959r242960
743498
744499WRITE8_MEMBER(mario_state::mario_sh_sound_w)
745500{
746#if OLD_SOUND
747501   m_discrete->write(space, DS_DAC, data);
748#else
749   m_audio_dac->write(data);
750#endif
751502}
752503
753504WRITE8_MEMBER(mario_state::mario_sh_p1_w)
r242959r242960
787538/* Mario running sample */
788539WRITE8_MEMBER(mario_state::mario_sh1_w)
789540{
790#if OLD_SOUND
791541   m_discrete->write(space, DS_SOUND0_INP, 0);
792#else
793    m_audio_snd0->write(data);
794#endif
795542}
796543
797544/* Luigi running sample */
798545WRITE8_MEMBER(mario_state::mario_sh2_w)
799546{
800#if OLD_SOUND
801547   m_discrete->write(space, DS_SOUND1_INP, 0);
802#endif
803548}
804549
805550/* Misc samples */
r242959r242960
832577         I8035_P1_W_AH(space, 3, data & 1);
833578         break;
834579      case 7: /* skid */
835#if OLD_SOUND
836580         machine().device<discrete_device>("discrete")->write(space, DS_SOUND7_INP, data & 1);
837#else
838          m_audio_snd7->write((data & 1) ^ 1);
839#endif
840581         break;
841582   }
842583}
r242959r242960
885626   MCFG_CPU_IO_MAP(mario_sound_io_map)
886627
887628   MCFG_SPEAKER_STANDARD_MONO("mono")
888
889#if OLD_SOUND
890629   MCFG_SOUND_ADD("discrete", DISCRETE, 0)
891630   MCFG_DISCRETE_INTF(mario)
892631   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1)
893#else
894    MCFG_SOUND_ADD("snd_nl", NETLIST_SOUND, 48000)
895    MCFG_NETLIST_SETUP(nl_mario)
896    MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 1.0)
897632
898    MCFG_NETLIST_LOGIC_INPUT("snd_nl", "snd0", "SOUND0.IN", 0, 1)
899    MCFG_NETLIST_LOGIC_INPUT("snd_nl", "snd7", "SOUND7.IN", 0, 1)
900    MCFG_NETLIST_LOGIC_INPUT("snd_nl", "dac", "DAC.VAL", 0, 255)
901
902    MCFG_NETLIST_STREAM_OUTPUT("snd_nl", 0, "ROUT.1")
903    MCFG_NETLIST_ANALOG_MULT_OFFSET(150000.0, 0.0)
904#endif
905
906633MACHINE_CONFIG_END
907634
908635MACHINE_CONFIG_FRAGMENT( masao_audio )
trunk/src/mame/drivers/20pacgal.c
r242959r242960
192192// likewise the sound table.. is it being uploaded in a different format at 0x0c000?
193193// we also need the palette data because there is only a single rom on this pcb?
194194static ADDRESS_MAP_START( 25pacman_map, AS_PROGRAM, 8, _25pacman_state )
195
195196   AM_RANGE(0x04000, 0x047ff) AM_RAM AM_SHARE("video_ram")
197
196198   AM_RANGE(0x04800, 0x05fff) AM_RAM
199
197200   AM_RANGE(0x06000, 0x06fff) AM_WRITEONLY AM_SHARE("char_gfx_ram")
198201   AM_RANGE(0x07000, 0x0717f) AM_WRITE(sprite_ram_w)
199202//  AM_RANGE(0x08000, 0x09fff) AM_READ_BANK("bank1") AM_WRITE(ram_48000_w)
200203   AM_RANGE(0x08000, 0x09fff) AM_WRITENOP
201204   AM_RANGE(0x0a000, 0x0bfff) AM_WRITE(sprite_gfx_w)
205
202206   AM_RANGE(0x0c000, 0x0dfff) AM_WRITENOP // is this the sound waveforms in a different format?
203207   AM_RANGE(0x0e000, 0x0ffff) AM_WRITENOP
204208   AM_RANGE(0x1c000, 0x1ffff) AM_WRITENOP
209
205210   AM_RANGE(0x00000, 0x3ffff) AM_DEVREADWRITE("flash", amd_29lv200t_device, read, write )  // (always fall through if nothing else is mapped?)
206211
207212ADDRESS_MAP_END
r242959r242960
333338   PORT_INCLUDE(20pacgal)
334339
335340   PORT_MODIFY("SERVICE")
336   PORT_BIT( 0x02, IP_ACTIVE_LOW, IPT_UNKNOWN )
337   PORT_BIT( 0x04, IP_ACTIVE_LOW, IPT_UNKNOWN )
338   PORT_BIT( 0x08, IP_ACTIVE_LOW, IPT_UNKNOWN )
339   PORT_BIT( 0x10, IP_ACTIVE_LOW, IPT_BUTTON5 ) PORT_NAME ( "Service Volume Up" )
340   PORT_BIT( 0x20, IP_ACTIVE_LOW, IPT_BUTTON6 ) PORT_NAME ( "Service Volume Down" )
341   PORT_BIT( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN )
341   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNKNOWN )
342   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNKNOWN )
343   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNKNOWN )
344   PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNKNOWN )
345   PORT_BIT( 0x20, IP_ACTIVE_HIGH, IPT_UNKNOWN )
346   PORT_BIT( 0x40, IP_ACTIVE_HIGH, IPT_UNKNOWN )
342347INPUT_PORTS_END
343348
344349
trunk/src/mame/drivers/aleck64.c
r242959r242960
103103        JAPAN
104104
105105
106On bootup, they also mention 'T.L.S' (Temporary Landing System), which seems
107to be the hardware system, designed by Arika Co. Ltd.
106108
107109
108110PCB Layout
r242959r242960
183185   DECLARE_DRIVER_INIT(aleck64);
184186   DECLARE_WRITE32_MEMBER(aleck_dips_w);
185187   DECLARE_READ32_MEMBER(aleck_dips_r);
186   DECLARE_READ16_MEMBER(e90_prot_r);
187   DECLARE_WRITE16_MEMBER(e90_prot_w);
188188private:
189189   UINT32 m_dip_read_offset;
190190};
r242959r242960
311311   AM_RANGE(0x1fc00000, 0x1fc007bf) AM_ROM AM_REGION("user1", 0)   // PIF ROM
312312   AM_RANGE(0x1fc007c0, 0x1fc007ff) AM_DEVREADWRITE("rcp", n64_periphs, pif_ram_r, pif_ram_w)
313313
314   AM_RANGE(0xc0000000, 0xc07fffff) AM_RAM // SDRAM, Aleck 64 specific
314   /*
315       Surely this should mirror main ram? srmvs crashes, and
316       vivdolls overwrites it's memory test code if it does mirror
317   */
318   AM_RANGE(0xc0000000, 0xc07fffff) AM_RAM
315319
316320   AM_RANGE(0xc0800000, 0xc0800fff) AM_READWRITE(aleck_dips_r,aleck_dips_w)
317ADDRESS_MAP_END
321   AM_RANGE(0xd0000000, 0xd00fffff) AM_RAM // mtetrisc, write only, mirror?
318322
319/*
320 E90 protection handlers
321*/
322
323READ16_MEMBER(aleck64_state::e90_prot_r)
324{
325// offset 0 $800 = status ready, active high
326   return 0;
327}
328
329WRITE16_MEMBER(aleck64_state::e90_prot_w)
330{   
331   switch(offset*2)
332   {
333      case 0x16:
334         if(data != 6 && data != 7)
335            printf("! %04x %04x %08x\n",offset*2,data,mem_mask);
336
337         if(data & 1) // 0 -> 1 transition
338         {
339            //for(int i=0;i<0x1000;i+=4)
340            //   space.write_dword(0x007502f4+i,space.read_dword(0xd0000000+i));
341         }
342         break;
343      //0x1e bit 0 probably enables the chip
344      default:
345         printf("%04x %04x %08x\n",offset*2,data,mem_mask);
346         break;
347   }
348}
349
350static ADDRESS_MAP_START( e90_map, AS_PROGRAM, 32, aleck64_state )
351   AM_IMPORT_FROM( n64_map )
352   AM_RANGE(0xd0000000, 0xd0000fff) AM_RAM // x/y offsets
353   AM_RANGE(0xd0010000, 0xd0010fff) AM_RAM // RGB555 palette
354   AM_RANGE(0xd0030000, 0xd003001f) AM_READWRITE16(e90_prot_r, e90_prot_w,0xffffffff)
355323ADDRESS_MAP_END
356324
357325static ADDRESS_MAP_START( rsp_map, AS_PROGRAM, 32, aleck64_state )
r242959r242960
383351   PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_SENSITIVITY(30) PORT_KEYDELTA(30) PORT_PLAYER(1)
384352
385353   PORT_START("P1_ANALOG_Y")
386   PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_MINMAX(0x00,0xff) PORT_SENSITIVITY(30) PORT_KEYDELTA(30) PORT_PLAYER(1) PORT_REVERSE
354   PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_MINMAX(0xff,0x00) PORT_SENSITIVITY(30) PORT_KEYDELTA(30) PORT_PLAYER(1)
387355
388356   PORT_START("P2")
389357   PORT_BIT( 0x8000, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_PLAYER(2)          // Button A
r242959r242960
406374   PORT_BIT( 0xff, 0x80, IPT_AD_STICK_X ) PORT_SENSITIVITY(30) PORT_KEYDELTA(30) PORT_PLAYER(2)
407375
408376   PORT_START("P2_ANALOG_Y")
409   PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_MINMAX(0x00,0xff) PORT_SENSITIVITY(30) PORT_KEYDELTA(30) PORT_PLAYER(2) PORT_REVERSE
377   PORT_BIT( 0xff, 0x80, IPT_AD_STICK_Y ) PORT_MINMAX(0xff,0x00) PORT_SENSITIVITY(30) PORT_KEYDELTA(30) PORT_PLAYER(2)
410378
411379   PORT_START("IN0")
412380   PORT_DIPNAME( 0x80000000, 0x80000000, "DIPSW1 #8" ) PORT_DIPLOCATION("SW1:8")
r242959r242960
470438static INPUT_PORTS_START( 11beat )
471439   PORT_INCLUDE( aleck64 )
472440
441   PORT_MODIFY("P1_ANALOG_Y")
442   PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
443   PORT_MODIFY("P2_ANALOG_X")
444   PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
445   PORT_MODIFY("P2_ANALOG_Y")
446   PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
447   PORT_MODIFY("P1_ANALOG_X")
448   PORT_BIT( 0xff, IP_ACTIVE_HIGH, IPT_UNUSED )
449
473450   PORT_MODIFY("P1")
474451   PORT_BIT( 0x2000, IP_ACTIVE_HIGH, IPT_UNUSED )
475   PORT_BIT( 0x0f00, IP_ACTIVE_LOW, IPT_UNUSED ) // "joystick type error" happens because game expects D-PADs to be unconnected
476452   PORT_BIT( 0x0020, IP_ACTIVE_HIGH, IPT_UNUSED )
477453   PORT_BIT( 0x0010, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_PLAYER(1)
478454   PORT_BIT( 0x0008, IP_ACTIVE_HIGH, IPT_UNUSED )
r242959r242960
482458
483459   PORT_MODIFY("P2")
484460   PORT_BIT( 0x2000, IP_ACTIVE_HIGH, IPT_UNUSED )
485   PORT_BIT( 0x0f00, IP_ACTIVE_LOW, IPT_UNUSED ) // "joystick type error" happens because game expects D-PADs to be unconnected
486461   PORT_BIT( 0x0020, IP_ACTIVE_HIGH, IPT_UNUSED )
487462   PORT_BIT( 0x0010, IP_ACTIVE_HIGH, IPT_BUTTON3 ) PORT_PLAYER(2)
488463   PORT_BIT( 0x0008, IP_ACTIVE_HIGH, IPT_UNUSED )
489464   PORT_BIT( 0x0004, IP_ACTIVE_HIGH, IPT_UNUSED )
490465   PORT_BIT( 0x0002, IP_ACTIVE_HIGH, IPT_UNUSED )
491466   PORT_BIT( 0x0001, IP_ACTIVE_HIGH, IPT_BUTTON4 ) PORT_PLAYER(2)
467
492468INPUT_PORTS_END
493469
494470static INPUT_PORTS_START( mtetrisc )
r242959r242960
873849   MCFG_N64_PERIPHS_ADD("rcp");
874850MACHINE_CONFIG_END
875851
876static MACHINE_CONFIG_DERIVED( a64_e90, aleck64 )
877   MCFG_CPU_MODIFY("maincpu")
878   MCFG_CPU_PROGRAM_MAP(e90_map)
879MACHINE_CONFIG_END
880
881852DRIVER_INIT_MEMBER(aleck64_state,aleck64)
882853{
883854   UINT8 *rom = memregion("user2")->base();
r242959r242960
910881   PIF_BOOTROM
911882
912883   ROM_REGION32_BE( 0x4000000, "user2", 0 )
913   ROM_LOAD16_WORD_SWAP( "nus-zhaj.u3", 0x000000, 0x0800000, CRC(02faa8a7) SHA1(824911452639cedf6a8186c05cd046e61fc98896) )
884   ROM_LOAD16_WORD_SWAP( "nus-zhaj.u3", 0x000000, 0x0800000, BAD_DUMP CRC(95258ba2) SHA1(0299b8fb9a8b1b24428d0f340f6bf1cfaf99c672) )
914885
915886   ROM_REGION16_BE( 0x80, "normpoint", 0 )
916887   ROM_LOAD( "normpnt.rom", 0x00, 0x80, CRC(e7f2a005) SHA1(c27b4a364a24daeee6e99fd286753fd6216362b4) )
r242959r242960
11111082GAME( 1998, aleck64,  0,        aleck64, aleck64, aleck64_state,  aleck64, ROT0, "Nintendo / Seta", "Aleck64 PIF BIOS", GAME_IS_BIOS_ROOT)
11121083
11131084// games
1114GAME( 1998, 11beat,   aleck64,  aleck64, 11beat, aleck64_state,   aleck64, ROT0, "Hudson", "Eleven Beat", GAME_NOT_WORKING ) // crashes at kick off / during attract with DRC
1115GAME( 1998, mtetrisc, aleck64,  a64_e90, mtetrisc, aleck64_state, aleck64, ROT0, "Capcom", "Magical Tetris Challenge (981009 Japan)", GAME_NOT_WORKING|GAME_IMPERFECT_GRAPHICS )
1085GAME( 1998, 11beat,   aleck64,  aleck64, 11beat, aleck64_state,   aleck64, ROT0, "Hudson", "Eleven Beat", GAME_NOT_WORKING|GAME_NO_SOUND )
1086GAME( 1998, mtetrisc, aleck64,  aleck64, mtetrisc, aleck64_state, aleck64, ROT0, "Capcom", "Magical Tetris Challenge (981009 Japan)", GAME_NOT_WORKING|GAME_IMPERFECT_GRAPHICS )
11161087GAME( 1998, starsldr, aleck64,  aleck64, starsldr, aleck64_state, aleck64, ROT0, "Hudson / Seta", "Star Soldier: Vanishing Earth", GAME_IMPERFECT_GRAPHICS )
11171088GAME( 1998, vivdolls, aleck64,  aleck64, aleck64, aleck64_state,  aleck64, ROT0, "Visco", "Vivid Dolls", GAME_IMPERFECT_GRAPHICS )
11181089GAME( 1999, srmvs,    aleck64,  aleck64, srmvs, aleck64_state,    aleck64, ROT0, "Seta", "Super Real Mahjong VS", GAME_NOT_WORKING|GAME_IMPERFECT_GRAPHICS )
trunk/src/mame/drivers/chihiro.c
r242959r242960
369369#include "debug/debugcon.h"
370370#include "debug/debugcmd.h"
371371#include "debug/debugcpu.h"
372#include "osdcore.h"
372373#include "includes/chihiro.h"
373374
374375#define LOG_PCI
trunk/src/mame/drivers/dec0.c
r242959r242960
526526
527527
528528
529void dec0_automat_state::machine_start()
530{
531   save_item(NAME(m_automat_adpcm_byte));
532   save_item(NAME(m_automat_msm5205_vclk_toggle));
533   save_item(NAME(m_automat_scroll_regs));   
534}
535529
536530
531
537532/* swizzle the palette writes around so we can use the same gfx plane ordering as the originals */
538533READ16_MEMBER( dec0_automat_state::automat_palette_r )
539534{
r242959r242960
30393034   return 0xffff;
30403035}
30413036
3037READ16_MEMBER(dec0_state::ffantasybl_vblank_r)
3038{
3039   return ioport("VBLANK")->read();
3040}
3041
30423042DRIVER_INIT_MEMBER(dec0_state,ffantasybl)
30433043{
30443044   m_maincpu->space(AS_PROGRAM).install_ram(0x24c880, 0x24cbff); // what is this? layer 3-related??
30453045
30463046   m_maincpu->space(AS_PROGRAM).install_read_handler(0x00242024, 0x00242025, read16_delegate(FUNC(dec0_state::ffantasybl_242024_r),this));
3047   m_maincpu->space(AS_PROGRAM).install_read_port(0x00ff87ee, 0x00ff87ef, "VBLANK");
3047   m_maincpu->space(AS_PROGRAM).install_read_handler(0x00ff87ee, 0x00ff87ef, read16_delegate(FUNC(dec0_state::ffantasybl_vblank_r),this));
30483048}
30493049
30503050/******************************************************************************/
30513051
30523052//    YEAR, NAME,       PARENT,   MACHINE,  INPUT,    STATE/DEVICE,   INIT, MONITOR,COMPANY,                 FULLNAME,            FLAGS
3053GAME( 1987, hbarrel,    0,        hbarrel,  hbarrel,  dec0_state,  hbarrel, ROT270, "Data East USA",         "Heavy Barrel (US)", GAME_SUPPORTS_SAVE )
3054GAME( 1987, hbarrelw,   hbarrel,  hbarrel,  hbarrel,  dec0_state,  hbarrel, ROT270, "Data East Corporation", "Heavy Barrel (World)", GAME_SUPPORTS_SAVE )
3055GAME( 1988, baddudes,   0,        baddudes, baddudes, dec0_state, baddudes, ROT0,   "Data East USA",         "Bad Dudes vs. Dragonninja (US)", GAME_SUPPORTS_SAVE )
3056GAME( 1988, drgninja,   baddudes, baddudes, drgninja, dec0_state, baddudes, ROT0,   "Data East Corporation", "Dragonninja (Japan)", GAME_SUPPORTS_SAVE )
3057GAME( 1988, birdtry,    0,        birdtry,  birdtry,  dec0_state,  birdtry, ROT270, "Data East Corporation", "Birdie Try (Japan)", GAME_UNEMULATED_PROTECTION | GAME_SUPPORTS_SAVE )
3058GAME( 1988, robocop,    0,        robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East Corporation", "Robocop (World revision 4)", GAME_SUPPORTS_SAVE )
3059GAME( 1988, robocopw,   robocop,  robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East Corporation", "Robocop (World revision 3)", GAME_SUPPORTS_SAVE )
3060GAME( 1988, robocopj,   robocop,  robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East Corporation", "Robocop (Japan)", GAME_SUPPORTS_SAVE )
3061GAME( 1988, robocopu,   robocop,  robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East USA",         "Robocop (US revision 1)", GAME_SUPPORTS_SAVE )
3062GAME( 1988, robocopu0,  robocop,  robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East USA",         "Robocop (US revision 0)", GAME_SUPPORTS_SAVE )
3063GAME( 1989, hippodrm,   0,        hippodrm, hippodrm, dec0_state, hippodrm, ROT0,   "Data East USA",         "Hippodrome (US)", GAME_SUPPORTS_SAVE )
3064GAME( 1989, ffantasy,   hippodrm, hippodrm, ffantasy, dec0_state, hippodrm, ROT0,   "Data East Corporation", "Fighting Fantasy (Japan revision 2)", GAME_SUPPORTS_SAVE )
3065GAME( 1989, ffantasya,  hippodrm, hippodrm, ffantasy, dec0_state, hippodrm, ROT0,   "Data East Corporation", "Fighting Fantasy (Japan)", GAME_SUPPORTS_SAVE )
3066GAME( 1989, secretag,   0,        slyspy,   slyspy,   dec0_state,   slyspy, ROT0,   "Data East Corporation", "Secret Agent (World revision 3)", GAME_SUPPORTS_SAVE )
3067GAME( 1989, secretagj,  secretag, slyspy,   slyspy,   dec0_state,   slyspy, ROT0,   "Data East Corporation", "Secret Agent (Japan revision 2)", GAME_SUPPORTS_SAVE )
3068GAME( 1989, slyspy,     secretag, slyspy,   slyspy,   dec0_state,   slyspy, ROT0,   "Data East USA",         "Sly Spy (US revision 3)", GAME_SUPPORTS_SAVE )
3069GAME( 1989, slyspy2,    secretag, slyspy,   slyspy,   dec0_state,   slyspy, ROT0,   "Data East USA",         "Sly Spy (US revision 2)", GAME_SUPPORTS_SAVE )
3070GAME( 1989, midres,     0,        midres,   midres,   driver_device,     0, ROT0,   "Data East Corporation", "Midnight Resistance (World)", GAME_SUPPORTS_SAVE )
3071GAME( 1989, midresu,    midres,   midres,   midresu,  driver_device,     0, ROT0,   "Data East USA",         "Midnight Resistance (US)", GAME_SUPPORTS_SAVE )
3072GAME( 1989, midresj,    midres,   midres,   midresu,  driver_device,     0, ROT0,   "Data East Corporation", "Midnight Resistance (Japan)", GAME_SUPPORTS_SAVE )
3073GAME( 1990, bouldash,   0,        slyspy,   bouldash, dec0_state,   slyspy, ROT0,   "Data East Corporation (licensed from First Star)", "Boulder Dash / Boulder Dash Part 2 (World)", GAME_SUPPORTS_SAVE )
3074GAME( 1990, bouldashj,  bouldash, slyspy,   bouldash, dec0_state,   slyspy, ROT0,   "Data East Corporation (licensed from First Star)", "Boulder Dash / Boulder Dash Part 2 (Japan)", GAME_SUPPORTS_SAVE )
3053GAME( 1987, hbarrel,    0,        hbarrel,  hbarrel,  dec0_state,  hbarrel, ROT270, "Data East USA",         "Heavy Barrel (US)", 0 )
3054GAME( 1987, hbarrelw,   hbarrel,  hbarrel,  hbarrel,  dec0_state,  hbarrel, ROT270, "Data East Corporation", "Heavy Barrel (World)", 0 )
3055GAME( 1988, baddudes,   0,        baddudes, baddudes, dec0_state, baddudes, ROT0,   "Data East USA",         "Bad Dudes vs. Dragonninja (US)", 0 )
3056GAME( 1988, drgninja,   baddudes, baddudes, drgninja, dec0_state, baddudes, ROT0,   "Data East Corporation", "Dragonninja (Japan)", 0 )
3057GAME( 1988, birdtry,    0,        birdtry,  birdtry,  dec0_state,  birdtry, ROT270, "Data East Corporation", "Birdie Try (Japan)", GAME_UNEMULATED_PROTECTION )
3058GAME( 1988, robocop,    0,        robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East Corporation", "Robocop (World revision 4)", 0 )
3059GAME( 1988, robocopw,   robocop,  robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East Corporation", "Robocop (World revision 3)", 0 )
3060GAME( 1988, robocopj,   robocop,  robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East Corporation", "Robocop (Japan)", 0 )
3061GAME( 1988, robocopu,   robocop,  robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East USA",         "Robocop (US revision 1)", 0 )
3062GAME( 1988, robocopu0,  robocop,  robocop,  robocop,  dec0_state,  robocop, ROT0,   "Data East USA",         "Robocop (US revision 0)", 0 )
3063GAME( 1989, hippodrm,   0,        hippodrm, hippodrm, dec0_state, hippodrm, ROT0,   "Data East USA",         "Hippodrome (US)", 0 )
3064GAME( 1989, ffantasy,   hippodrm, hippodrm, ffantasy, dec0_state, hippodrm, ROT0,   "Data East Corporation", "Fighting Fantasy (Japan revision 2)", 0 )
3065GAME( 1989, ffantasya,  hippodrm, hippodrm, ffantasy, dec0_state, hippodrm, ROT0,   "Data East Corporation", "Fighting Fantasy (Japan)", 0 )
3066GAME( 1989, secretag,   0,        slyspy,   slyspy,   dec0_state,   slyspy, ROT0,   "Data East Corporation", "Secret Agent (World revision 3)", 0 )
3067GAME( 1989, secretagj,  secretag, slyspy,   slyspy,   dec0_state,   slyspy, ROT0,   "Data East Corporation", "Secret Agent (Japan revision 2)", 0 )
3068GAME( 1989, slyspy,     secretag, slyspy,   slyspy,   dec0_state,   slyspy, ROT0,   "Data East USA",         "Sly Spy (US revision 3)", 0 )
3069GAME( 1989, slyspy2,    secretag, slyspy,   slyspy,   dec0_state,   slyspy, ROT0,   "Data East USA",         "Sly Spy (US revision 2)", 0 )
3070GAME( 1989, midres,     0,        midres,   midres,   driver_device,     0, ROT0,   "Data East Corporation", "Midnight Resistance (World)", 0 )
3071GAME( 1989, midresu,    midres,   midres,   midresu,  driver_device,     0, ROT0,   "Data East USA",         "Midnight Resistance (US)", 0 )
3072GAME( 1989, midresj,    midres,   midres,   midresu,  driver_device,     0, ROT0,   "Data East Corporation", "Midnight Resistance (Japan)", 0 )
3073GAME( 1990, bouldash,   0,        slyspy,   bouldash, dec0_state,   slyspy, ROT0,   "Data East Corporation (licensed from First Star)", "Boulder Dash / Boulder Dash Part 2 (World)", 0 )
3074GAME( 1990, bouldashj,  bouldash, slyspy,   bouldash, dec0_state,   slyspy, ROT0,   "Data East Corporation (licensed from First Star)", "Boulder Dash / Boulder Dash Part 2 (Japan)", 0 )
30753075
30763076// bootlegs
30773077
30783078// more or less just an unprotected versions of the game, everything intact
3079GAME( 1988, robocopb,   robocop,  robocopb, robocop, dec0_state,  robocop,  ROT0,   "bootleg", "Robocop (World bootleg)", GAME_SUPPORTS_SAVE )
3080GAME( 1988, drgninjab,  baddudes, baddudes, drgninja, dec0_state, baddudes, ROT0,   "bootleg", "Dragonninja (bootleg)", GAME_SUPPORTS_SAVE )
3079GAME( 1988, robocopb,   robocop,  robocopb, robocop, dec0_state,  robocop,  ROT0,   "bootleg", "Robocop (World bootleg)", 0)
3080GAME( 1988, drgninjab,  baddudes, baddudes, drgninja, dec0_state, baddudes, ROT0,   "bootleg", "Dragonninja (bootleg)", 0 )
30813081
30823082// this is a common bootleg board
3083GAME( 1989, midresb,    midres,   midresb,  midresb, dec0_state,  midresb,  ROT0,   "bootleg", "Midnight Resistance (bootleg with 68705)", GAME_SUPPORTS_SAVE ) // need to hook up 68705?
3084GAME( 1989, ffantasybl, hippodrm, ffantasybl, ffantasybl, dec0_state, ffantasybl,   ROT0,   "bootleg", "Fighting Fantasy (bootleg with 68705)", GAME_IMPERFECT_GRAPHICS | GAME_SUPPORTS_SAVE ) // 68705 not dumped, might be the same as midresb
3083GAME( 1989, midresb,    midres,   midresb,  midresb, dec0_state,  midresb,  ROT0,   "bootleg", "Midnight Resistance (bootleg with 68705)", 0 ) // need to hook up 68705?
3084GAME( 1989, ffantasybl, hippodrm, ffantasybl, ffantasybl, dec0_state, ffantasybl,   ROT0,   "bootleg", "Fighting Fantasy (bootleg with 68705)", GAME_IMPERFECT_GRAPHICS ) // 68705 not dumped, might be the same as midresb
30853085/* A Bad Dudes bootleg with 68705 like the midres and ffantasy ones exists, but is not dumped */
30863086
30873087// these are different to the above but quite similar to each other
3088GAME( 1988, automat,    robocop,  automat,  robocop, dec0_state,  robocop,  ROT0,   "bootleg", "Automat (bootleg of Robocop)", GAME_NOT_WORKING | GAME_SUPPORTS_SAVE ) // sound rom / music from section z with mods for ADPCM?
3089GAME( 1989, secretab,   secretag, secretab, slyspy, dec0_state,   slyspy,   ROT0,   "bootleg", "Secret Agent (bootleg)", GAME_NOT_WORKING | GAME_SUPPORTS_SAVE )
3088GAME( 1988, automat,    robocop,  automat,  robocop, dec0_state,  robocop,  ROT0,   "bootleg", "Automat (bootleg of Robocop)", GAME_NOT_WORKING ) // sound rom / music from section z with mods for ADPCM?
3089GAME( 1989, secretab,   secretag, secretab, slyspy, dec0_state,   slyspy,   ROT0,   "bootleg", "Secret Agent (bootleg)", GAME_NOT_WORKING )
trunk/src/mame/drivers/eolith.c
r242959r242960
103103
104104#include "machine/eepromser.h"
105105#include "includes/eolith.h"
106#include "includes/eolithsp.h"
106107
107108
109
110
111
108112/*************************************
109113 *
110114 *  Control
r242959r242960
121125       bit 8 = ???
122126       bit 9 = ???
123127   */
124   speedup_read();
128   eolith_speedup_read(space);
125129
126130   return (m_in0->read() & ~0x300) | (machine().rand() & 0x300);
127131}
r242959r242960
161165   m_sound_data = data;
162166   m_soundcpu->set_input_line(MCS51_INT0_LINE, ASSERT_LINE);
163167
164   machine().scheduler().boost_interleave(attotime::zero, attotime::from_usec(250));
168   space.machine().scheduler().boost_interleave(attotime::zero, attotime::from_usec(250));
165169}
166170
167171
r242959r242960
14871491
14881492DRIVER_INIT_MEMBER(eolith_state,eolith)
14891493{
1490   init_speedup();
1494   init_eolith_speedup(machine());
14911495
14921496   // Sound CPU -> QS1000 CPU serial link
14931497   m_soundcpu->i8051_set_serial_tx_callback(write8_delegate(FUNC(eolith_state::soundcpu_to_qs1000),this));
14941498
14951499   // Configure the sound ROM banking
14961500   membank("sound_bank")->configure_entries(0, 16, memregion("sounddata")->base(), 0x8000);
1497   
1498   save_item(NAME(m_sound_data));
14991501}
15001502
15011503DRIVER_INIT_MEMBER(eolith_state,landbrk)
r242959r242960
15671569 *
15681570 *************************************/
15691571
1570GAME( 1998, linkypip,  0,        eolith45, linkypip,  eolith_state, eolith,   ROT0, "Eolith", "Linky Pipe", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1571GAME( 1998, ironfort,  0,        ironfort, ironfort,  eolith_state, eolith,   ROT0, "Eolith", "Iron Fortress", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1572GAME( 1998, ironfortj, ironfort, ironfort, ironfortj, eolith_state, eolith,   ROT0, "Eolith", "Iron Fortress (Japan)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1573GAME( 1998, hidnctch,  0,        eolith45, hidnctch,  eolith_state, eolith,   ROT0, "Eolith", "Hidden Catch (World) / Tul Lin Gu Lim Chat Ki '98 (Korea) (pcb ver 3.03)",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE ) // or Teurrin Geurim Chajgi '98
1574GAME( 1998, raccoon,   0,        eolith45, raccoon,   eolith_state, eolith,   ROT0, "Eolith", "Raccoon World", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1575GAME( 1998, puzzlekg,  0,        eolith45, puzzlekg,  eolith_state, eolith,   ROT0, "Eolith", "Puzzle King (Dance & Puzzle)",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1576GAME( 1999, candy,     0,        eolith50, candy,     eolith_state, eolith,   ROT0, "Eolith", "Candy Candy",  GAME_IMPERFECT_GRAPHICS | GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1577GAME( 1999, hidctch2,  0,        eolith50, hidctch2,  eolith_state, hidctch2, ROT0, "Eolith", "Hidden Catch 2 (pcb ver 3.03) (Kor/Eng) (AT89c52 protected)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1578GAME( 1999, hidctch2a, hidctch2, eolith50, hidctch2,  eolith_state, eolith,   ROT0, "Eolith", "Hidden Catch 2 (pcb ver 1.00) (Kor/Eng/Jpn/Chi)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1579GAME( 1999, hidnc2k,   0,        eolith50, hidctch2,  eolith_state, hidnc2k,  ROT0, "Eolith", "Hidden Catch 2000 (AT89c52 protected)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1580GAME( 1999, landbrk,   0,        eolith45, landbrk,   eolith_state, landbrk,  ROT0, "Eolith", "Land Breaker (World) / Miss Tang Ja Ru Gi (Korea) (pcb ver 3.02)",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE ) // or Miss Ttang Jjareugi
1581GAME( 1999, landbrka,  landbrk,  eolith45, landbrk,   eolith_state, landbrka, ROT0, "Eolith", "Land Breaker (World) / Miss Tang Ja Ru Gi (Korea) (pcb ver 3.03) (AT89c52 protected)",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE ) // or Miss Ttang Jjareugi
1582GAME( 1999, nhidctch,  0,        eolith45, hidctch2,  eolith_state, eolith,   ROT0, "Eolith", "New Hidden Catch (World) / New Tul Lin Gu Lim Chat Ki '98 (Korea) (pcb ver 3.02)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE ) // or New Teurrin Geurim Chajgi '98
1583GAME( 1999, penfan,    0,        eolith45, penfan,    eolith_state, eolith,   ROT0, "Eolith", "Penfan Girls - Step1. Mild Mind (set 1)",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE ) // alt title of Ribbon
1584GAME( 1999, penfana,   penfan,   eolith45, penfan,    eolith_state, eolith,   ROT0, "Eolith", "Penfan Girls - Step1. Mild Mind (set 2)",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1585GAME( 2000, stealsee,  0,        eolith45, stealsee,  eolith_state, eolith,   ROT0, "Moov Generation / Eolith", "Steal See",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1586GAME( 2000, hidctch3,  0,        eolith50, hidctch3,  eolith_state, hidctch3, ROT0, "Eolith", "Hidden Catch 3 (ver 1.00 / pcb ver 3.05)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1587GAME( 2001, fort2b,    0,        eolith50, common,    eolith_state, eolith,   ROT0, "Eolith", "Fortress 2 Blue Arcade (ver 1.01 / pcb ver 3.05)",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1588GAME( 2001, fort2ba,   fort2b,   eolith50, common,    eolith_state, eolith,   ROT0, "Eolith", "Fortress 2 Blue Arcade (ver 1.00 / pcb ver 3.05)",  GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1572GAME( 1998, linkypip,  0,        eolith45, linkypip,  eolith_state, eolith,   ROT0, "Eolith", "Linky Pipe", GAME_IMPERFECT_SOUND )
1573GAME( 1998, ironfort,  0,        ironfort, ironfort,  eolith_state, eolith,   ROT0, "Eolith", "Iron Fortress", GAME_IMPERFECT_SOUND )
1574GAME( 1998, ironfortj, ironfort, ironfort, ironfortj, eolith_state, eolith,   ROT0, "Eolith", "Iron Fortress (Japan)", GAME_IMPERFECT_SOUND )
1575GAME( 1998, hidnctch,  0,        eolith45, hidnctch,  eolith_state, eolith,   ROT0, "Eolith", "Hidden Catch (World) / Tul Lin Gu Lim Chat Ki '98 (Korea) (pcb ver 3.03)",  GAME_IMPERFECT_SOUND ) // or Teurrin Geurim Chajgi '98
1576GAME( 1998, raccoon,   0,        eolith45, raccoon,   eolith_state, eolith,   ROT0, "Eolith", "Raccoon World", GAME_IMPERFECT_SOUND )
1577GAME( 1998, puzzlekg,  0,        eolith45, puzzlekg,  eolith_state, eolith,   ROT0, "Eolith", "Puzzle King (Dance & Puzzle)",  GAME_IMPERFECT_SOUND )
1578GAME( 1999, candy,     0,        eolith50, candy,     eolith_state, eolith,   ROT0, "Eolith", "Candy Candy",  GAME_IMPERFECT_GRAPHICS | GAME_IMPERFECT_SOUND )
1579GAME( 1999, hidctch2,  0,        eolith50, hidctch2,  eolith_state, hidctch2, ROT0, "Eolith", "Hidden Catch 2 (pcb ver 3.03) (Kor/Eng) (AT89c52 protected)", GAME_IMPERFECT_SOUND )
1580GAME( 1999, hidctch2a, hidctch2, eolith50, hidctch2,  eolith_state, eolith,   ROT0, "Eolith", "Hidden Catch 2 (pcb ver 1.00) (Kor/Eng/Jpn/Chi)", GAME_IMPERFECT_SOUND )
1581GAME( 1999, hidnc2k,   0,        eolith50, hidctch2,  eolith_state, hidnc2k,  ROT0, "Eolith", "Hidden Catch 2000 (AT89c52 protected)", GAME_IMPERFECT_SOUND )
1582GAME( 1999, landbrk,   0,        eolith45, landbrk,   eolith_state, landbrk,  ROT0, "Eolith", "Land Breaker (World) / Miss Tang Ja Ru Gi (Korea) (pcb ver 3.02)",  GAME_IMPERFECT_SOUND ) // or Miss Ttang Jjareugi
1583GAME( 1999, landbrka,  landbrk,  eolith45, landbrk,   eolith_state, landbrka, ROT0, "Eolith", "Land Breaker (World) / Miss Tang Ja Ru Gi (Korea) (pcb ver 3.03) (AT89c52 protected)",  GAME_IMPERFECT_SOUND ) // or Miss Ttang Jjareugi
1584GAME( 1999, nhidctch,  0,        eolith45, hidctch2,  eolith_state, eolith,   ROT0, "Eolith", "New Hidden Catch (World) / New Tul Lin Gu Lim Chat Ki '98 (Korea) (pcb ver 3.02)", GAME_IMPERFECT_SOUND ) // or New Teurrin Geurim Chajgi '98
1585GAME( 1999, penfan,    0,        eolith45, penfan,    eolith_state, eolith,   ROT0, "Eolith", "Penfan Girls - Step1. Mild Mind (set 1)",  GAME_IMPERFECT_SOUND ) // alt title of Ribbon
1586GAME( 1999, penfana,   penfan,   eolith45, penfan,    eolith_state, eolith,   ROT0, "Eolith", "Penfan Girls - Step1. Mild Mind (set 2)",  GAME_IMPERFECT_SOUND )
1587GAME( 2000, stealsee,  0,        eolith45, stealsee,  eolith_state, eolith,   ROT0, "Moov Generation / Eolith", "Steal See",  GAME_IMPERFECT_SOUND )
1588GAME( 2000, hidctch3,  0,        eolith50, hidctch3,  eolith_state, hidctch3, ROT0, "Eolith", "Hidden Catch 3 (ver 1.00 / pcb ver 3.05)", GAME_IMPERFECT_SOUND )
1589GAME( 2001, fort2b,    0,        eolith50, common,    eolith_state, eolith,   ROT0, "Eolith", "Fortress 2 Blue Arcade (ver 1.01 / pcb ver 3.05)",  GAME_IMPERFECT_SOUND )
1590GAME( 2001, fort2ba,   fort2b,   eolith50, common,    eolith_state, eolith,   ROT0, "Eolith", "Fortress 2 Blue Arcade (ver 1.00 / pcb ver 3.05)",  GAME_IMPERFECT_SOUND )
trunk/src/mame/drivers/eolith16.c
r242959r242960
1515
1616#include "sound/okim6295.h"
1717#include "includes/eolith.h"
18#include "includes/eolithsp.h"
1819
1920
2021class eolith16_state : public eolith_state
r242959r242960
2526
2627   UINT16 *m_vram;
2728   int m_vbuffer;
28   
2929   DECLARE_WRITE16_MEMBER(eeprom_w);
3030   DECLARE_READ16_MEMBER(eolith16_custom_r);
3131   DECLARE_WRITE16_MEMBER(vram_w);
3232   DECLARE_READ16_MEMBER(vram_r);
33   
3433   DECLARE_DRIVER_INIT(eolith16);
3534   DECLARE_VIDEO_START(eolith16);
3635   DECLARE_PALETTE_INIT(eolith16);
37   
3836   UINT32 screen_update_eolith16(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
3937};
4038
r242959r242960
4543   m_vbuffer = (data & 0x80) >> 7;
4644   coin_counter_w(machine(), 0, data & 1);
4745
48   m_eepromoutport->write(data, 0xff);
46   ioport("EEPROMOUT")->write(data, 0xff);
4947
5048   //data & 0x100 and data & 0x004 always set
5149}
5250
5351READ16_MEMBER(eolith16_state::eolith16_custom_r)
5452{
55   speedup_read();
53   eolith_speedup_read(space);
5654   return ioport("SPECIAL")->read();
5755}
5856
r242959r242960
115113VIDEO_START_MEMBER(eolith16_state,eolith16)
116114{
117115   m_vram = auto_alloc_array(machine(), UINT16, 0x10000);
118   save_pointer(NAME(m_vram), 0x10000);
119   save_item(NAME(m_vbuffer));
120116}
121117
122118UINT32 eolith16_state::screen_update_eolith16(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
r242959r242960
257253
258254DRIVER_INIT_MEMBER(eolith16_state,eolith16)
259255{
260   init_speedup();
256   init_eolith_speedup(machine());
261257}
262258
263GAME( 1999, klondkp, 0, eolith16, eolith16, eolith16_state, eolith16, ROT0, "Eolith", "KlonDike+", GAME_SUPPORTS_SAVE )
259GAME( 1999, klondkp, 0, eolith16, eolith16, eolith16_state, eolith16, ROT0, "Eolith", "KlonDike+", 0 )
trunk/src/mame/drivers/eolithsp.c
r242959r242960
99*/
1010
1111#include "emu.h"
12#include "includes/eolithsp.h"
1213#include "includes/eolith.h"
1314
15static int eolith_speedup_address;
16static int eolith_speedup_address2;
17static int eolith_speedup_resume_scanline;
18static int eolith_vblank = 0;
19static int eolith_scanline = 0;
1420
15void eolith_state::speedup_read()
21void eolith_speedup_read(address_space &space)
1622{
1723   /* for debug */
18   //if ((space.device().safe_pc()!=m_speedup_address) && (m_speedup_vblank!=1) )
19   //    printf("%s:eolith speedup_read data %02x\n",space.machine().describe_context(), m_speedup_vblank);
24   //if ((space.device().safe_pc()!=eolith_speedup_address) && (eolith_vblank!=1) )
25   //    printf("%s:eolith speedup_read data %02x\n",space.machine().describe_context(), eolith_vblank);
2026
21   if (m_speedup_vblank==0 && m_speedup_scanline < m_speedup_resume_scanline)
27   if (eolith_vblank==0 && eolith_scanline < eolith_speedup_resume_scanline)
2228   {
23      int pc = m_maincpu->pc();
29      int pc = space.device().safe_pc();
2430
25      if ((pc==m_speedup_address) || (pc==m_speedup_address2))
31      if ((pc==eolith_speedup_address) || (pc==eolith_speedup_address2))
2632      {
27         m_maincpu->spin_until_trigger(1000);
33         space.device().execute().spin_until_trigger(1000);
2834      }
2935   }
3036}
r242959r242960
6571};
6672
6773
68void eolith_state::init_speedup()
74void init_eolith_speedup(running_machine &machine)
6975{
7076   int n_game = 0;
71   m_speedup_address = 0;
72   m_speedup_address2 = 0;
73   m_speedup_resume_scanline = 0;
74   m_speedup_vblank = 0;
75   m_speedup_scanline = 0;
77   eolith_speedup_address = 0;
78   eolith_speedup_resume_scanline = 0;
7679
7780   while( eolith_speedup_table[ n_game ].s_name != NULL )
7881   {
79      if( strcmp( machine().system().name, eolith_speedup_table[ n_game ].s_name ) == 0 )
82      if( strcmp( machine.system().name, eolith_speedup_table[ n_game ].s_name ) == 0 )
8083      {
81         m_speedup_address = eolith_speedup_table[ n_game ].speedup_address;
82         m_speedup_address2 = eolith_speedup_table[ n_game ].speedup_address2;
83         m_speedup_resume_scanline = eolith_speedup_table[ n_game ].speedup_resume_scanline;
84         eolith_speedup_address = eolith_speedup_table[ n_game ].speedup_address;
85         eolith_speedup_address2 = eolith_speedup_table[ n_game ].speedup_address2;
86         eolith_speedup_resume_scanline = eolith_speedup_table[ n_game ].speedup_resume_scanline;
8487      }
8588      n_game++;
8689   }
87   
88   save_item(NAME(m_speedup_vblank));
89   save_item(NAME(m_speedup_scanline));
9090}
9191
9292/* todo, use timers instead! */
r242959r242960
9494{
9595   if (param==0)
9696   {
97      m_speedup_vblank = 0;
97      eolith_vblank = 0;
9898   }
9999
100   if (param==m_speedup_resume_scanline)
100   if (param==eolith_speedup_resume_scanline)
101101   {
102102      machine().scheduler().trigger(1000);
103103   }
104104
105105   if (param==240)
106106   {
107      m_speedup_vblank = 1;
107      eolith_vblank = 1;
108108   }
109109}
110110
111111CUSTOM_INPUT_MEMBER(eolith_state::eolith_speedup_getvblank)
112112{
113//  printf("%s:eolith speedup_read data %02x\n",machine().describe_context(), m_speedup_vblank);
113//  printf("%s:eolith speedup_read data %02x\n",machine().describe_context(), eolith_vblank);
114114
115115
116116   return (m_screen->vpos() >= 240);
r242959r242960
122122   int pc = m_maincpu->pc();
123123
124124   if (pc==0x400081ec)
125      if(!m_speedup_vblank)
125      if(!eolith_vblank)
126126         m_maincpu->eat_cycles(500);
127127
128128   return (m_screen->vpos() >= 240);
trunk/src/mame/drivers/hyhoo.c
r242959r242960
302302ROM_END
303303
304304
305GAME( 1987, hyhoo,  0, hyhoo,  hyhoo,  driver_device, 0, ROT90, "Nichibutsu", "Hayaoshi Taisen Quiz Hyhoo (Japan)", GAME_SUPPORTS_SAVE )
306GAME( 1987, hyhoo2, 0, hyhoo2, hyhoo2, driver_device, 0, ROT90, "Nichibutsu", "Hayaoshi Taisen Quiz Hyhoo 2 (Japan)", GAME_SUPPORTS_SAVE )
305GAME( 1987, hyhoo,  0, hyhoo,  hyhoo,  driver_device, 0, ROT90, "Nichibutsu", "Hayaoshi Taisen Quiz Hyhoo (Japan)", 0 )
306GAME( 1987, hyhoo2, 0, hyhoo2, hyhoo2, driver_device, 0, ROT90, "Nichibutsu", "Hayaoshi Taisen Quiz Hyhoo 2 (Japan)", 0 )
trunk/src/mame/drivers/naomi.c
r242959r242960
521521Star Horse (satellite)                          840-0056C  23627    6 (128Mb)* 315-6319   315-6213  not present   * +1 (64Mb), requires 837-13785 ARCNET&IO BD
522522Star Horse Progress (satellite) (Rev A)         840-0123C  24122A   7 (128Mb)  315-6319A  315-6213  not present   requires 837-13785 ARCNET&IO BD
523523The King of Route 66 (Rev A)                    840-0087C  23819A  10 (128Mb)  315-6319A  315-6213  not present
524Virtua Striker 3                                840-0061C  23663   11 (128Mb)  315-6319A  315-6213  317-0310-COM
524525Virtua Striker 3 (Rev B)                        840-0061C  23663B  11 (128Mb)  315-6319A  315-6213  317-0310-COM
525Virtua Striker 3 (Rev C)                        840-0061C  23663C  11 (128Mb)  315-6319A  315-6213  317-0310-COM
526526Wave Runner GP                                  840-0064C  24059    6 (128Mb)  315-6319A  315-6213  not present
527527Wild Riders                                     840-0046C  23622   10 (128Mb)  315-6319A  315-6213  317-0301-COM
528528WWF Royal Rumble                                840-0040C  22261    8 (128Mb)  315-6319   315-6213  317-0285-COM
r242959r242960
77907790   NAOMI_DEFAULT_EEPROM
77917791
77927792   ROM_REGION( 0xb000000, "rom_board", ROMREGION_ERASEFF)
7793   ROM_LOAD( "epr-23663c.ic22",0x0000000, 0x0400000, CRC(7007fec7) SHA1(523168f0b218d0bd5c815d65bf0caba2c8468c9d) )
7793   // rom was handmade from 2 damaged dumps, needs to be verified
7794   ROM_LOAD( "epr-23663.ic22", 0x0000000, 0x0400000, BAD_DUMP CRC(6910a008) SHA1(865affff1cf31321725ef727a17be384555e3aae) )
77947795   ROM_LOAD( "mpr-23652.ic1",  0x0800000, 0x1000000, CRC(992758a2) SHA1(5e2a25c520c1795128e5026fc00d355c24852ded) )
77957796   ROM_LOAD( "mpr-23653.ic2",  0x1800000, 0x1000000, CRC(e210e932) SHA1(2f6f0a31c3e98b21f1ff3af1680e50b3535b130f) )
77967797   ROM_LOAD( "mpr-23654.ic3",  0x2800000, 0x1000000, CRC(91335971) SHA1(fc7599b836fb7995dd7da940e64b08b3c09cb180) )
r242959r242960
90349035
90359036/* 840-xxxxx (Sega Naomi 2 cart games) */
90369037/* 0046 */ GAME( 2001, wldrider, naomi2,  naomi2m2, naomi, naomi_state, naomi2,   ROT0, "Sega", "Wild Riders (JPN, USA, EXP, KOR, AUS)", GAME_FLAGS )
9037/* 0061 */ GAME( 2001, vstrik3c, naomi2,  naomi2m2, naomi, naomi_state, naomi2,   ROT0, "Sega", "Virtua Striker 3 (USA, EXP, KOR, AUS) (Cart, Rev C)", GAME_FLAGS )
9038/* 0061 */ GAME( 2001, vstrik3c, naomi2,  naomi2m2, naomi, naomi_state, naomi2,   ROT0, "Sega", "Virtua Striker 3 (USA, EXP, KOR, AUS) (Cart)", GAME_FLAGS )
90389039/* 0061 */ GAME( 2001, vstrik3cb,vstrik3c,naomi2m2, naomi, naomi_state, naomi2,   ROT0, "Sega", "Virtua Striker 3 (USA, EXP, KOR, AUS) (Cart, Rev B)", GAME_FLAGS )
90399040/* 0062 */ GAME( 2001, clubkrte, naomi2,  naomi2m2, naomi, naomi_state, naomi2,   ROT0, "Sega", "Club Kart: European Session", GAME_FLAGS )
90409041/* 0062 */ GAME( 2001, clubkrtd, clubkrte,naomi2m2, naomi, naomi_state, naomi2,   ROT0, "Sega", "Club Kart: European Session (Rev D)", GAME_FLAGS )
trunk/src/mame/drivers/pastelg.c
r242959r242960
3636#endif
3737
3838
39void pastelg_state::machine_start()
40{
41   save_item(NAME(m_mux_data));
42}
4339
4440READ8_MEMBER(pastelg_state::pastelg_sndrom_r)
4541{
4642   UINT8 *ROM = memregion("voice")->base();
4743
48   return ROM[pastelg_blitter_src_addr_r() & 0x7fff];
44   return ROM[pastelg_blitter_src_addr_r(space) & 0x7fff];
4945}
5046
5147static ADDRESS_MAP_START( pastelg_map, AS_PROGRAM, 8, pastelg_state )
r242959r242960
7066   AM_RANGE(0xa0, 0xa0) AM_DEVREADWRITE("nb1413m3", nb1413m3_device, inputport1_r, inputportsel_w)
7167   AM_RANGE(0xb0, 0xb0) AM_DEVREAD("nb1413m3", nb1413m3_device, inputport2_r) AM_WRITE(pastelg_romsel_w)
7268   AM_RANGE(0xc0, 0xc0) AM_READ(pastelg_sndrom_r)
73   AM_RANGE(0xc0, 0xcf) AM_WRITEONLY AM_SHARE("clut")
69   AM_RANGE(0xc0, 0xcf) AM_WRITE(pastelg_clut_w)
7470   AM_RANGE(0xd0, 0xd0) AM_READ(pastelg_irq_ack_r) AM_DEVWRITE("dac", dac_device, write_unsigned8)
7571   AM_RANGE(0xe0, 0xe0) AM_READ_PORT("DSWC")
7672ADDRESS_MAP_END
r242959r242960
122118   AM_RANGE(0xf0, 0xf6) AM_WRITE(pastelg_blitter_w)
123119   AM_RANGE(0xa0, 0xa0) AM_READWRITE(threeds_inputport1_r, threeds_inputportsel_w)
124120   AM_RANGE(0xb0, 0xb0) AM_READ(threeds_inputport2_r) AM_WRITE(threeds_output_w)//writes: bit 3 is coin lockout, bit 1 is coin counter
125   AM_RANGE(0xc0, 0xcf) AM_WRITEONLY AM_SHARE("clut")
121   AM_RANGE(0xc0, 0xcf) AM_WRITE(pastelg_clut_w)
126122   AM_RANGE(0xc0, 0xc0) AM_READ(threeds_rom_readback_r)
127123   AM_RANGE(0xd0, 0xd0) AM_READ(pastelg_irq_ack_r) AM_DEVWRITE("dac", dac_device, write_unsigned8)
128124ADDRESS_MAP_END
r242959r242960
563559
564560
565561
566GAME( 1985, pastelg, 0,       pastelg, pastelg, driver_device, 0, ROT0, "Nichibutsu", "Pastel Gal (Japan 851224)", GAME_SUPPORTS_SAVE )
567GAME( 1985, threeds, 0,       threeds, threeds, driver_device, 0, ROT0, "Nichibutsu", "Three Ds - Three Dealers Casino House", GAME_SUPPORTS_SAVE )
568GAME( 1985, galds,   threeds, threeds, galds,   driver_device, 0, ROT0, "Nihon System Corp.", "Gals Ds - Three Dealers Casino House (bootleg?)", GAME_SUPPORTS_SAVE )
562GAME( 1985, pastelg, 0,       pastelg, pastelg, driver_device, 0, ROT0, "Nichibutsu", "Pastel Gal (Japan 851224)", 0 )
563GAME( 1985, threeds, 0,       threeds, threeds, driver_device, 0, ROT0, "Nichibutsu", "Three Ds - Three Dealers Casino House", 0 )
564GAME( 1985, galds,   threeds, threeds, galds,   driver_device, 0, ROT0, "Nihon System Corp.", "Gals Ds - Three Dealers Casino House (bootleg?)", 0 )
trunk/src/mame/drivers/peplus.c
r242959r242960
16241624   ROM_LOAD( "cap740.u50", 0x0000, 0x0100, CRC(6fe619c4) SHA1(49e43dafd010ce0fe9b2a63b96a4ddedcb933c6d) ) /* BPROM type DM74LS471 (compatible with N82S135N) verified */
16251625ROM_END
16261626
1627ROM_START( pepp0038 ) /* Normal board : Standard Draw Poker (PP0038) */
1628/*
1629PayTable   Js+  2PR  3K   STR  FL  FH  4K  SF  RF  (Bonus)
1630----------------------------------------------------------
1631   PE       1    2    3    4    6   9  25  50 300    900
1632  % Range: 95.8-97.8%  Optimum: 99.8%  Hit Frequency: 45.4%
1633     Programs Available: PP0038, X002121P
1634*/
1635   ROM_REGION( 0x10000, "maincpu", 0 )
1636   ROM_LOAD( "pp0038_a45-a74.u68",   0x00000, 0x10000, CRC(85fe387e) SHA1(a0aa4cb422c04066d61d665943eced30b2eaf5b2) ) /* Game Version: A45, Library Version: A74 */
1637
1638   ROM_REGION( 0x020000, "gfx1", 0 )
1639   ROM_LOAD( "mro-cg821.u72",   0x00000, 0x8000, CRC(e91f1192) SHA1(1a00027b681fad6b350366b2dff7411445a07f05) )
1640   ROM_LOAD( "mgo-cg821.u73",   0x08000, 0x8000, CRC(fa417bbc) SHA1(8c59d9156fb52099bf76b0a7e0da3a27518d6f19) )
1641   ROM_LOAD( "mbo-cg821.u74",   0x10000, 0x8000, CRC(4229457a) SHA1(aa1f26792279a834ed2025d6be58fa7ea38329fd) )
1642   ROM_LOAD( "mxo-cg821.u75",   0x18000, 0x8000, CRC(2da9729a) SHA1(3a5cf4c794e0057bdb705e0c7da541c3c8b48591) )
1643
1644   ROM_REGION( 0x100, "proms", 0 )
1645   ROM_LOAD( "cap904.u50", 0x0000, 0x0100, CRC(0eec8336) SHA1(a6585c978dbc2f4f3818e3a5b92f8c28be23c4c0) ) /* BPROM type N82S135N verified */
1646ROM_END
1647
16481627ROM_START( pepp0040 ) /* Normal board : Standard Draw Poker (PP0040) */
16491628/*
16501629PayTable   Js+  2PR  3K   STR  FL  FH  4K  SF  RF  (Bonus)
r242959r242960
22862265   ROM_LOAD( "cap740.u50", 0x0000, 0x0100, CRC(6fe619c4) SHA1(49e43dafd010ce0fe9b2a63b96a4ddedcb933c6d) ) /* BPROM type DM74LS471 (compatible with N82S135N) verified */
22872266ROM_END
22882267
2289ROM_START( pepp0116a ) /* Normal board : Standard Draw Poker (PP0116) */
2290/*
2291PayTable   Js+  2PR  3K   STR  FL  FH  4K  SF  RF  (Bonus)
2292----------------------------------------------------------
2293   BA       1    2    3    4    5   8  25  50 250    800
2294  % Range: 93.8-95.8%  Optimum: 97.8%  Hit Frequency: 45.3%
2295     Programs Available: PP0116
2296*/
2297   ROM_REGION( 0x10000, "maincpu", 0 )
2298   ROM_LOAD( "pp0116_554-544.u68",   0x00000, 0x8000, CRC(27aba06b) SHA1(7976a2b2577c28e332091cbbcb4c7d53ffbea827) ) /* Game Version: 554, Library Version: 544, Video Lib Ver: 544 */
2299   ROM_RELOAD(                       0x08000, 0x8000) /* 32K version built using earlier gaming libraries */
2300
2301   ROM_REGION( 0x020000, "gfx1", 0 )
2302   ROM_LOAD( "mro-cg864.u72",   0x00000, 0x8000, CRC(f4ac28b9) SHA1(35c8a603120f35bd92905e0491e9ae5cd201e13f) ) /*  09/13/89   @ IGT  L89-1706  */
2303   ROM_LOAD( "mgo-cg864.u73",   0x08000, 0x8000, CRC(da8efcb9) SHA1(942c6b613074c52f6ed1c2fce78d46ef0f221c48) ) /* Custom Mirage casino card backs */
2304   ROM_LOAD( "mbo-cg864.u74",   0x10000, 0x8000, CRC(d48ac9cd) SHA1(a62d6c1daf199856aa1777d1d99fe81399215e36) )
2305   ROM_LOAD( "mxo-cg864.u75",   0x18000, 0x8000, CRC(04f81245) SHA1(055271c6c502fad3be5f2d694a94f96bf3176404) )
2306
2307   ROM_REGION( 0x100, "proms", 0 )
2308   ROM_LOAD( "cap864.u50", 0x0000, 0x0100, CRC(c80e5743) SHA1(edf4e5a68905cc566077613d856bc90b8136a227) ) /* BPROM type DM74LS471 (compatible with N82S135N) verified */
2309ROM_END
2310
23112268ROM_START( pepp0118 ) /* Normal board : Standard Draw Poker (PP0118) */
23122269/*
23132270PayTable   Js+  2PR  3K  STR  FL  FH  4K  SF  RF  (Bonus)
r242959r242960
36873644   ROM_REGION( 0x020000, "gfx1", 0 )
36883645   ROM_LOAD( "mro-cg2153.u72",   0x00000, 0x8000, CRC(004c9c8e) SHA1(ec3fa9d2c658de59e722d9979513d6b0c71d5742) ) /*  05/01/95   @ IGT  L95-1123  */
36893646   ROM_LOAD( "mgo-cg2153.u73",   0x08000, 0x8000, CRC(e6843b35) SHA1(2d5219a3cb054ce8b470797c0496c7e24e94ed81) )
3690   ROM_LOAD( "mbo-cg2153.u74",   0x10000, 0x8000, CRC(e3e28611) SHA1(d040f1df6203dc0bd6a79a391fb90fb930f8dd1a) ) /* Custom Arizona Charlie's Casino card backs */
3647   ROM_LOAD( "mbo-cg2153.u74",   0x10000, 0x8000, CRC(e3e28611) SHA1(d040f1df6203dc0bd6a79a391fb90fb930f8dd1a) ) /* Custom Arizona Charlie's Casino graphics */
36913648   ROM_LOAD( "mxo-cg2153.u75",   0x18000, 0x8000, CRC(3ae44f7e) SHA1(00d625b60bffef6ce622cb50a3aa93b92131f578) )
36923649
36933650   ROM_REGION( 0x100, "proms", 0 )
r242959r242960
47724729  Four of a Kind Bonus Poker
47734730  Deuces Wild Poker
47744731
4775Also uses a Dallas (Maxim) DS1216 SmartWatch RAM for RTC (Real Time Clock) functions
4776
47774732Came out of an IGT machine with belly glass calling it Montana Choice
47784733*/
47794734   ROM_REGION( 0x10000, "maincpu", 0 )
r242959r242960
53935348   ROM_LOAD( "x000055p.u66",   0x00000, 0x10000, CRC(e06819df) SHA1(36590c4588b8036908e63714fbb3e77d23e60eae) ) /* Deuces Wild Poker */
53945349
53955350   ROM_REGION( 0x020000, "gfx1", 0 )
5396   ROM_LOAD( "mro-cg2291.u77",  0x00000, 0x8000, CRC(db4e491c) SHA1(e371e7b236962a0f30640c683d3a0a302c51aee9) ) /* Custom The Orleans card backs */
5351   ROM_LOAD( "mro-cg2291.u77",  0x00000, 0x8000, CRC(db4e491c) SHA1(e371e7b236962a0f30640c683d3a0a302c51aee9) ) /* Custom The Orleans graphics */
53975352   ROM_LOAD( "mgo-cg2291.u78",  0x08000, 0x8000, CRC(17bb35f8) SHA1(ba9e8aa3ff42b17c7be6ee46c70db22d8e60e52c) ) /* Compatible with most "standard" game sets */
53985353   ROM_LOAD( "mbo-cg2291.u79",  0x10000, 0x8000, CRC(de1036e4) SHA1(774bbcda301754dc4a606974248847a2264c3827) )
53995354   ROM_LOAD( "mxo-cg2291.u80",  0x18000, 0x8000, CRC(7049403c) SHA1(3a29a00fb8dfdb30dba757c1536151827ea09068) )
r242959r242960
54185373   ROM_LOAD( "x000055p.u66",   0x00000, 0x10000, CRC(e06819df) SHA1(36590c4588b8036908e63714fbb3e77d23e60eae) ) /* Deuces Wild Poker */
54195374
54205375   ROM_REGION( 0x020000, "gfx1", 0 )
5421   ROM_LOAD( "mro-cg2399.u72",  0x00000, 0x8000, CRC(0424f4ba) SHA1(c8b192a6f63c8c9937cb3923d27b9ba2c39823cd) ) /* Custom The Fun Ships card backs */
5376   ROM_LOAD( "mro-cg2399.u72",  0x00000, 0x8000, CRC(0424f4ba) SHA1(c8b192a6f63c8c9937cb3923d27b9ba2c39823cd) ) /* Custom The Fun Ships graphics */
54225377   ROM_LOAD( "mgo-cg2399.u73",  0x08000, 0x8000, CRC(5848a2fa) SHA1(4173a473016b7a776d2b59bf3ded0be35bd43721) )
54235378   ROM_LOAD( "mbo-cg2399.u74",  0x10000, 0x8000, CRC(5c3e16f6) SHA1(a4aa457f239527bffa6472e0d6f9d836f796b326) )
54245379   ROM_LOAD( "mxo-cg2399.u75",  0x18000, 0x8000, CRC(bd7669d5) SHA1(4343a9764fd563e2e1cdd8558f2f53f77006b159) )
r242959r242960
54435398   ROM_LOAD( "x000055p.u66",   0x00000, 0x10000, CRC(e06819df) SHA1(36590c4588b8036908e63714fbb3e77d23e60eae) ) /* Deuces Wild Poker */
54445399
54455400   ROM_REGION( 0x020000, "gfx1", 0 )
5446   ROM_LOAD( "mro-cg2374.u72",  0x00000, 0x8000, CRC(ceeb714d) SHA1(6de908d04bcaa243195943affa9ad0d725de5c81) ) /* Custom Horseshoe Casino card backs */
5447   ROM_LOAD( "mgo-cg2374.u73",  0x08000, 0x8000, CRC(d0fabad5) SHA1(438ebe074fa3eaa3073ef042f481449f416d0665) )
5448   ROM_LOAD( "mbo-cg2374.u74",  0x10000, 0x8000, CRC(9a0fbc8d) SHA1(aa39f47cbeaf8218fd2d753c9a350e9eab5df5d3) )
5449   ROM_LOAD( "mxo-cg2374.u75",  0x18000, 0x8000, CRC(99814562) SHA1(2d8e132f4cc4edd06332c0327927219513b22832) )
5401   ROM_LOAD( "mro-cg2185.u77",  0x00000, 0x8000, CRC(7e64bd1a) SHA1(e988a380ee58078bf5bdc7747e83aed1393cfad8) ) /*  07/10/95   @ IGT  L95-1506  */
5402   ROM_LOAD( "mgo-cg2185.u78",  0x08000, 0x8000, CRC(d4127893) SHA1(75039c45ba6fd171a66876c91abc3191c7feddfc) )
5403   ROM_LOAD( "mbo-cg2185.u79",  0x10000, 0x8000, CRC(17dba955) SHA1(5f77379c88839b3a04e235e4fb0120c77e17b60e) )
5404   ROM_LOAD( "mxo-cg2185.u80",  0x18000, 0x8000, CRC(583eb3b1) SHA1(4a2952424969917fb1594698a779fe5a1e99bff5) )
54505405
54515406   ROM_REGION( 0x200, "proms", 0 )
5452   ROM_LOAD( "capx2374.u43", 0x0000, 0x0200, CRC(f922e1b8) SHA1(4aa5291c59431c022dc0561a6e3b38209f60286a) )
5407   ROM_LOAD( "capx1321.u43", 0x0000, 0x0200, CRC(4b57569f) SHA1(fa29c0f627e7ce79951ec6dadec114864144f37d) )
54535408ROM_END
54545409
54555410ROM_START( pex0055pd ) /* Superboard : Deuces Wild Poker (X000055P+XP000035) */
r242959r242960
79407895   ROM_LOAD( "x002374p.u66",   0x00000, 0x10000, CRC(fc4b6c8d) SHA1(b101f9042bd54dbfdeed4c7a3acf3798096f6857) ) /* Super Aces Poker */
79417896
79427897   ROM_REGION( 0x020000, "gfx1", 0 )
7943   ROM_LOAD( "mro-cg2324.u77",  0x00000, 0x8000, CRC(6eceef42) SHA1(a2ddd2a3290c41e510f483c6b633fe0002694d0b) )
7944   ROM_LOAD( "mgo-cg2324.u78",  0x08000, 0x8000, CRC(26d0acbe) SHA1(09a9127deb88185cd5b748bac657461eadb2f48f) )
7945   ROM_LOAD( "mbo-cg2324.u79",  0x10000, 0x8000, CRC(47baee32) SHA1(d8af09022ccb5fc06aa3aa4c200a734b66cbee00) )
7946   ROM_LOAD( "mxo-cg2324.u80",  0x18000, 0x8000, CRC(60449fc0) SHA1(251d1e04786b70c1d2bc7b02f3b69cd58ac76398) )
7898   ROM_LOAD( "mro-cg2374.u72",  0x00000, 0x8000, CRC(ceeb714d) SHA1(6de908d04bcaa243195943affa9ad0d725de5c81) ) /* Custom Horseshoe Casino card backs */
7899   ROM_LOAD( "mgo-cg2374.u73",  0x08000, 0x8000, CRC(d0fabad5) SHA1(438ebe074fa3eaa3073ef042f481449f416d0665) )
7900   ROM_LOAD( "mbo-cg2374.u74",  0x10000, 0x8000, CRC(9a0fbc8d) SHA1(aa39f47cbeaf8218fd2d753c9a350e9eab5df5d3) )
7901   ROM_LOAD( "mxo-cg2374.u75",  0x18000, 0x8000, CRC(99814562) SHA1(2d8e132f4cc4edd06332c0327927219513b22832) )
79477902
79487903   ROM_REGION( 0x200, "proms", 0 )
7949   ROM_LOAD( "capx1321.u43", 0x0000, 0x0200, CRC(4b57569f) SHA1(fa29c0f627e7ce79951ec6dadec114864144f37d) )
7904   ROM_LOAD( "cap2374.u43", 0x0000, 0x0200, CRC(f922e1b8) SHA1(4aa5291c59431c022dc0561a6e3b38209f60286a) )
79507905ROM_END
79517906
79527907ROM_START( pex2377p ) /* Superboard : Super Double Bonus Poker (X002377P+XP000112) */
r242959r242960
90779032GAMEL(1987, pepp0014,  pepp0002, peplus,  peplus_poker, peplus_state, peplus,   ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0014) Standard Draw Poker (International)", 0, layout_pe_poker )
90789033GAMEL(1987, pepp0014a, pepp0002, peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0014) Standard Draw Poker",           0, layout_pe_poker )
90799034GAMEL(1987, pepp0023,  pepp0002, peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0023) 10's or Better",                0, layout_pe_poker )
9080GAMEL(1987, pepp0038,  pepp0002, peplus,  peplus_poker, peplus_state, peplus,   ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0038) Standard Draw Poker",           0, layout_pe_poker )
90819035GAMEL(1987, pepp0040,  pepp0002, peplus,  peplus_poker, peplus_state, peplus,   ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0040) Standard Draw Poker",           0, layout_pe_poker )
90829036GAMEL(1987, pepp0040a, pepp0002, peplus,  peplus_poker, peplus_state, peplus,   ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0040) Standard Draw Poker (International)", 0, layout_pe_poker )
90839037GAMEL(1987, pepp0041,  pepp0002, peplus,  peplus_poker, peplus_state, peplus,   ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0041) Standard Draw Poker",           0, layout_pe_poker )
r242959r242960
91079061GAMEL(1987, pepp0083,  pepp0002, peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0083) 10's or Better",                0, layout_pe_poker )
91089062GAMEL(1987, pepp0103,  pepp0055, peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0103) Deuces Wild Poker",             0, layout_pe_poker )
91099063GAMEL(1987, pepp0116,  pepp0002, peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0116) Standard Draw Poker",           0, layout_pe_poker )
9110GAMEL(1987, pepp0116a, pepp0002, peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0116) Standard Draw Poker (Mirage)",  0, layout_pe_poker )
91119064GAMEL(1987, pepp0118,  pepp0002, peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0118) Standard Draw Poker",           0, layout_pe_poker )
91129065GAMEL(1987, pepp0120,  0,        peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0120) Wild Sevens Poker",             0, layout_pe_poker )
91139066GAMEL(1987, pepp0125,  pepp0055, peplus,  peplus_poker, peplus_state, nonplus,  ROT0,  "IGT - International Game Technology", "Player's Edge Plus (PP0125) Deuces Wild Poker",             0, layout_pe_poker )
r242959r242960
92659218GAMEL(1995, pex0055p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X000055P+XP000019) Deuces Wild Poker",   0, layout_pe_poker )
92669219GAMEL(1995, pex0055pa, pex0055p,  peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X000055P+XP000022) Deuces Wild Poker (The Orleans)", 0, layout_pe_poker )
92679220GAMEL(1995, pex0055pb, pex0055p,  peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X000055P+XP000023) Deuces Wild Poker (The Fun Ships)", 0, layout_pe_poker )
9268GAMEL(1995, pex0055pc, pex0055p,  peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X000055P+XP000028) Deuces Wild Poker (Horseshoe)", 0, layout_pe_poker )
9221GAMEL(1995, pex0055pc, pex0055p,  peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X000055P+XP000028) Deuces Wild Poker",  0, layout_pe_poker )
92699222GAMEL(1995, pex0055pd, pex0055p,  peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X000055P+XP000035) Deuces Wild Poker",   0, layout_pe_poker )
92709223GAMEL(1995, pex0055pe, pex0055p,  peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X000055P+XP000038) Deuces Wild Poker",   0, layout_pe_poker )
92719224GAMEL(1995, pex0055pf, pex0055p,  peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X000055P+XP000040) Deuces Wild Poker",   0, layout_pe_poker )
r242959r242960
93639316GAMEL(1995, pex2308p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X002308P+XP000112) Triple Double Bonus Poker", 0, layout_pe_poker )
93649317GAMEL(1995, pex2310p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X002310P+XP000112) Triple Double Bonus Poker", 0, layout_pe_poker )
93659318GAMEL(1995, pex2314p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X002314P+XP000112) Triple Bonus Poker Plus", 0, layout_pe_poker )
9366GAMEL(1995, pex2374p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X002374P+XP000112) Super Aces Poker",    0, layout_pe_poker )
9319GAMEL(1995, pex2374p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X002374P+XP000112) Super Aces Poker (Horseshoe)", 0, layout_pe_poker )
93679320GAMEL(1995, pex2377p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X002377P+XP000112) Super Double Bonus Poker", 0, layout_pe_poker )
93689321GAMEL(1995, pex2419p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X002419P+XP000064) Deuces Wild Bonus Poker - French", 0, layout_pe_poker )
93699322GAMEL(1995, pex2420p,  0,         peplus,  peplus_poker, peplus_state, peplussb, ROT0,  "IGT - International Game Technology", "Player's Edge Plus (X002420P+XP000064) Deuces Wild Bonus Poker - French", 0, layout_pe_poker )
trunk/src/mame/drivers/psychic5.c
r242959r242960
800800
801801
802802
803ROM_START( psychic5j )
803ROM_START( psychic5 )
804804   ROM_REGION( 0x20000, "maincpu", 0 )                     /* Main CPU */
805805   ROM_LOAD( "p5d",          0x00000, 0x08000, CRC(90259249) SHA1(ac2d8dd95f6c04b6ad726136931e37dcd537e977) )
806806   ROM_LOAD( "p5e",          0x10000, 0x10000, CRC(72298f34) SHA1(725be2fbf5f3622f646c0fb8e6677cbddf0b1fc2) )
r242959r242960
824824   ROM_LOAD( "my09.3t",    0x200, 0x400, CRC(59e44236) SHA1(f53d99694fa5acd7cc51dd78e09f0d2ef730e7a4) )
825825ROM_END
826826
827ROM_START( psychic5 )
827ROM_START( psychic5a )
828828   ROM_REGION( 0x20000, "maincpu", 0 )                     /* Main CPU */
829829   ROM_LOAD( "myp5d",          0x00000, 0x08000, CRC(1d40a8c7) SHA1(79b36e690ea334c066b55b1e39ceb5fe0688cd7b) )
830830   ROM_LOAD( "myp5e",          0x10000, 0x10000, CRC(2fa7e8c0) SHA1(d5096ebec58329346a3292ad2da1be3742fad093) )
r242959r242960
944944ROM_END
945945
946946
947GAME( 1987, psychic5,  0,        psychic5, psychic5, driver_device, 0, ROT270, "Jaleco / NMK", "Psychic 5 (World)", 0 ) // "Oversea's version V2.00 CHANGED BY TAMIO NAKASATO" text present in ROM, various modifications (English names, more complete attract demo etc.)
948GAME( 1987, psychic5j, psychic5, psychic5, psychic5, driver_device, 0, ROT270, "Jaleco / NMK", "Psychic 5 (Japan)", 0 )
949GAME( 1988, bombsa,    0,        bombsa,   bombsa,   driver_device, 0, ROT270, "Jaleco", "Bombs Away", GAME_NOT_WORKING )
950
947GAME( 1987, psychic5,  0,        psychic5, psychic5, driver_device, 0, ROT270, "Jaleco", "Psychic 5 (set 1)", 0 )
948GAME( 1987, psychic5a, psychic5, psychic5, psychic5, driver_device, 0, ROT270, "Jaleco", "Psychic 5 (set 2)", 0 ) // player doesn't die as early in attract mode on this set..
949GAME( 1988, bombsa,    0,        bombsa,   bombsa, driver_device,   0, ROT270, "Jaleco", "Bombs Away", GAME_NOT_WORKING )
trunk/src/mame/drivers/segajw.c
r242959r242960
438438ROM_END
439439
440440
441GAMEL( 1991, segajw,  0,   segajw,  segajw, driver_device,  0, ROT0, "Sega", "Golden Poker Series \"Joker's Wild\" (Rev. B)", GAME_NOT_WORKING | GAME_NO_SOUND | GAME_IMPERFECT_GRAPHICS, layout_segajw ) // TODO: correct title
441GAMEL( 198?, segajw,  0,   segajw,  segajw, driver_device,  0, ROT0, "Sega", "Golden Poker Series \"Joker's Wild\" (Rev. B)", GAME_NOT_WORKING | GAME_NO_SOUND | GAME_IMPERFECT_GRAPHICS, layout_segajw ) // TODO: correct title
trunk/src/mame/drivers/sprint2.c
r242959r242960
9898         case 4: m_gear[i] = 3; break;
9999         case 8: m_gear[i] = 4; break;
100100         }
101         output_set_value("P1gear", m_gear[0]);
102         output_set_value("P2gear", m_gear[1]);
103101      }
104102   }
105103
trunk/src/mame/drivers/stadhero.c
r242959r242960
3535   switch (offset<<1)
3636   {
3737      case 0:
38         return m_inputs->read();
38         return ioport("INPUTS")->read();
3939
4040      case 2:
41         return m_coin->read();
41         return ioport("COIN")->read();
4242
4343      case 4:
44         return m_dsw->read();
44         return ioport("DSW")->read();
4545   }
4646
4747   logerror("CPU #0 PC %06x: warning - read unmapped memory address %06x\n",space.device().safe_pc(),0x30c000+offset);
r242959r242960
305305
306306/******************************************************************************/
307307
308GAME( 1988, stadhero, 0, stadhero, stadhero, driver_device, 0, ROT0, "Data East Corporation", "Stadium Hero (Japan)", GAME_SUPPORTS_SAVE )
308GAME( 1988, stadhero, 0, stadhero, stadhero, driver_device, 0, ROT0, "Data East Corporation", "Stadium Hero (Japan)", 0 )
trunk/src/mame/drivers/stfight.c
r242959r242960
247247#include "cpu/z80/z80.h"
248248#include "cpu/m6805/m6805.h"
249249#include "sound/2203intf.h"
250#include "sound/msm5205.h"
250251#include "includes/stfight.h"
251252
252253static ADDRESS_MAP_START( cpu1_map, AS_PROGRAM, 8, stfight_state )
r242959r242960
10361037ROM_END
10371038
10381039// Note: Marked GAME_IMPERFECT_SOUND due to YM2203 clock issue
1039GAME( 1986, empcity,  0,       stfight, stfight, stfight_state, empcity, ROT0,   "Seibu Kaihatsu",                           "Empire City: 1931 (bootleg?)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1040GAME( 1986, empcityu, empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu (Taito / Romstar license)", "Empire City: 1931 (US)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE ) // different title logo
1041GAME( 1986, empcityj, empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu (Taito license)",           "Empire City: 1931 (Japan)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1042GAME( 1986, empcityi, empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu (Eurobed license)",         "Empire City: 1931 (Italy)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1043GAME( 1986, stfight,  empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu (Tuning license)",          "Street Fight (Germany)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1044GAME( 1986, stfighta, empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu",                           "Street Fight (bootleg?)", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
1040GAME( 1986, empcity,  0,       stfight, stfight, stfight_state, empcity, ROT0,   "Seibu Kaihatsu",                           "Empire City: 1931 (bootleg?)", GAME_IMPERFECT_SOUND )
1041GAME( 1986, empcityu, empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu (Taito / Romstar license)", "Empire City: 1931 (US)", GAME_IMPERFECT_SOUND ) // different title logo
1042GAME( 1986, empcityj, empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu (Taito license)",           "Empire City: 1931 (Japan)", GAME_IMPERFECT_SOUND )
1043GAME( 1986, empcityi, empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu (Eurobed license)",         "Empire City: 1931 (Italy)", GAME_IMPERFECT_SOUND )
1044GAME( 1986, stfight,  empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu (Tuning license)",          "Street Fight (Germany)", GAME_IMPERFECT_SOUND )
1045GAME( 1986, stfighta, empcity, stfight, stfight, stfight_state, stfight, ROT0,   "Seibu Kaihatsu",                           "Street Fight (bootleg?)", GAME_IMPERFECT_SOUND )
10451046/* Cross Shooter runs on a slightly modified PCB, with a different text tilemap and gfx blobs (see also cshooter.c) */
1046GAME( 1987, cshooter,  0,      cshooter,cshooter, stfight_state, cshooter,ROT270,"Seibu Kaihatsu (Taito license)",           "Cross Shooter (not encrypted)", GAME_NOT_WORKING | GAME_SUPPORTS_SAVE )
1047GAME( 1987, cshooter,  0,      cshooter,cshooter, stfight_state, cshooter,ROT270,"Seibu Kaihatsu (Taito license)",           "Cross Shooter (not encrypted)", GAME_NOT_WORKING )
trunk/src/mame/drivers/stlforce.c
r242959r242960
370370}
371371
372372
373GAME( 1994, stlforce, 0,        stlforce, stlforce, stlforce_state, stlforce, ROT0, "Electronic Devices Italy / Ecogames S.L. Spain", "Steel Force", GAME_SUPPORTS_SAVE )
374GAME( 1995, twinbrat, 0,        twinbrat, stlforce, stlforce_state, twinbrat, ROT0, "Elettronica Video-Games S.R.L.", "Twin Brats (set 1)", GAME_SUPPORTS_SAVE )
375GAME( 1995, twinbrata,twinbrat, twinbrat, stlforce, stlforce_state, twinbrat, ROT0, "Elettronica Video-Games S.R.L.", "Twin Brats (set 2)", GAME_SUPPORTS_SAVE )
373GAME( 1994, stlforce, 0,        stlforce, stlforce, stlforce_state, stlforce, ROT0, "Electronic Devices Italy / Ecogames S.L. Spain", "Steel Force", 0 )
374GAME( 1995, twinbrat, 0,        twinbrat, stlforce, stlforce_state, twinbrat, ROT0, "Elettronica Video-Games S.R.L.", "Twin Brats (set 1)", 0 )
375GAME( 1995, twinbrata,twinbrat, twinbrat, stlforce, stlforce_state, twinbrat, ROT0, "Elettronica Video-Games S.R.L.", "Twin Brats (set 2)", 0 )
trunk/src/mame/drivers/strnskil.c
r242959r242960
2222#include "sound/sn76496.h"
2323#include "includes/strnskil.h"
2424
25
26
27void strnskil_state::machine_start()
28{
29   save_item(NAME(m_scrl_ctrl));
30   save_item(NAME(m_irq_source));
31}
32
3325/****************************************************************************/
3426
3527READ8_MEMBER(strnskil_state::strnskil_d800_r)
r242959r242960
541533   m_maincpu->space(AS_PROGRAM).install_write_handler(0xd80d, 0xd80d, write8_delegate(FUNC(strnskil_state::protection_w),this));
542534}
543535
544GAME( 1984, strnskil, 0,        strnskil, strnskil, driver_device, 0,       ROT0, "Sun Electronics", "Strength & Skill", GAME_SUPPORTS_SAVE )
545GAME( 1984, guiness,  strnskil, strnskil, strnskil, driver_device, 0,       ROT0, "Sun Electronics", "The Guiness (Japan)", GAME_SUPPORTS_SAVE )
546GAME( 1984, banbam,   0,        banbam,   banbam, strnskil_state,   banbam,  ROT0, "Sun Electronics", "BanBam", GAME_UNEMULATED_PROTECTION | GAME_SUPPORTS_SAVE )
547GAME( 1984, pettanp,  banbam,   strnskil, banbam, strnskil_state,   pettanp, ROT0, "Sun Electronics", "Pettan Pyuu (Japan)", GAME_UNEMULATED_PROTECTION | GAME_SUPPORTS_SAVE )
536GAME( 1984, strnskil, 0,        strnskil, strnskil, driver_device, 0,       ROT0, "Sun Electronics", "Strength & Skill", 0 )
537GAME( 1984, guiness,  strnskil, strnskil, strnskil, driver_device, 0,       ROT0, "Sun Electronics", "The Guiness (Japan)", 0 )
538GAME( 1984, banbam,   0,        banbam,   banbam, strnskil_state,   banbam,  ROT0, "Sun Electronics", "BanBam", GAME_UNEMULATED_PROTECTION )
539GAME( 1984, pettanp,  banbam,   strnskil, banbam, strnskil_state,   pettanp, ROT0, "Sun Electronics", "Pettan Pyuu (Japan)", GAME_UNEMULATED_PROTECTION )
trunk/src/mame/drivers/tourtabl.c
r242959r242960
2020      : driver_device(mconfig, type, tag),
2121      m_maincpu(*this, "maincpu") { }
2222
23   required_device<cpu_device> m_maincpu;
24   
2523   DECLARE_WRITE8_MEMBER(tourtabl_led_w);
2624   DECLARE_READ16_MEMBER(tourtabl_read_input_port);
2725   DECLARE_READ8_MEMBER(tourtabl_get_databus_contents);
2826   DECLARE_WRITE8_MEMBER(watchdog_w);
27   required_device<cpu_device> m_maincpu;
2928};
3029
3130
r242959r242960
202201ROM_END
203202
204203
205GAME( 1978, tourtabl, 0,        tourtabl, tourtabl, driver_device, 0, ROT0, "Atari", "Tournament Table (set 1)", GAME_SUPPORTS_SAVE )
206GAME( 1978, tourtab2, tourtabl, tourtabl, tourtabl, driver_device, 0, ROT0, "Atari", "Tournament Table (set 2)", GAME_SUPPORTS_SAVE )
204GAME( 1978, tourtabl, 0,        tourtabl, tourtabl, driver_device, 0, ROT0, "Atari", "Tournament Table (set 1)", 0 )
205GAME( 1978, tourtab2, tourtabl, tourtabl, tourtabl, driver_device, 0, ROT0, "Atari", "Tournament Table (set 2)", 0 )
trunk/src/mame/drivers/vegaeo.c
r242959r242960
1616#include "machine/at28c16.h"
1717#include "sound/qs1000.h"
1818#include "includes/eolith.h"
19#include "includes/eolithsp.h"
1920
2021
2122class vegaeo_state : public eolith_state
r242959r242960
2627
2728   UINT32 *m_vega_vram;
2829   UINT8 m_vega_vbuffer;
29   
3030   DECLARE_WRITE32_MEMBER(vega_vram_w);
3131   DECLARE_READ32_MEMBER(vega_vram_r);
3232   DECLARE_WRITE32_MEMBER(vega_misc_w);
3333   DECLARE_READ32_MEMBER(vegaeo_custom_read);
3434   DECLARE_WRITE32_MEMBER(soundlatch_w);
35
3536   DECLARE_READ8_MEMBER(qs1000_p1_r);
37
3638   DECLARE_WRITE8_MEMBER(qs1000_p1_w);
3739   DECLARE_WRITE8_MEMBER(qs1000_p2_w);
3840   DECLARE_WRITE8_MEMBER(qs1000_p3_w);
39
4041   DECLARE_DRIVER_INIT(vegaeo);
4142   DECLARE_VIDEO_START(vega);
42
4343   UINT32 screen_update_vega(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
4444};
4545
r242959r242960
6262   // ...x .... - ?
6363   // ..x. .... - /IRQ clear
6464
65   qs1000_device *qs1000 = machine().device<qs1000_device>("qs1000");
66
6567   membank("qs1000:bank")->set_entry(data & 0x07);
6668
6769   if (!BIT(data, 5))
68      m_qs1000->set_irq(CLEAR_LINE);
70      qs1000->set_irq(CLEAR_LINE);
6971}
7072
7173WRITE32_MEMBER(vegaeo_state::vega_vram_w)
r242959r242960
113115
114116READ32_MEMBER(vegaeo_state::vegaeo_custom_read)
115117{
116   speedup_read();
118   eolith_speedup_read(space);
117119   return ioport("SYSTEM")->read();
118120}
119121
120122WRITE32_MEMBER(vegaeo_state::soundlatch_w)
121123{
124   qs1000_device *qs1000 = space.machine().device<qs1000_device>("qs1000");
125
122126   soundlatch_byte_w(space, 0, data);
123   m_qs1000->set_irq(ASSERT_LINE);
127   qs1000->set_irq(ASSERT_LINE);
124128
125129   machine().scheduler().boost_interleave(attotime::zero, attotime::from_usec(100));
126130}
r242959r242960
176180VIDEO_START_MEMBER(vegaeo_state,vega)
177181{
178182   m_vega_vram = auto_alloc_array(machine(), UINT32, 0x14000*2/4);
179   save_pointer(NAME(m_vega_vram), 0x14000*2/4);
180   save_item(NAME(m_vega_vbuffer));
181183}
182184
183185UINT32 vegaeo_state::screen_update_vega(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
r242959r242960
326328   machine().device("qs1000:cpu")->memory().space(AS_IO).install_read_bank(0x0100, 0xffff, "bank");
327329   membank("qs1000:bank")->configure_entries(0, 8, memregion("qs1000:cpu")->base()+0x100, 0x10000);
328330
329   init_speedup();
331   init_eolith_speedup(machine());
330332}
331333
332GAME( 2002, crazywar, 0, vega, crazywar, vegaeo_state, vegaeo, ROT0, "Eolith", "Crazy War", GAME_IMPERFECT_SOUND | GAME_SUPPORTS_SAVE )
334GAME( 2002, crazywar, 0, vega, crazywar, vegaeo_state, vegaeo, ROT0, "Eolith", "Crazy War", GAME_IMPERFECT_SOUND )
trunk/src/mame/drivers/xyonix.c
r242959r242960
2525#include "includes/xyonix.h"
2626
2727
28void xyonix_state::machine_start()
28WRITE8_MEMBER(xyonix_state::xyonix_irqack_w)
2929{
30   save_item(NAME(m_e0_data));
31   save_item(NAME(m_credits));
32   save_item(NAME(m_coins));
33   save_item(NAME(m_prev_coin));
34}
35
36WRITE8_MEMBER(xyonix_state::irqack_w)
37{
3830   m_maincpu->set_input_line(0, CLEAR_LINE);
3931}
4032
r242959r242960
7971}
8072
8173
82READ8_MEMBER(xyonix_state::io_r)
74READ8_MEMBER(xyonix_state::xyonix_io_r)
8375{
8476   int regPC = space.device().safe_pc();
8577
r242959r242960
130122   return 0xff;
131123}
132124
133WRITE8_MEMBER(xyonix_state::io_w)
125WRITE8_MEMBER(xyonix_state::xyonix_io_w)
134126{
135127   //logerror ("xyonix_port_e0_w %02x - PC = %04x\n", data, space.device().safe_pc());
136128   m_e0_data = data;
r242959r242960
141133static ADDRESS_MAP_START( main_map, AS_PROGRAM, 8, xyonix_state )
142134   AM_RANGE(0x0000, 0xbfff) AM_ROM
143135   AM_RANGE(0xc000, 0xdfff) AM_RAM
144   AM_RANGE(0xe000, 0xffff) AM_RAM_WRITE(vidram_w) AM_SHARE("vidram")
136   AM_RANGE(0xe000, 0xffff) AM_RAM_WRITE(xyonix_vidram_w) AM_SHARE("vidram")
145137ADDRESS_MAP_END
146138
147139static ADDRESS_MAP_START( port_map, AS_IO, 8, xyonix_state )
r242959r242960
149141   AM_RANGE(0x20, 0x20) AM_READNOP AM_DEVWRITE("sn1", sn76496_device, write)   /* SN76496 ready signal */
150142   AM_RANGE(0x21, 0x21) AM_READNOP AM_DEVWRITE("sn2", sn76496_device, write)
151143   AM_RANGE(0x40, 0x40) AM_WRITENOP        /* NMI ack? */
152   AM_RANGE(0x50, 0x50) AM_WRITE(irqack_w)
144   AM_RANGE(0x50, 0x50) AM_WRITE(xyonix_irqack_w)
153145   AM_RANGE(0x60, 0x61) AM_WRITENOP        /* mc6845 */
154   AM_RANGE(0xe0, 0xe0) AM_READWRITE(io_r, io_w)
146   AM_RANGE(0xe0, 0xe0) AM_READWRITE(xyonix_io_r, xyonix_io_w)
155147ADDRESS_MAP_END
156148
157149/* Inputs Ports **************************************************************/
r242959r242960
234226   MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(0))
235227   MCFG_SCREEN_SIZE(80*4, 32*8)
236228   MCFG_SCREEN_VISIBLE_AREA(0, 80*4-1, 0, 28*8-1)
237   MCFG_SCREEN_UPDATE_DRIVER(xyonix_state, screen_update)
229   MCFG_SCREEN_UPDATE_DRIVER(xyonix_state, screen_update_xyonix)
238230   MCFG_SCREEN_PALETTE("palette")
239231
240232   MCFG_GFXDECODE_ADD("gfxdecode", "palette", xyonix)
r242959r242960
267259
268260/* GAME drivers **************************************************************/
269261
270GAME( 1989, xyonix, 0, xyonix, xyonix, driver_device, 0, ROT0, "Philko", "Xyonix", GAME_SUPPORTS_SAVE )
262GAME( 1989, xyonix, 0, xyonix, xyonix, driver_device, 0, ROT0, "Philko", "Xyonix", 0 )
trunk/src/mame/includes/dec0.h
r242959r242960
88public:
99   dec0_state(const machine_config &mconfig, device_type type, const char *tag)
1010      : driver_device(mconfig, type, tag),
11      m_maincpu(*this, "maincpu"),
12      m_audiocpu(*this, "audiocpu"),
13      m_subcpu(*this, "sub"),
14      m_mcu(*this, "mcu"),
15      m_msm(*this, "msm"),
16      m_palette(*this, "palette"),
11      m_ram(*this, "ram"),
12      m_spriteram(*this, "spriteram"),
13      m_paletteram(*this, "palette"),
14      m_robocop_shared_ram(*this, "robocop_shared"),
15      m_hippodrm_shared_ram(*this, "hippodrm_shared"),
1716      m_tilegen1(*this, "tilegen1"),
1817      m_tilegen2(*this, "tilegen2"),
1918      m_tilegen3(*this, "tilegen3"),
2019      m_spritegen(*this, "spritegen"),
2120      m_pfprotect(*this, "pfprotect"),
22      m_ram(*this, "ram"),
23      m_spriteram(*this, "spriteram"),
24      m_paletteram(*this, "palette"),
25      m_robocop_shared_ram(*this, "robocop_shared"),
26      m_hippodrm_shared_ram(*this, "hippodrm_shared") { }
27     
28   required_device<cpu_device> m_maincpu;
29   required_device<cpu_device> m_audiocpu;
30   optional_device<cpu_device> m_subcpu;
31   optional_device<cpu_device> m_mcu;
32   optional_device<msm5205_device> m_msm;
33   required_device<palette_device> m_palette;
34   optional_device<deco_bac06_device> m_tilegen1;
35   optional_device<deco_bac06_device> m_tilegen2;
36   optional_device<deco_bac06_device> m_tilegen3;
37   optional_device<deco_mxc06_device> m_spritegen;
38   optional_device<address_map_bank_device> m_pfprotect;
21      m_maincpu(*this, "maincpu"),
22      m_audiocpu(*this, "audiocpu"),
23      m_subcpu(*this, "sub"),
24      m_mcu(*this, "mcu"),
25      m_msm(*this, "msm"),
26      m_palette(*this, "palette") { }
3927
4028   required_shared_ptr<UINT16> m_ram;
4129   required_shared_ptr<UINT16> m_spriteram;
r242959r242960
4331   optional_shared_ptr<UINT8> m_robocop_shared_ram;
4432   optional_shared_ptr<UINT8> m_hippodrm_shared_ram;
4533
46   int m_game;
34   optional_device<deco_bac06_device> m_tilegen1;
35   optional_device<deco_bac06_device> m_tilegen2;
36   optional_device<deco_bac06_device> m_tilegen3;
37   optional_device<deco_mxc06_device> m_spritegen;
38
39   optional_device<address_map_bank_device> m_pfprotect;
40
41   int m_GAME;
4742   int m_i8751_return;
4843   int m_i8751_command;
4944   int m_slyspy_state;
5045   int m_hippodrm_msb;
5146   int m_hippodrm_lsb;
5247   UINT8 m_i8751_ports[4];
48
5349   UINT16 *m_buffered_spriteram;
5450   UINT16 m_pri;
55
5651   DECLARE_WRITE16_MEMBER(dec0_control_w);
5752   DECLARE_WRITE16_MEMBER(slyspy_control_w);
5853   DECLARE_WRITE16_MEMBER(midres_sound_w);
r242959r242960
7570   DECLARE_WRITE16_MEMBER(dec0_update_sprites_w);
7671   DECLARE_WRITE16_MEMBER(dec0_priority_w);
7772   DECLARE_READ16_MEMBER(ffantasybl_242024_r);
78   DECLARE_WRITE_LINE_MEMBER(sound_irq);
79   DECLARE_WRITE_LINE_MEMBER(sound_irq2);
80   
73   DECLARE_READ16_MEMBER(ffantasybl_vblank_r);
8174   DECLARE_DRIVER_INIT(robocop);
8275   DECLARE_DRIVER_INIT(hippodrm);
8376   DECLARE_DRIVER_INIT(hbarrel);
r242959r242960
8679   DECLARE_DRIVER_INIT(baddudes);
8780   DECLARE_DRIVER_INIT(midresb);
8881   DECLARE_DRIVER_INIT(ffantasybl);
89   
90   virtual void machine_start();
91   DECLARE_MACHINE_RESET(slyspy);
9282   DECLARE_VIDEO_START(dec0);
83   DECLARE_MACHINE_RESET(slyspy);
9384   DECLARE_VIDEO_START(dec0_nodma);
94   
9585   UINT32 screen_update_hbarrel(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
9686   UINT32 screen_update_baddudes(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
9787   UINT32 screen_update_birdtry(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
r242959r242960
9989   UINT32 screen_update_hippodrm(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
10090   UINT32 screen_update_slyspy(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
10191   UINT32 screen_update_midres(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
102   
10392   void baddudes_i8751_write(int data);
10493   void birdtry_i8751_write(int data);
10594   void dec0_i8751_write(int data);
10695   void dec0_i8751_reset();
10796   void h6280_decrypt(const char *cputag);
97   DECLARE_WRITE_LINE_MEMBER(sound_irq);
98   DECLARE_WRITE_LINE_MEMBER(sound_irq2);
99   required_device<cpu_device> m_maincpu;
100   required_device<cpu_device> m_audiocpu;
101   optional_device<cpu_device> m_subcpu;
102   optional_device<cpu_device> m_mcu;
103   optional_device<msm5205_device> m_msm;
104   required_device<palette_device> m_palette;
108105};
109106
110107
r242959r242960
117114
118115   UINT8 m_automat_adpcm_byte;
119116   int m_automat_msm5205_vclk_toggle;
120   UINT16 m_automat_scroll_regs[4];
121   
122117   DECLARE_WRITE16_MEMBER(automat_control_w);
123118   DECLARE_WRITE8_MEMBER(automat_adpcm_w);
124119   DECLARE_READ16_MEMBER( automat_palette_r );
r242959r242960
127122   {
128123      COMBINE_DATA(&m_automat_scroll_regs[offset]);
129124   }
130   DECLARE_WRITE_LINE_MEMBER(automat_vclk_cb);
131   
132   virtual void machine_start();
133   
125   UINT16 m_automat_scroll_regs[4];
126
134127   UINT32 screen_update_automat(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
135128   UINT32 screen_update_secretab(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
129   DECLARE_WRITE_LINE_MEMBER(automat_vclk_cb);
136130};
trunk/src/mame/includes/eolith.h
r242959r242960
1010         m_maincpu(*this, "maincpu"),
1111         m_soundcpu(*this, "soundcpu"),
1212         m_qs1000(*this, "qs1000"),
13         m_screen(*this, "screen"),
14         m_palette(*this, "palette"),
1513         m_in0(*this, "IN0"),
1614         m_eepromoutport(*this, "EEPROMOUT"),
1715         m_penx1port(*this, "PEN_X_P1"),
1816         m_peny1port(*this, "PEN_Y_P1"),
1917         m_penx2port(*this, "PEN_X_P2"),
2018         m_peny2port(*this, "PEN_Y_P2"),
21         m_sndbank(*this, "sound_bank")
19         m_sndbank(*this, "sound_bank"),
20         m_screen(*this, "screen"),
21         m_palette(*this, "palette")
2222      { }
2323
24   int m_coin_counter_bit;
25   int m_buffer;
26   UINT32 *m_vram;
2427
28   UINT8 m_sound_data;
29   UINT8 m_data_to_qs1000;
30
2531   required_device<cpu_device> m_maincpu;
2632   optional_device<i8032_device> m_soundcpu;
2733   optional_device<qs1000_device> m_qs1000;
28   required_device<screen_device> m_screen;
29   required_device<palette_device> m_palette;
30   
3134   optional_ioport m_in0; // klondkp doesn't have it
3235   optional_ioport m_eepromoutport;
3336   optional_ioport m_penx1port;
3437   optional_ioport m_peny1port;
3538   optional_ioport m_penx2port;
3639   optional_ioport m_peny2port;
37   
3840   optional_memory_bank m_sndbank;
39   
40   int m_coin_counter_bit;
41   int m_buffer;
42   UINT32 *m_vram;
41   required_device<screen_device> m_screen;
42   required_device<palette_device> m_palette;
4343
44   UINT8 m_sound_data;
45   
46   // speedups - see machine/eolithsp.c
47   int m_speedup_address;
48   int m_speedup_address2;
49   int m_speedup_resume_scanline;
50   int m_speedup_vblank;
51   int m_speedup_scanline;
52   void speedup_read();
53   void init_speedup();
54   DECLARE_CUSTOM_INPUT_MEMBER(eolith_speedup_getvblank);
55   DECLARE_CUSTOM_INPUT_MEMBER(stealsee_speedup_getvblank);
56
5744   DECLARE_READ32_MEMBER(eolith_custom_r);
5845   DECLARE_WRITE32_MEMBER(systemcontrol_w);
5946   DECLARE_WRITE32_MEMBER(sound_w);
r242959r242960
6148   DECLARE_READ32_MEMBER(hidctch3_pen2_r);
6249   DECLARE_WRITE32_MEMBER(eolith_vram_w);
6350   DECLARE_READ32_MEMBER(eolith_vram_r);
51   DECLARE_CUSTOM_INPUT_MEMBER(eolith_speedup_getvblank);
52   DECLARE_CUSTOM_INPUT_MEMBER(stealsee_speedup_getvblank);
53
6454   DECLARE_READ8_MEMBER(sound_cmd_r);
6555   DECLARE_WRITE8_MEMBER(sound_p1_w);
56
6657   DECLARE_READ8_MEMBER(qs1000_p1_r);
6758   DECLARE_WRITE8_MEMBER(qs1000_p1_w);
68   DECLARE_WRITE8_MEMBER(soundcpu_to_qs1000);
69   
7059   DECLARE_DRIVER_INIT(eolith);
7160   DECLARE_DRIVER_INIT(landbrk);
7261   DECLARE_DRIVER_INIT(hidctch3);
7362   DECLARE_DRIVER_INIT(hidctch2);
7463   DECLARE_DRIVER_INIT(hidnc2k);
7564   DECLARE_DRIVER_INIT(landbrka);
76   
7765   DECLARE_MACHINE_RESET(eolith);
7866   DECLARE_VIDEO_START(eolith);
79   
8067   UINT32 screen_update_eolith(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
81   
8268   TIMER_DEVICE_CALLBACK_MEMBER(eolith_speedup);
69   DECLARE_WRITE8_MEMBER(soundcpu_to_qs1000);
8370};
trunk/src/mame/includes/eolithsp.h
r0r242960
1/*----------- defined in drivers/eolithsp.c -----------*/
2
3void eolith_speedup_read(address_space &space);
4void init_eolith_speedup(running_machine &machine);
trunk/src/mame/includes/hyhoo.h
r242959r242960
1010
1111   hyhoo_state(const machine_config &mconfig, device_type type, const char *tag)
1212      : driver_device(mconfig, type, tag),
13      m_clut(*this, "clut"),
1314      m_maincpu(*this, "maincpu"),
1415      m_nb1413m3(*this, "nb1413m3"),
15      m_screen(*this, "screen"),
16      m_clut(*this, "clut") { }
16      m_screen(*this, "screen")   { }
1717
18   required_shared_ptr<UINT8> m_clut;
1819   required_device<cpu_device> m_maincpu;
1920   required_device<nb1413m3_device> m_nb1413m3;
2021   required_device<screen_device> m_screen;
21   required_shared_ptr<UINT8> m_clut;
2222
2323   int m_blitter_destx;
2424   int m_blitter_desty;
r242959r242960
3232   int m_highcolorflag;
3333   int m_flipscreen;
3434   bitmap_rgb32 m_tmpbitmap;
35   
3635   DECLARE_WRITE8_MEMBER(hyhoo_blitter_w);
3736   DECLARE_WRITE8_MEMBER(hyhoo_romsel_w);
38   
3937   DECLARE_CUSTOM_INPUT_MEMBER(nb1413m3_busyflag_r);
40   
4138   virtual void video_start();
42   
4339   UINT32 screen_update_hyhoo(screen_device &screen, bitmap_rgb32 &bitmap, const rectangle &cliprect);
4440   void hyhoo_gfxdraw();
4541
trunk/src/mame/includes/mario.h
r242959r242960
11#ifndef MARIO_H_
22#define MARIO_H_
33
4#include "sound/discrete.h"
45#include "machine/z80dma.h"
56
6#define OLD_SOUND   (1)
7
8#if !OLD_SOUND
9#include "machine/netlist.h"
10#include "netlist/devices/net_lib.h"
11#else
12#include "sound/discrete.h"
13#endif
14
157/*
168 * From the schematics:
179 *
r242959r242960
5042      m_gfxdecode(*this, "gfxdecode"),
5143      m_palette(*this, "palette"),
5244      m_z80dma(*this, "z80dma"),
53#if OLD_SOUND
5445      m_discrete(*this, "discrete"),
55#else
56      m_audio_snd0(*this, "snd_nl:snd0"),
57        m_audio_snd7(*this, "snd_nl:snd7"),
58        m_audio_dac(*this, "snd_nl:dac"),
59#endif
6046      m_spriteram(*this, "spriteram"),
6147      m_videoram(*this, "videoram"),
6248      m_monitor(0) { }
r242959r242960
6753   required_device<gfxdecode_device> m_gfxdecode;
6854   required_device<palette_device> m_palette;
6955   optional_device<z80dma_device> m_z80dma;
70#if OLD_SOUND
7156   optional_device<discrete_device> m_discrete;
72#else
73   optional_device<netlist_mame_logic_input_t> m_audio_snd0;
74    optional_device<netlist_mame_logic_input_t> m_audio_snd7;
75    optional_device<netlist_mame_logic_input_t> m_audio_dac;
76#endif
7757
7858   /* memory pointers */
7959   required_shared_ptr<UINT8> m_spriteram;
trunk/src/mame/includes/nb1413m3.h
r242959r242960
129129
130130   // (static) configuration helpers
131131   static void set_type(device_t &device, int type) { downcast<nb1413m3_device &>(device).m_nb1413m3_type = type; }
132   
133   enum
134   {
135      TIMER_CB
136   };
137132
138133   DECLARE_WRITE8_MEMBER( nmi_clock_w );
139134   DECLARE_READ8_MEMBER( sndrom_r );
r242959r242960
166161
167162protected:
168163   // device-level overrides
164   virtual void device_config_complete();
169165   virtual void device_start();
170166   virtual void device_reset();
171   virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr);
172   
167
173168private:
174169
175170   int m_74ls193_counter;
r242959r242960
181176   int m_gfxradr_h;
182177   int m_gfxrombank;
183178   int m_outcoin_enable;
184   emu_timer *m_timer_cb;
179
185180   TIMER_CALLBACK_MEMBER( timer_callback );
181
186182};
187183
188184/* used in: hyhoo.c, niyanpai.c, pastelg.c, nbmj8688.c, nbmj8891.c, nbmj8991.c, nbmj9195.c*/
trunk/src/mame/includes/pastelg.h
r242959r242960
1212      : driver_device(mconfig, type, tag) ,
1313      m_maincpu(*this, "maincpu"),
1414      m_nb1413m3(*this, "nb1413m3"),
15      m_screen(*this, "screen"),
16      m_clut(*this, "clut") { }
15      m_screen(*this, "screen")   { }
1716
1817   required_device<cpu_device> m_maincpu;
1918   required_device<nb1413m3_device> m_nb1413m3;
2019   required_device<screen_device> m_screen;
21   required_shared_ptr<UINT8> m_clut;
2220
2321   UINT8 m_mux_data;
2422   int m_blitter_destx;
r242959r242960
3331   int m_blitter_direction_y;
3432   int m_palbank;
3533   UINT8 *m_videoram;
34   UINT8 *m_clut;
3635   int m_flipscreen_old;
37   
3836   DECLARE_READ8_MEMBER(pastelg_sndrom_r);
3937   DECLARE_READ8_MEMBER(pastelg_irq_ack_r);
4038   DECLARE_READ8_MEMBER(threeds_inputport1_r);
4139   DECLARE_READ8_MEMBER(threeds_inputport2_r);
4240   DECLARE_WRITE8_MEMBER(threeds_inputportsel_w);
41   DECLARE_WRITE8_MEMBER(pastelg_clut_w);
4342   DECLARE_WRITE8_MEMBER(pastelg_blitter_w);
4443   DECLARE_WRITE8_MEMBER(threeds_romsel_w);
4544   DECLARE_WRITE8_MEMBER(threeds_output_w);
4645   DECLARE_READ8_MEMBER(threeds_rom_readback_r);
4746   DECLARE_WRITE8_MEMBER(pastelg_romsel_w);
48   
4947   DECLARE_CUSTOM_INPUT_MEMBER(nb1413m3_busyflag_r);
5048   DECLARE_CUSTOM_INPUT_MEMBER(nb1413m3_hackbusyflag_r);
51   
52   virtual void machine_start();
5349   virtual void video_start();
54   
5550   DECLARE_PALETTE_INIT(pastelg);
5651   UINT32 screen_update_pastelg(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
57   int pastelg_blitter_src_addr_r();
52   int pastelg_blitter_src_addr_r(address_space &space);
5853   void pastelg_vramflip();
5954   void pastelg_gfxdraw();
6055
r242959r242960
6257   virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr);
6358};
6459
60/*----------- defined in video/pastelg.c -----------*/
61int pastelg_blitter_src_addr_r(address_space &space);
trunk/src/mame/includes/stadhero.h
r242959r242960
1010      m_audiocpu(*this, "audiocpu"),
1111      m_tilegen1(*this, "tilegen1"),
1212      m_spritegen(*this, "spritegen"),
13      m_gfxdecode(*this, "gfxdecode"),
1413      m_spriteram(*this, "spriteram"),
1514      m_pf1_data(*this, "pf1_data"),
16      m_inputs(*this, "INPUTS"),
17      m_coin(*this, "COIN"),
18      m_dsw(*this, "DSW") { }
15      m_gfxdecode(*this, "gfxdecode") { }
1916
2017   required_device<cpu_device> m_maincpu;
2118   required_device<cpu_device> m_audiocpu;
2219   required_device<deco_bac06_device> m_tilegen1;
2320   required_device<deco_mxc06_device> m_spritegen;
24   required_device<gfxdecode_device> m_gfxdecode;
25   
2621   required_shared_ptr<UINT16> m_spriteram;
2722   required_shared_ptr<UINT16> m_pf1_data;
28   
29   required_ioport m_inputs;
30   required_ioport m_coin;
31   required_ioport m_dsw;
23   required_device<gfxdecode_device> m_gfxdecode;
3224
3325   tilemap_t *m_pf1_tilemap;
34   
26   int m_flipscreen;
3527   DECLARE_READ16_MEMBER(stadhero_control_r);
3628   DECLARE_WRITE16_MEMBER(stadhero_control_w);
3729   DECLARE_WRITE16_MEMBER(stadhero_pf1_data_w);
38   DECLARE_WRITE_LINE_MEMBER(irqhandler);
39   
40   virtual void video_start();
41   
4230   TILE_GET_INFO_MEMBER(get_pf1_tile_info);
31   virtual void video_start();
4332   UINT32 screen_update_stadhero(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
33   DECLARE_WRITE_LINE_MEMBER(irqhandler);
4434};
trunk/src/mame/includes/stfight.h
r242959r242960
1010
1111   stfight_state(const machine_config &mconfig, device_type type, const char *tag)
1212      : driver_device(mconfig, type, tag),
13      m_text_char_ram(*this, "text_char_ram"),
14      m_text_attr_ram(*this, "text_attr_ram"),
15      m_tx_vram(*this, "tx_vram"),
16      m_vh_latch_ram(*this, "vh_latch_ram"),
17      m_sprite_ram(*this, "sprite_ram"),
1318      m_maincpu(*this, "maincpu"),
1419      m_audiocpu(*this, "audiocpu"),
1520      m_mcu(*this, "mcu"),
1621      m_msm(*this, "msm"),
1722      m_gfxdecode(*this, "gfxdecode"),
18      m_palette(*this, "palette"),
19      m_text_char_ram(*this, "text_char_ram"),
20      m_text_attr_ram(*this, "text_attr_ram"),
21      m_tx_vram(*this, "tx_vram"),
22      m_vh_latch_ram(*this, "vh_latch_ram"),
23      m_sprite_ram(*this, "sprite_ram") { }
23      m_palette(*this, "palette") { }
2424
25   optional_shared_ptr<UINT8> m_text_char_ram;
26   optional_shared_ptr<UINT8> m_text_attr_ram;
27   optional_shared_ptr<UINT8> m_tx_vram;
28   required_shared_ptr<UINT8> m_vh_latch_ram;
29   required_shared_ptr<UINT8> m_sprite_ram;
2530   required_device<cpu_device> m_maincpu;
2631   required_device<cpu_device> m_audiocpu;
2732   required_device<cpu_device> m_mcu;
2833   required_device<msm5205_device> m_msm;
2934   required_device<gfxdecode_device> m_gfxdecode;
3035   required_device<palette_device> m_palette;
31   
32   optional_shared_ptr<UINT8> m_text_char_ram;
33   optional_shared_ptr<UINT8> m_text_attr_ram;
34   optional_shared_ptr<UINT8> m_tx_vram;
35   required_shared_ptr<UINT8> m_vh_latch_ram;
36   required_shared_ptr<UINT8> m_sprite_ram;
3736
3837   UINT8 *m_decrypt;
3938   UINT8 m_fm_data;
r242959r242960
8079
8180   DECLARE_VIDEO_START(stfight);
8281   DECLARE_VIDEO_START(cshooter);
83   virtual void machine_start();
8482   virtual void machine_reset();
8583   DECLARE_PALETTE_INIT(stfight);
8684   UINT32 screen_update_stfight(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
r242959r242960
108106   UINT8 m_portB_out, m_portB_in;
109107   UINT8 m_portC_out, m_portC_in;
110108   UINT8 m_ddrA, m_ddrB, m_ddrC;
109   UINT8 m_from_main, m_main_sent;
111110
112111protected:
113112   virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr);
trunk/src/mame/includes/stlforce.h
r242959r242960
66public:
77   stlforce_state(const machine_config &mconfig, device_type type, const char *tag)
88      : driver_device(mconfig, type, tag),
9      m_maincpu(*this, "maincpu"),
10      m_oki(*this, "oki"),
11      m_eeprom(*this, "eeprom"),
12      m_gfxdecode(*this, "gfxdecode"),
13      m_palette(*this, "palette"),
149      m_bg_videoram(*this, "bg_videoram"),
1510      m_mlow_videoram(*this, "mlow_videoram"),
1611      m_mhigh_videoram(*this, "mhigh_videoram"),
r242959r242960
1914      m_mlow_scrollram(*this, "mlow_scrollram"),
2015      m_mhigh_scrollram(*this, "mhigh_scrollram"),
2116      m_vidattrram(*this, "vidattrram"),
22      m_spriteram(*this, "spriteram") { }
17      m_spriteram(*this, "spriteram"),
18      m_maincpu(*this, "maincpu"),
19      m_oki(*this, "oki"),
20      m_eeprom(*this, "eeprom"),
21      m_gfxdecode(*this, "gfxdecode"),
22      m_palette(*this, "palette") { }
2323
24   required_device<cpu_device> m_maincpu;
25   required_device<okim6295_device> m_oki;
26   required_device<eeprom_serial_93cxx_device> m_eeprom;
27   required_device<gfxdecode_device> m_gfxdecode;
28   required_device<palette_device> m_palette;
24   tilemap_t *m_bg_tilemap;
25   tilemap_t *m_mlow_tilemap;
26   tilemap_t *m_mhigh_tilemap;
27   tilemap_t *m_tx_tilemap;
2928
3029   required_shared_ptr<UINT16> m_bg_videoram;
3130   required_shared_ptr<UINT16> m_mlow_videoram;
r242959r242960
3534   required_shared_ptr<UINT16> m_mlow_scrollram;
3635   required_shared_ptr<UINT16> m_mhigh_scrollram;
3736   required_shared_ptr<UINT16> m_vidattrram;
37
3838   required_shared_ptr<UINT16> m_spriteram;
39   
40   tilemap_t *m_bg_tilemap;
41   tilemap_t *m_mlow_tilemap;
42   tilemap_t *m_mhigh_tilemap;
43   tilemap_t *m_tx_tilemap;
4439
4540   int m_sprxoffs;
46   
4741   DECLARE_WRITE16_MEMBER(stlforce_bg_videoram_w);
4842   DECLARE_WRITE16_MEMBER(stlforce_mlow_videoram_w);
4943   DECLARE_WRITE16_MEMBER(stlforce_mhigh_videoram_w);
5044   DECLARE_WRITE16_MEMBER(stlforce_tx_videoram_w);
5145   DECLARE_WRITE16_MEMBER(eeprom_w);
5246   DECLARE_WRITE16_MEMBER(oki_bank_w);
53   
5447   DECLARE_DRIVER_INIT(twinbrat);
5548   DECLARE_DRIVER_INIT(stlforce);
56   
5749   TILE_GET_INFO_MEMBER(get_stlforce_bg_tile_info);
5850   TILE_GET_INFO_MEMBER(get_stlforce_mlow_tile_info);
5951   TILE_GET_INFO_MEMBER(get_stlforce_mhigh_tile_info);
6052   TILE_GET_INFO_MEMBER(get_stlforce_tx_tile_info);
61   
6253   virtual void video_start();
6354   UINT32 screen_update_stlforce(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
6455   void draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect );
56   required_device<cpu_device> m_maincpu;
57   required_device<okim6295_device> m_oki;
58   required_device<eeprom_serial_93cxx_device> m_eeprom;
59   required_device<gfxdecode_device> m_gfxdecode;
60   required_device<palette_device> m_palette;
6561};
trunk/src/mame/includes/strnskil.h
r242959r242960
55      : driver_device(mconfig, type, tag),
66      m_maincpu(*this,"maincpu"),
77      m_subcpu(*this,"sub"),
8      m_gfxdecode(*this, "gfxdecode"),
9      m_palette(*this, "palette"),
108      m_videoram(*this, "videoram"),
119      m_xscroll(*this, "xscroll"),
12      m_spriteram(*this, "spriteram") { }
10      m_spriteram(*this, "spriteram"),
11      m_gfxdecode(*this, "gfxdecode"),
12      m_palette(*this, "palette") { }
1313
1414   required_device<cpu_device> m_maincpu;
1515   required_device<cpu_device> m_subcpu;
16   required_device<gfxdecode_device> m_gfxdecode;
17   required_device<palette_device> m_palette;
18   
1916   required_shared_ptr<UINT8> m_videoram;
2017   required_shared_ptr<UINT8> m_xscroll;
2118   required_shared_ptr<UINT8> m_spriteram;
19   required_device<gfxdecode_device> m_gfxdecode;
20   required_device<palette_device> m_palette;
2221
2322   UINT8 m_scrl_ctrl;
2423   tilemap_t *m_bg_tilemap;
2524   UINT8 m_irq_source;
26   
27   TIMER_DEVICE_CALLBACK_MEMBER(strnskil_irq);
2825
2926   DECLARE_READ8_MEMBER(strnskil_d800_r);
3027   DECLARE_READ8_MEMBER(pettanp_protection_r);
r242959r242960
3229   DECLARE_WRITE8_MEMBER(protection_w);
3330   DECLARE_WRITE8_MEMBER(strnskil_videoram_w);
3431   DECLARE_WRITE8_MEMBER(strnskil_scrl_ctrl_w);
35   
3632   DECLARE_DRIVER_INIT(banbam);
3733   DECLARE_DRIVER_INIT(pettanp);
38   
3934   TILE_GET_INFO_MEMBER(get_bg_tile_info);
40   
41   virtual void machine_start();   
4235   virtual void video_start();
4336   DECLARE_PALETTE_INIT(strnskil);
4437   UINT32 screen_update_strnskil(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
38   TIMER_DEVICE_CALLBACK_MEMBER(strnskil_irq);
4539   void draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect);
4640};
trunk/src/mame/includes/vaportra.h
r242959r242960
2323      m_generic_paletteram_16(*this, "paletteram"),
2424      m_generic_paletteram2_16(*this, "paletteram2") { }
2525
26   /* memory pointers */
27   UINT16 *  m_pf1_rowscroll;
28   UINT16 *  m_pf2_rowscroll;
29   UINT16 *  m_pf3_rowscroll;
30   UINT16 *  m_pf4_rowscroll;
31
32   /* misc */
33   UINT16    m_priority[2];
34
2635   /* devices */
2736   required_device<cpu_device> m_maincpu;
2837   required_device<cpu_device> m_audiocpu;
r242959r242960
3140   required_device<deco_mxc06_device> m_spritegen;
3241   required_device<buffered_spriteram16_device> m_spriteram;
3342   required_device<palette_device> m_palette;
34
3543   required_shared_ptr<UINT16> m_generic_paletteram_16;
3644   required_shared_ptr<UINT16> m_generic_paletteram2_16;
3745
38   /* misc */
39   UINT16    m_priority[2];
40
4146   DECLARE_WRITE16_MEMBER(vaportra_sound_w);
4247   DECLARE_READ16_MEMBER(vaportra_control_r);
4348   DECLARE_READ8_MEMBER(vaportra_soundlatch_r);
4449   DECLARE_WRITE16_MEMBER(vaportra_priority_w);
4550   DECLARE_WRITE16_MEMBER(vaportra_palette_24bit_rg_w);
4651   DECLARE_WRITE16_MEMBER(vaportra_palette_24bit_b_w);
47   
4852   DECLARE_DRIVER_INIT(vaportra);
4953   virtual void machine_start();
5054   virtual void machine_reset();
51   
5255   UINT32 screen_update_vaportra(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
5356   void update_24bitcol( int offset );
54   
5557   DECO16IC_BANK_CB_MEMBER(bank_callback);
5658};
trunk/src/mame/includes/xyonix.h
r242959r242960
33public:
44   xyonix_state(const machine_config &mconfig, device_type type, const char *tag)
55      : driver_device(mconfig, type, tag),
6      m_vidram(*this, "vidram"),
67      m_maincpu(*this, "maincpu"),
7      m_gfxdecode(*this, "gfxdecode"),
8      m_vidram(*this, "vidram") { }
8      m_gfxdecode(*this, "gfxdecode") { }
99
10   required_device<cpu_device> m_maincpu;
11   required_device<gfxdecode_device> m_gfxdecode;
12   
1310   required_shared_ptr<UINT8> m_vidram;
14   
1511   tilemap_t *m_tilemap;
1612
1713   int m_e0_data;
1814   int m_credits;
1915   int m_coins;
2016   int m_prev_coin;
21   
22   DECLARE_WRITE8_MEMBER(irqack_w);
23   DECLARE_READ8_MEMBER(io_r);
24   DECLARE_WRITE8_MEMBER(io_w);
25   DECLARE_WRITE8_MEMBER(vidram_w);
26   
27   virtual void machine_start();
17   DECLARE_WRITE8_MEMBER(xyonix_irqack_w);
18   DECLARE_READ8_MEMBER(xyonix_io_r);
19   DECLARE_WRITE8_MEMBER(xyonix_io_w);
20   DECLARE_WRITE8_MEMBER(xyonix_vidram_w);
21   TILE_GET_INFO_MEMBER(get_xyonix_tile_info);
2822   virtual void video_start();
29   TILE_GET_INFO_MEMBER(get_tile_info);
3023   DECLARE_PALETTE_INIT(xyonix);
31   UINT32 screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
32   
24   UINT32 screen_update_xyonix(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect);
3325   void handle_coins(int coin);
26   required_device<cpu_device> m_maincpu;
27   required_device<gfxdecode_device> m_gfxdecode;
3428};
trunk/src/mame/machine/dec0.c
r242959r242960
1414
1515/******************************************************************************/
1616
17void dec0_state::machine_start()
18{
19   save_item(NAME(m_i8751_return));
20   save_item(NAME(m_i8751_command));
21   save_item(NAME(m_i8751_ports));
22}
23
2417READ16_MEMBER(dec0_state::dec0_controls_r)
2518{
2619   switch (offset<<1)
r242959r242960
301294   m_i8751_command=data;
302295
303296   /* Writes to this address cause an IRQ to the i8751 microcontroller */
304   if (m_game == 1) m_mcu->set_input_line(MCS51_INT1_LINE, ASSERT_LINE);
305   if (m_game == 2) baddudes_i8751_write(data);
306   if (m_game == 3) birdtry_i8751_write(data);
297   if (m_GAME == 1) m_mcu->set_input_line(MCS51_INT1_LINE, ASSERT_LINE);
298   if (m_GAME == 2) baddudes_i8751_write(data);
299   if (m_GAME == 3) birdtry_i8751_write(data);
307300
308301   //logerror("%s: warning - write %02x to i8751\n",machine().describe_context(),data);
309302}
r242959r242960
364357   RAM[0x1af] = 0x60; /* RTS prot area */
365358   RAM[0x1db] = 0x60; /* RTS prot area */
366359   RAM[0x21a] = 0x60; /* RTS prot area */
367   
368   save_item(NAME(m_hippodrm_msb));
369   save_item(NAME(m_hippodrm_lsb));
370360}
371361
372362DRIVER_INIT_MEMBER(dec0_state,slyspy)
r242959r242960
377367   /* Slyspy sound cpu has some protection */
378368   RAM[0xf2d] = 0xea;
379369   RAM[0xf2e] = 0xea;
380   
381   save_item(NAME(m_slyspy_state));
382370}
383371
384372DRIVER_INIT_MEMBER(dec0_state,robocop)
r242959r242960
388376
389377DRIVER_INIT_MEMBER(dec0_state,baddudes)
390378{
391   m_game = 2;
379   m_GAME = 2;
392380}
393381
394382DRIVER_INIT_MEMBER(dec0_state,hbarrel)
395383{
396   m_game = 1;
384   m_GAME = 1;
397385}
398386
399387DRIVER_INIT_MEMBER(dec0_state,birdtry)
400388{
401   m_game=3;
389   m_GAME=3;
402390}
trunk/src/mame/machine/nb1413m3.c
r242959r242960
4242{
4343}
4444
45//-------------------------------------------------
46//  device_config_complete - perform any
47//  operations now that the configuration is
48//  complete
49//-------------------------------------------------
4550
51void nb1413m3_device::device_config_complete()
52{
53}
54
4655//-------------------------------------------------
4756//  device_start - device-specific startup
4857//-------------------------------------------------
4958
5059void nb1413m3_device::device_start()
5160{
52   m_timer_cb = timer_alloc(TIMER_CB);
53   synchronize(TIMER_CB);
61   machine().scheduler().synchronize(timer_expired_delegate(FUNC(nb1413m3_device::timer_callback), this));
5462
5563   save_item(NAME(m_nb1413m3_type));
5664   save_item(NAME(m_sndrombank1));
r242959r242960
97105    DEVICE HANDLERS
98106*****************************************************************************/
99107
100void nb1413m3_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
101{
102   switch (id)
103   {
104      case TIMER_CB:
105         timer_callback(ptr, param);
106         break;
107      default:
108         assert_always(FALSE, "Unknown id in nb1413m3_device::device_timer");
109   }
110}
111
112108/* TODO: is all of this actually programmable? */
113109TIMER_CALLBACK_MEMBER( nb1413m3_device::timer_callback )
114110{
115   m_timer_cb->adjust(attotime::from_hz(NB1413M3_TIMER_BASE) * 256);
111   machine().scheduler().timer_set(attotime::from_hz(NB1413M3_TIMER_BASE) * 256, timer_expired_delegate(FUNC(nb1413m3_device::timer_callback), this));
116112
117113   m_74ls193_counter++;
118114   m_74ls193_counter &= 0x0f;
trunk/src/mame/machine/stfight.c
r242959r242960
11/***************************************************************************
22
3  stfight.c
3  machine.c
44
55  Functions to emulate general aspects of the machine (RAM, ROM, interrupts,
66  I/O ports)
r242959r242960
6363            ( ( ( src ^ A ) >> 1 ) & 0x08 ) |
6464            ( ~( ( src >> 6 ) ^ A ) & 0x01 );
6565   }
66   
6766}
6867
6968DRIVER_INIT_MEMBER(stfight_state,stfight)
r242959r242960
7574{
7675}
7776
78void stfight_state::machine_start()
79{
80   save_item(NAME(m_fm_data));
81   save_item(NAME(m_cpu_to_mcu_data));
82   save_item(NAME(m_cpu_to_mcu_empty));
83   save_item(NAME(m_adpcm_data_offs));
84   save_item(NAME(m_adpcm_nibble));
85   save_item(NAME(m_adpcm_reset));
86   save_item(NAME(m_coin_state));
87   save_item(NAME(m_sprite_base));
88   save_item(NAME(m_portA_out));
89   save_item(NAME(m_portA_in));
90   save_item(NAME(m_portB_out));
91   save_item(NAME(m_portB_in));
92   save_item(NAME(m_portC_out));
93   save_item(NAME(m_portC_in));
94   save_item(NAME(m_ddrA));
95   save_item(NAME(m_ddrB));
96   save_item(NAME(m_ddrC));
97}
98
9977void stfight_state::machine_reset()
10078{
10179   m_fm_data = 0;
trunk/src/mame/mame.lst
r242959r242960
54465446starhrsp        // 2003.12.01 Star Horse Progress (satellite) (Rev A)
54475447puyofevp        // 2003.?? Puyo Puyo Fever (prototype)
54485448            // 2003.?? Dragon Treasure
5449            // 2003.?? Rabbit 2
54505449cfield          // 2004.06 Chaos Field
54515450tetkiwam        // 2004.06 Tetris Kiwamemichi (Arcade TV Game List - P.88, Right, 11 from bottom)
54525451trizeal         // 2004.09 Trizeal
r242959r242960
55135512
55145513// NAOMI 2
55155514naomi2          // 2001.?? Naomi 2 BIOS
5516vstrik3        // 2001.04.06 Virtua Striker 3 Ver. 2002
5515vstrik3c        // 2001.04 Virtua Striker 3 (cartridge)
55175516vstrik3cb       // 2001.04 Virtua Striker 3 (Rev B) (cartridge)
5518vstrik3c        // 2001.04 Virtua Striker 3 (Rev C) (cartridge)
5517vstrik3        // 2001.04.06 Virtua Striker 3 Ver. 2002
55195518wldrider        // 2001.05 Wild Riders
55205519clubkrte        // 2001.06 Club Kart: European Session
5521clubkrtd        // 2001.06 Club Kart: European Session (Rev D)
55225520clubkrtc        // 2001.?? Club Kart: European Session (Rev C)
5521clubkrtd        // 2001.06 Club Kart: European Session (Rev D)
55235522beachspi        // 2001.07 Beach Spikers
55245523vf4cart         // 2001.08.02 Virtua Fighter 4 (cartridge)
55255524vf4             // 2001.08.02 Virtua Fighter 4 (GD-ROM)
r242959r242960
85678566butasan         // (c) 1987 Jaleco - english subtitled
85688567butasanj        // (c) 1987 Jaleco
85698568psychic5        // (c) 1987 Jaleco
8570psychic5j       // (c) 1987 Jaleco
8569psychic5a       // (c) 1987 Jaleco
85718570bombsa          // (c) 1988 Jaleco
85728571ginganin        // (c) 1987 Jaleco
85738572ginganina       // (c) 1987 Jaleco
r242959r242960
1105411053pepp0014        // (c) 1987 IGT - International Game Technology
1105511054pepp0014a       // (c) 1987 IGT - International Game Technology
1105611055pepp0023        // (c) 1987 IGT - International Game Technology
11057pepp0038        // (c) 1987 IGT - International Game Technology
1105811056pepp0040        // (c) 1987 IGT - International Game Technology
1105911057pepp0040a       // (c) 1987 IGT - International Game Technology
1106011058pepp0041        // (c) 1987 IGT - International Game Technology
r242959r242960
1108411082pepp0083        // (c) 1987 IGT - International Game Technology
1108511083pepp0103        // (c) 1987 IGT - International Game Technology
1108611084pepp0116        // (c) 1987 IGT - International Game Technology
11087pepp0116a       // (c) 1987 IGT - International Game Technology
1108811085pepp0118        // (c) 1987 IGT - International Game Technology
1108911086pepp0120        // (c) 1987 IGT - International Game Technology
1109011087pepp0125        // (c) 1987 IGT - International Game Technology
trunk/src/mame/video/dec0.c
r242959r242960
339339VIDEO_START_MEMBER(dec0_state,dec0_nodma)
340340{
341341   save_item(NAME(m_pri));
342
342343   m_buffered_spriteram = m_spriteram;
343   save_pointer(NAME(m_buffered_spriteram), 0x800/2);
344344}
345345
346346VIDEO_START_MEMBER(dec0_state,dec0)
347347{
348   save_item(NAME(m_pri));
348   VIDEO_START_CALL_MEMBER(dec0_nodma);
349349   m_buffered_spriteram = auto_alloc_array(machine(), UINT16, 0x800/2);
350   save_pointer(NAME(m_buffered_spriteram), 0x800/2);
351350}
352351
353352/******************************************************************************/
trunk/src/mame/video/decbac06.c
r242959r242960
116116   save_pointer(NAME(m_pf_data), 0x4000/2);
117117   save_pointer(NAME(m_pf_rowscroll), 0x2000/2);
118118   save_pointer(NAME(m_pf_colscroll), 0x2000/2);
119   save_item(NAME(m_pf_control_0));
120   save_item(NAME(m_pf_control_1));
121   save_item(NAME(m_gfxcolmask));
119   save_pointer(NAME(m_pf_control_0), 8);
120   save_pointer(NAME(m_pf_control_1), 8);
121
122122   save_item(NAME(m_rambank));
123123}
124124
trunk/src/mame/video/eolith.c
r242959r242960
3333VIDEO_START_MEMBER(eolith_state,eolith)
3434{
3535   m_vram = auto_alloc_array(machine(), UINT32, 0x40000*2/4);
36   save_pointer(NAME(m_vram), 0x40000*2/4);
37   save_item(NAME(m_buffer));
3836}
3937
4038UINT32 eolith_state::screen_update_eolith(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
4139{
42   for (int y = 0; y < 240; y++)
40   int y;
41
42   for (y = 0; y < 240; y++)
4343   {
44      int x;
4445      UINT32 *src = &m_vram[(m_buffer ? 0 : 0x10000) | (y * (336 / 2))];
4546      UINT16 *dest = &bitmap.pix16(y);
4647
47      for (int x = 0; x < 320; x += 2)
48      for (x = 0; x < 320; x += 2)
4849      {
4950         dest[0] = (*src >> 16) & 0x7fff;
5051         dest[1] = (*src >>  0) & 0x7fff;
trunk/src/mame/video/hyhoo.c
r242959r242960
226226void hyhoo_state::video_start()
227227{
228228   m_screen->register_screen_bitmap(m_tmpbitmap);
229   save_item(NAME(m_blitter_destx));
230   save_item(NAME(m_blitter_desty));
231   save_item(NAME(m_blitter_sizex));
232   save_item(NAME(m_blitter_sizey));
233   save_item(NAME(m_blitter_src_addr));
234   save_item(NAME(m_blitter_direction_x));
235   save_item(NAME(m_blitter_direction_y));
236   save_item(NAME(m_gfxrom));
237   save_item(NAME(m_dispflag));
238   save_item(NAME(m_highcolorflag));
239   save_item(NAME(m_flipscreen));
240   save_item(NAME(m_tmpbitmap));
241229}
242230
243231
trunk/src/mame/video/pastelg.c
r242959r242960
4242   }
4343}
4444
45WRITE8_MEMBER(pastelg_state::pastelg_clut_w)
46{
47   m_clut[offset] = data;
48}
49
4550/******************************************************************************
4651
4752
4853******************************************************************************/
49int pastelg_state::pastelg_blitter_src_addr_r()
54int pastelg_state::pastelg_blitter_src_addr_r(address_space &space)
5055{
5156   return m_blitter_src_addr;
5257}
r242959r242960
283288   int height = m_screen->height();
284289
285290   m_videoram = auto_alloc_array_clear(machine(), UINT8, width * height);
286   
287   save_item(NAME(m_blitter_desty));
288   save_item(NAME(m_blitter_sizex));
289   save_item(NAME(m_blitter_sizey));
290   save_item(NAME(m_blitter_src_addr));
291   save_item(NAME(m_gfxrom));
292   save_item(NAME(m_dispflag));
293   save_item(NAME(m_flipscreen));
294   save_item(NAME(m_blitter_direction_x));
295   save_item(NAME(m_blitter_direction_y));
296   save_item(NAME(m_palbank));
297   save_pointer(NAME(m_videoram), width*height);
298   save_item(NAME(m_flipscreen_old));
291   m_clut = auto_alloc_array(machine(), UINT8, 0x10);
299292}
300293
301294/******************************************************************************
trunk/src/mame/video/stadhero.c
r242959r242960
2020
2121UINT32 stadhero_state::screen_update_stadhero(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
2222{
23//  machine().tilemap().set_flip_all(m_flipscreen ? (TILEMAP_FLIPY | TILEMAP_FLIPX) : 0);
24
2325   flip_screen_set(m_tilegen1->get_flip_state());
2426
2527   m_tilegen1->set_bppmultmask(0x8, 0x7);
r242959r242960
5456
5557void stadhero_state::video_start()
5658{
57   m_pf1_tilemap = &machine().tilemap().create(m_gfxdecode, tilemap_get_info_delegate(FUNC(stadhero_state::get_pf1_tile_info),this),TILEMAP_SCAN_ROWS, 8, 8,32,32);
59   m_pf1_tilemap =     &machine().tilemap().create(m_gfxdecode, tilemap_get_info_delegate(FUNC(stadhero_state::get_pf1_tile_info),this),TILEMAP_SCAN_ROWS, 8, 8,32,32);
5860   m_pf1_tilemap->set_transparent_pen(0);
5961}
6062
trunk/src/mame/video/strnskil.c
r242959r242960
4141
4242WRITE8_MEMBER(strnskil_state::strnskil_videoram_w)
4343{
44   m_videoram[offset] = data;
44   UINT8 *videoram = m_videoram;
45   videoram[offset] = data;
4546   m_bg_tilemap->mark_tile_dirty(offset / 2);
4647}
4748
r242959r242960
5859
5960TILE_GET_INFO_MEMBER(strnskil_state::get_bg_tile_info)
6061{
61   int attr = m_videoram[tile_index * 2];
62   int code = m_videoram[(tile_index * 2) + 1] + ((attr & 0x60) << 3);
62   UINT8 *videoram = m_videoram;
63   int attr = videoram[tile_index * 2];
64   int code = videoram[(tile_index * 2) + 1] + ((attr & 0x60) << 3);
6365   int color = (attr & 0x1f) | ((attr & 0x80) >> 2);
6466
6567   SET_TILE_INFO_MEMBER(0, code, color, 0);
r242959r242960
7577
7678void strnskil_state::draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect)
7779{
80   UINT8 *spriteram = m_spriteram;
7881   int offs;
7982
8083   for (offs = 0x60; offs < 0x100; offs += 4)
8184   {
82      int code = m_spriteram[offs + 1];
83      int color = m_spriteram[offs + 2] & 0x3f;
85      int code = spriteram[offs + 1];
86      int color = spriteram[offs + 2] & 0x3f;
8487      int flipx = flip_screen_x();
8588      int flipy = flip_screen_y();
8689
87      int sx = m_spriteram[offs + 3];
88      int sy = m_spriteram[offs];
90      int sx = spriteram[offs + 3];
91      int sy = spriteram[offs];
8992      int px, py;
9093
9194      if (flip_screen())
r242959r242960
115118
116119UINT32 strnskil_state::screen_update_strnskil(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
117120{
121   int row;
118122   const UINT8 *usr1 = memregion("user1")->base();
119123
120   for (int row = 0; row < 32; row++)
124   for (row = 0; row < 32; row++)
121125   {
122126      if (m_scrl_ctrl != 0x07)
123127      {
trunk/src/mame/video/tia.c
r242959r242960
430430   helper[0] = auto_bitmap_ind16_alloc(machine(), cx, TIA_MAX_SCREEN_HEIGHT);
431431   helper[1] = auto_bitmap_ind16_alloc(machine(), cx, TIA_MAX_SCREEN_HEIGHT);
432432   helper[2] = auto_bitmap_ind16_alloc(machine(), cx, TIA_MAX_SCREEN_HEIGHT);
433   
434   register_save_state();
435433}
436434
437435
r242959r242960
667665
668666int tia_video_device::current_x()
669667{
670   return 3 * ((machine().device<cpu_device>("maincpu")->total_cycles() - frame_cycles) % 76) - 68;
668   return 3 * ((machine().firstcpu->total_cycles() - frame_cycles) % 76) - 68;
671669}
672670
673671
674672int tia_video_device::current_y()
675673{
676   return (machine().device<cpu_device>("maincpu")->total_cycles() - frame_cycles) / 76;
674   return (machine().firstcpu->total_cycles() - frame_cycles) / 76;
677675}
678676
679677
r242959r242960
10121010
10131011WRITE8_MEMBER( tia_video_device::WSYNC_w )
10141012{
1015   int cycles = machine().device<cpu_device>("maincpu")->total_cycles() - frame_cycles;
1013   int cycles = machine().firstcpu->total_cycles() - frame_cycles;
10161014
10171015   if (cycles % 76)
10181016   {
r242959r242960
10531051{
10541052   if (data & 0x80)
10551053   {
1056      paddle_start = machine().device<cpu_device>("maincpu")->total_cycles();
1054      paddle_start = machine().firstcpu->total_cycles();
10571055   }
10581056   if ( ! ( VBLANK & 0x40 ) ) {
10591057      INPT4 = 0x80;
r242959r242960
18061804
18071805READ8_MEMBER( tia_video_device::INPT_r )
18081806{
1809   UINT64 elapsed = machine().device<cpu_device>("maincpu")->total_cycles() - paddle_start;
1807   UINT64 elapsed = machine().firstcpu->total_cycles() - paddle_start;
18101808   UINT16 input = TIA_INPUT_PORT_ALWAYS_ON;
18111809   if ( !m_read_input_port_cb.isnull() )
18121810   {
r242959r242960
21792177   COLUBK = 0;
21802178   COLUPF = 0;
21812179}
2182
2183
2184void tia_video_device::register_save_state()
2185{
2186   save_item(NAME(p0gfx.start_pixel));
2187   save_item(NAME(p0gfx.start_drawing));
2188   save_item(NAME(p0gfx.size));
2189   save_item(NAME(p0gfx.skipclip));
2190   save_item(NAME(p1gfx.start_pixel));
2191   save_item(NAME(p1gfx.start_drawing));
2192   save_item(NAME(p1gfx.size));
2193   save_item(NAME(p1gfx.skipclip));
2194   save_item(NAME(frame_cycles));
2195   save_item(NAME(paddle_start));
2196   save_item(NAME(horzP0));
2197   save_item(NAME(horzP1));
2198   save_item(NAME(horzM0));
2199   save_item(NAME(horzM1));
2200   save_item(NAME(horzBL));
2201   save_item(NAME(motclkP0));
2202   save_item(NAME(motclkP1));
2203   save_item(NAME(motclkM0));
2204   save_item(NAME(motclkM1));
2205   save_item(NAME(motclkBL));
2206   save_item(NAME(startP0));
2207   save_item(NAME(startP1));
2208   save_item(NAME(startM0));
2209   save_item(NAME(startM1));
2210   save_item(NAME(skipclipP0));
2211   save_item(NAME(skipclipP1));
2212   save_item(NAME(skipM0delay));
2213   save_item(NAME(skipM1delay));
2214   save_item(NAME(current_bitmap));
2215   save_item(NAME(prev_x));
2216   save_item(NAME(prev_y));
2217   save_item(NAME(VSYNC));
2218   save_item(NAME(VBLANK));
2219   save_item(NAME(COLUP0));
2220   save_item(NAME(COLUP1));
2221   save_item(NAME(COLUBK));
2222   save_item(NAME(COLUPF));
2223   save_item(NAME(CTRLPF));
2224   save_item(NAME(GRP0));
2225   save_item(NAME(GRP1));
2226   save_item(NAME(REFP0));
2227   save_item(NAME(REFP1));
2228   save_item(NAME(HMP0));
2229   save_item(NAME(HMP1));
2230   save_item(NAME(HMM0));
2231   save_item(NAME(HMM1));
2232   save_item(NAME(HMBL));
2233   save_item(NAME(VDELP0));
2234   save_item(NAME(VDELP1));
2235   save_item(NAME(VDELBL));
2236   save_item(NAME(NUSIZ0));
2237   save_item(NAME(NUSIZ1));
2238   save_item(NAME(ENAM0));
2239   save_item(NAME(ENAM1));
2240   save_item(NAME(ENABL));
2241   save_item(NAME(CXM0P));
2242   save_item(NAME(CXM1P));
2243   save_item(NAME(CXP0FB));
2244   save_item(NAME(CXP1FB));
2245   save_item(NAME(CXM0FB));
2246   save_item(NAME(CXM1FB));
2247   save_item(NAME(CXBLPF));
2248   save_item(NAME(CXPPMM));
2249   save_item(NAME(RESMP0));
2250   save_item(NAME(RESMP1));
2251   save_item(NAME(PF0));
2252   save_item(NAME(PF1));
2253   save_item(NAME(PF2));
2254   save_item(NAME(INPT4));
2255   save_item(NAME(INPT5));
2256   save_item(NAME(prevGRP0));
2257   save_item(NAME(prevGRP1));
2258   save_item(NAME(prevENABL));
2259   save_item(NAME(HMOVE_started));
2260   save_item(NAME(HMOVE_started_previous));
2261   save_item(NAME(HMP0_latch));
2262   save_item(NAME(HMP1_latch));
2263   save_item(NAME(HMM0_latch));
2264   save_item(NAME(HMM1_latch));
2265   save_item(NAME(HMBL_latch));
2266   save_item(NAME(REFLECT));
2267   save_item(NAME(NUSIZx_changed));
2268}
trunk/src/mame/video/tia.h
r242959r242960
199199   bitmap_ind16 *helper[3];
200200
201201   UINT16 screen_height;
202   
203   void register_save_state();
204202};
205203
206204class tia_pal_video_device : public tia_video_device
trunk/src/mame/video/xyonix.c
r242959r242960
3131}
3232
3333
34TILE_GET_INFO_MEMBER(xyonix_state::get_tile_info)
34TILE_GET_INFO_MEMBER(xyonix_state::get_xyonix_tile_info)
3535{
3636   int tileno;
3737   int attr = m_vidram[tile_index+0x1000+1];
r242959r242960
4141   SET_TILE_INFO_MEMBER(0,tileno,attr >> 4,0);
4242}
4343
44WRITE8_MEMBER(xyonix_state::vidram_w)
44WRITE8_MEMBER(xyonix_state::xyonix_vidram_w)
4545{
4646   m_vidram[offset] = data;
4747   m_tilemap->mark_tile_dirty((offset-1)&0x0fff);
r242959r242960
4949
5050void xyonix_state::video_start()
5151{
52   m_tilemap = &machine().tilemap().create(m_gfxdecode, tilemap_get_info_delegate(FUNC(xyonix_state::get_tile_info),this), TILEMAP_SCAN_ROWS, 4, 8, 80, 32);
52   m_tilemap = &machine().tilemap().create(m_gfxdecode, tilemap_get_info_delegate(FUNC(xyonix_state::get_xyonix_tile_info),this), TILEMAP_SCAN_ROWS, 4, 8, 80, 32);
5353}
5454
55UINT32 xyonix_state::screen_update(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
55UINT32 xyonix_state::screen_update_xyonix(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
5656{
5757   m_tilemap->draw(screen, bitmap, cliprect, 0, 0);
5858   return 0;
trunk/src/mess/drivers/a2600.c
r242959r242960
209209         if ( supported_screen_heights[i] != m_current_screen_height )
210210         {
211211            m_current_screen_height = supported_screen_heights[i];
212//              m_screen->configure(228, m_current_screen_height, &visarea[i], HZ_TO_ATTOSECONDS( MASTER_CLOCK_NTSC ) * 228 * m_current_screen_height );
212//              machine.first_screen()->configure(228, m_current_screen_height, &visarea[i], HZ_TO_ATTOSECONDS( MASTER_CLOCK_NTSC ) * 228 * m_current_screen_height );
213213         }
214214      }
215215   }
r242959r242960
226226         if ( supported_screen_heights[i] != m_current_screen_height )
227227         {
228228            m_current_screen_height = supported_screen_heights[i];
229//              m_screen->configure(228, m_current_screen_height, &visarea[i], HZ_TO_ATTOSECONDS( MASTER_CLOCK_PAL ) * 228 * m_current_screen_height );
229//              machine.first_screen()->configure(228, m_current_screen_height, &visarea[i], HZ_TO_ATTOSECONDS( MASTER_CLOCK_PAL ) * 228 * m_current_screen_height );
230230         }
231231      }
232232   }
r242959r242960
316316
317317   /* Banks may have changed, reset the cpu so it uses the correct reset vector */
318318   m_maincpu->reset();
319   
320   save_item(NAME(m_current_screen_height));
321319}
322320
323321
r242959r242960
543541#define rom_a2600p rom_a2600
544542
545543/*    YEAR  NAME    PARENT  COMPAT  MACHINE INPUT   INIT    COMPANY     FULLNAME */
546CONS( 1977, a2600,  0,      0,      a2600,  a2600, driver_device,   0,      "Atari",    "Atari 2600 (NTSC)" , GAME_SUPPORTS_SAVE )
547CONS( 1978, a2600p, a2600,  0,      a2600p, a2600, driver_device,   0,      "Atari",    "Atari 2600 (PAL)",   GAME_SUPPORTS_SAVE )
544CONS( 1977, a2600,  0,      0,      a2600,  a2600, driver_device,   0,      "Atari",    "Atari 2600 (NTSC)" , 0)
545CONS( 1978, a2600p, a2600,  0,      a2600p, a2600, driver_device,   0,      "Atari",    "Atari 2600 (PAL)",   0)
trunk/src/mess/drivers/apple3.c
r242959r242960
102102   MCFG_FLOPPY_DRIVE_ADD("2", a3_floppies, "525", apple3_state::floppy_formats)
103103   MCFG_FLOPPY_DRIVE_ADD("3", a3_floppies, "525", apple3_state::floppy_formats)
104104
105   /* softlist for fdc */
106   MCFG_SOFTWARE_LIST_ADD("flop525_list","apple3")
107
108105   /* acia */
109106   MCFG_DEVICE_ADD("acia", MOS6551, 0)
110107   MCFG_MOS6551_XTAL(XTAL_1_8432MHz) // HACK: The schematic shows an external clock generator but using a XTAL is faster to emulate.
trunk/src/mess/drivers/comp4.c
r242959r242960
141141static INPUT_PORTS_START( comp4 )
142142   PORT_START("IN.0") // O1
143143   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_R) PORT_CODE(KEYCODE_DEL) PORT_CODE(KEYCODE_DEL_PAD) PORT_NAME("R")
144   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CODE(KEYCODE_1_PAD) PORT_NAME("1")
145   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CODE(KEYCODE_4_PAD) PORT_NAME("4")
144   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CODE(KEYCODE_1_PAD) PORT_NAME("1")
145   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CODE(KEYCODE_4_PAD) PORT_NAME("4")
146146   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_7) PORT_CODE(KEYCODE_7_PAD) PORT_NAME("7")
147147
148148   PORT_START("IN.1") // O2
149149   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_0) PORT_CODE(KEYCODE_0_PAD) PORT_NAME("0")
150   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CODE(KEYCODE_2_PAD) PORT_NAME("2")
151   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CODE(KEYCODE_5_PAD) PORT_NAME("5")
150   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CODE(KEYCODE_2_PAD) PORT_NAME("2")
151   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CODE(KEYCODE_5_PAD) PORT_NAME("5")
152152   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_8) PORT_CODE(KEYCODE_8_PAD) PORT_NAME("8")
153153
154154   PORT_START("IN.2") // O3
155155   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_CODE(KEYCODE_ENTER) PORT_CODE(KEYCODE_ENTER_PAD) PORT_NAME("E")
156   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CODE(KEYCODE_3_PAD) PORT_NAME("3")
157   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_6_PAD) PORT_NAME("6")
156   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_3_PAD) PORT_NAME("3")
157   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CODE(KEYCODE_6_PAD) PORT_NAME("6")
158158   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_9) PORT_CODE(KEYCODE_9_PAD) PORT_NAME("9")
159159INPUT_PORTS_END
160160
trunk/src/mess/drivers/elecdet.c
r242959r242960
1// license:BSD-3-Clause
2// copyright-holders:hap
3/***************************************************************************
4
5  Ideal Electronic Detective
6  * TMS0980NLL MP6100A (die labeled 0980B-00)
7  hardware (and concept) is very similar to Parker Bros Stop Thief
8
9  This is an electronic board game. It requires game cards with suspect info,
10  and good old pen and paper to record game progress. To start the game, enter
11  difficulty(1-3), then number of players(1-4), then [ENTER]. Refer to the
12  manual for more information.
13
14
15  TODO:
16  - MCU clock is unknown
17
18***************************************************************************/
19
20#include "emu.h"
21#include "cpu/tms0980/tms0980.h"
22#include "sound/speaker.h"
23
24#include "elecdet.lh"
25
26// master clock is unknown, the value below is an approximation
27#define MASTER_CLOCK (425000)
28
29
30class elecdet_state : public driver_device
31{
32public:
33   elecdet_state(const machine_config &mconfig, device_type type, const char *tag)
34      : driver_device(mconfig, type, tag),
35      m_maincpu(*this, "maincpu"),
36      m_button_matrix(*this, "IN"),
37      m_speaker(*this, "speaker")
38   { }
39
40   required_device<cpu_device> m_maincpu;
41   required_ioport_array<5> m_button_matrix;
42   required_device<speaker_sound_device> m_speaker;
43
44   UINT16 m_o;
45   bool m_power_on;
46
47   UINT16 m_leds_state[0x10];
48   UINT16 m_leds_cache[0x10];
49   UINT8 m_leds_decay[0x100];
50
51   DECLARE_READ8_MEMBER(read_k);
52   DECLARE_WRITE16_MEMBER(write_o);
53   DECLARE_WRITE16_MEMBER(write_r);
54
55   DECLARE_INPUT_CHANGED_MEMBER(power_button);
56   DECLARE_WRITE_LINE_MEMBER(auto_power_off);
57
58   TIMER_DEVICE_CALLBACK_MEMBER(leds_decay_tick);
59   void leds_update();
60
61   virtual void machine_reset();
62   virtual void machine_start();
63};
64
65
66
67/***************************************************************************
68
69  LEDs
70
71***************************************************************************/
72
73// The device strobes the outputs very fast, it is unnoticeable to the user.
74// To prevent flickering here, we need to simulate a decay.
75
76// decay time, in steps of 10ms
77#define LEDS_DECAY_TIME 4
78
79void elecdet_state::leds_update()
80{
81   UINT16 active_state[0x10];
82
83   for (int i = 0; i < 0x10; i++)
84   {
85      active_state[i] = 0;
86
87      for (int j = 0; j < 0x10; j++)
88      {
89         int di = j << 4 | i;
90
91         // turn on powered leds
92         if (m_power_on && m_leds_state[i] >> j & 1)
93            m_leds_decay[di] = LEDS_DECAY_TIME;
94
95         // determine active state
96         int ds = (m_leds_decay[di] != 0) ? 1 : 0;
97         active_state[i] |= (ds << j);
98      }
99   }
100
101   // on difference, send to output
102   for (int i = 0; i < 0x10; i++)
103      if (m_leds_cache[i] != active_state[i])
104         output_set_digit_value(i, active_state[i]);
105
106   memcpy(m_leds_cache, active_state, sizeof(m_leds_cache));
107}
108
109TIMER_DEVICE_CALLBACK_MEMBER(elecdet_state::leds_decay_tick)
110{
111   // slowly turn off unpowered leds
112   for (int i = 0; i < 0x100; i++)
113      if (!(m_leds_state[i & 0xf] >> (i>>4) & 1) && m_leds_decay[i])
114         m_leds_decay[i]--;
115
116   leds_update();
117}
118
119
120
121/***************************************************************************
122
123  I/O
124
125***************************************************************************/
126
127READ8_MEMBER(elecdet_state::read_k)
128{
129   // the Vss row is always on
130   UINT8 k = m_button_matrix[4]->read();
131
132   // read selected button rows
133   for (int i = 0; i < 4; i++)
134   {
135      const int ki[4] = { 0, 1, 4, 6 };
136      if (m_o >> ki[i] & 1)
137         k |= m_button_matrix[i]->read();
138   }
139
140   return k;
141}
142
143WRITE16_MEMBER(elecdet_state::write_r)
144{
145   // R0-R6: select digit
146   UINT8 o = BITSWAP8(m_o,7,5,2,1,4,0,6,3) & 0x7f;
147   for (int i = 0; i < 7; i++)
148      m_leds_state[i] = (data >> i & 1) ? o : 0;
149
150   leds_update();
151
152   // R7,R8: speaker on
153   m_speaker->level_w((data & 0x180 && m_o & 0x80) ? 1 : 0);
154}
155
156WRITE16_MEMBER(elecdet_state::write_o)
157{
158   // O0,O1,O4,O6: input mux
159   // O0-O6: led segments A-G
160   // O7: speaker out
161   m_o = data;
162}
163
164
165
166/***************************************************************************
167
168  Inputs
169
170***************************************************************************/
171
172INPUT_CHANGED_MEMBER(elecdet_state::power_button)
173{
174   m_power_on = (bool)(FPTR)param;
175   m_maincpu->set_input_line(INPUT_LINE_RESET, m_power_on ? CLEAR_LINE : ASSERT_LINE);
176}
177
178/* physical button layout and labels is like this:
179
180    [1]   [2]   [3]   [SUSPECT]
181    [4]   [5]   [6]   [PRIVATE QUESTION]
182    [7]   [8]   [9]   [I ACCUSE]
183                [0]   [ENTER]
184    [ON]  [OFF]       [END TURN]
185*/
186
187static INPUT_PORTS_START( elecdet )
188   PORT_START("IN.0") // O0 pin18
189   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_4) PORT_CODE(KEYCODE_4_PAD) PORT_NAME("4")
190   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED )
191   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_6) PORT_CODE(KEYCODE_6_PAD) PORT_NAME("6")
192   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_Q) PORT_NAME("Private Question")
193   PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_5) PORT_CODE(KEYCODE_5_PAD) PORT_NAME("5")
194
195   PORT_START("IN.1") // O1 pin17
196   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_UNUSED )
197   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED )
198   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_0) PORT_CODE(KEYCODE_0_PAD) PORT_NAME("0")
199   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_ENTER) PORT_CODE(KEYCODE_ENTER_PAD) PORT_NAME("Enter")
200   PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_UNUSED )
201
202   PORT_START("IN.2") // O4 pin14
203   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_7) PORT_CODE(KEYCODE_7_PAD) PORT_NAME("7")
204   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED )
205   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_9) PORT_CODE(KEYCODE_9_PAD) PORT_NAME("9")
206   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_A) PORT_NAME("I Accuse")
207   PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_8) PORT_CODE(KEYCODE_8_PAD) PORT_NAME("8")
208
209   PORT_START("IN.3") // O6 pin12
210   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_1) PORT_CODE(KEYCODE_1_PAD) PORT_NAME("1")
211   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED )
212   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_3) PORT_CODE(KEYCODE_3_PAD) PORT_NAME("3")
213   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_S) PORT_NAME("Suspect")
214   PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_2) PORT_CODE(KEYCODE_2_PAD) PORT_NAME("2")
215
216   // note: even though power buttons are on the matrix, they are not CPU-controlled
217   PORT_START("IN.4") // Vss!
218   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_PGUP) PORT_NAME("On") PORT_CHANGED_MEMBER(DEVICE_SELF, elecdet_state, power_button, (void *)true)
219   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_UNUSED )
220   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_UNUSED )
221   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_E) PORT_NAME("End Turn")
222   PORT_BIT( 0x10, IP_ACTIVE_HIGH, IPT_KEYBOARD ) PORT_CODE(KEYCODE_PGDN) PORT_NAME("Off") PORT_CHANGED_MEMBER(DEVICE_SELF, elecdet_state, power_button, (void *)false)
223INPUT_PORTS_END
224
225
226
227/***************************************************************************
228
229  Machine Config
230
231***************************************************************************/
232
233WRITE_LINE_MEMBER(elecdet_state::auto_power_off)
234{
235   // TMS0980 auto power-off opcode
236   if (state)
237   {
238      m_power_on = false;
239      m_maincpu->set_input_line(INPUT_LINE_RESET, ASSERT_LINE);
240   }
241}
242
243
244void elecdet_state::machine_reset()
245{
246   m_power_on = true;
247}
248
249void elecdet_state::machine_start()
250{
251   // zerofill
252   memset(m_leds_state, 0, sizeof(m_leds_state));
253   memset(m_leds_cache, 0, sizeof(m_leds_cache));
254   memset(m_leds_decay, 0, sizeof(m_leds_decay));
255
256   m_o = 0;
257   m_power_on = false;
258
259   // register for savestates
260   save_item(NAME(m_leds_state));
261   save_item(NAME(m_leds_cache));
262   save_item(NAME(m_leds_decay));
263
264   save_item(NAME(m_o));
265   save_item(NAME(m_power_on));
266}
267
268
269static MACHINE_CONFIG_START( elecdet, elecdet_state )
270
271   /* basic machine hardware */
272   MCFG_CPU_ADD("maincpu", TMS0980, MASTER_CLOCK)
273   MCFG_TMS1XXX_READ_K_CB(READ8(elecdet_state, read_k))
274   MCFG_TMS1XXX_WRITE_O_CB(WRITE16(elecdet_state, write_o))
275   MCFG_TMS1XXX_WRITE_R_CB(WRITE16(elecdet_state, write_r))
276   MCFG_TMS1XXX_POWER_OFF_CB(WRITELINE(elecdet_state, auto_power_off))
277
278   MCFG_TIMER_DRIVER_ADD_PERIODIC("leds_decay", elecdet_state, leds_decay_tick, attotime::from_msec(10))
279
280   MCFG_DEFAULT_LAYOUT(layout_elecdet)
281
282   /* no video! */
283
284   /* sound hardware */
285   MCFG_SPEAKER_STANDARD_MONO("mono")
286   MCFG_SOUND_ADD("speaker", SPEAKER_SOUND, 0)
287   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
288MACHINE_CONFIG_END
289
290
291
292/***************************************************************************
293
294  Game driver(s)
295
296***************************************************************************/
297
298ROM_START( elecdet )
299   ROM_REGION( 0x1000, "maincpu", 0 )
300   ROM_LOAD( "tms0980nll_mp6100a", 0x0000, 0x1000, CRC(8160a081) SHA1(14cbfc0529ad83a58e0dc15fe8ba594947e49f08) )
301
302   ROM_REGION( 1246, "maincpu:ipla", 0 )
303   ROM_LOAD( "tms0980_default_ipla.pla", 0, 1246, CRC(42db9a38) SHA1(2d127d98028ec8ec6ea10c179c25e447b14ba4d0) )
304   ROM_REGION( 1982, "maincpu:mpla", 0 )
305   ROM_LOAD( "tms0980_default_mpla.pla", 0, 1982, CRC(3709014f) SHA1(d28ee59ded7f3b9dc3f0594a32a98391b6e9c961) )
306   ROM_REGION( 352, "maincpu:opla", 0 )
307   ROM_LOAD( "tms0980_elecdet_opla.pla", 0, 352, CRC(652d19c3) SHA1(75550c2b293453b6b9efed88c8cc77195a53161f) )
308   ROM_REGION( 157, "maincpu:spla", 0 )
309   ROM_LOAD( "tms0980_elecdet_spla.pla", 0, 157, CRC(399aa481) SHA1(72c56c58fde3fbb657d69647a9543b5f8fc74279) )
310ROM_END
311
312
313CONS( 1979, elecdet, 0, 0, elecdet, elecdet, driver_device, 0, "Ideal", "Electronic Detective", GAME_SUPPORTS_SAVE )
trunk/src/mess/drivers/fmtowns.c
r242959r242960
1515            1024 sprites (16x16), rendered direct to VRAM
1616            16 colour text mode, rendered direct to VRAM
1717
18    Later models add an unknown single channel 16-bit PCM/ADPCM (FreshTV, SJ, MX), and CL-GD543x Windows accelerator chipsets (SJ)
1918
20
2119    Fujitsu FM-Towns Marty
2220
2321    Japanese console, based on the FM-Towns computer, using an AMD 80386SX CPU,
trunk/src/mess/drivers/gamate.c
r242959r242960
1111#include "bus/generic/carts.h"
1212#include "rendlay.h"
1313
14//#define USE_GFX
15
1614class gamate_state : public driver_device
1715{
1816public:
r242959r242960
2018      : driver_device(mconfig, type, tag)
2119      , m_maincpu(*this, "maincpu")
2220      , m_cart(*this, "cartslot")
23#ifdef USE_GFX     
24      , m_gfxdecode(*this, "gfxdecode")
25#endif
21//      , m_gfxdecode(*this, "gfxdecode")
2622      , m_io_joy(*this, "JOY")
2723      , m_palette(*this, "palette")
2824      , m_bios(*this, "bios")
r242959r242960
3026
3127   DECLARE_PALETTE_INIT(gamate);
3228   DECLARE_READ8_MEMBER(protection_r);
33   DECLARE_READ8_MEMBER(newer_protection_set);
34   DECLARE_WRITE8_MEMBER(protection_reset);
3529   DECLARE_READ8_MEMBER(gamate_cart_protection_r);
3630   DECLARE_WRITE8_MEMBER(gamate_cart_protection_w);
3731   DECLARE_WRITE8_MEMBER(cart_bankswitchmulti_w);
r242959r242960
5347
5448   struct
5549   {
56     UINT8 reg[8];
57     struct {
58       bool write;
59       bool page2; // else page1
50   UINT8 reg[8];
51   struct {
52      bool write;
53      bool page2; // else page1
6054   UINT8 ypos, xpos/*tennis*/;
61       UINT8 data[2][0x100][0x20];
62     } bitmap;
63     UINT8 x, y;
55      UINT8 data[2][0x100][0x20];
56      } bitmap;
57   UINT8 x, y;
6458      bool y_increment;
6559   } video;
6660
6761   struct {
68     bool set;
6962      int bit_shifter;
7063      UINT8 cartridge_byte;
7164      UINT16 address; // in reality something more like short local cartridge address offset
7265      bool unprotected;
7366      bool failed;
74     
7567   } card_protection;
7668
7769   required_device<cpu_device> m_maincpu;
7870   required_device<generic_slot_device> m_cart;
79#ifdef USE_GFX
80   required_device<gfxdecode_device> m_gfxdecode;
81#endif
71//  required_device<gfxdecode_device> m_gfxdecode;
8272   required_ioport m_io_joy;
8373   required_device<palette_device> m_palette;
8474   required_shared_ptr<UINT8> m_bios;
8575   emu_timer *timer1;
8676   emu_timer *timer2;
87   UINT8 bank_multi; 
8877};
8978
9079WRITE8_MEMBER( gamate_state::gamate_cart_protection_w )
9180{
92        logerror("%.6f protection write %x %x address:%x data:%x shift:%d\n",machine().time().as_double(), offset, data, card_protection.address, card_protection.cartridge_byte, card_protection.bit_shifter);
93 
9481   switch (offset) {
9582   case 0:
9683      card_protection.failed= card_protection.failed || ((card_protection.cartridge_byte&0x80)!=0) != ((data&4)!=0);
r242959r242960
10491}
10592READ8_MEMBER( gamate_state::gamate_cart_protection_r )
10693{
107
108  UINT8 ret=1;
109  if (card_protection.bit_shifter==7 && card_protection.unprotected) {
110    ret=m_cart->get_rom_base()[bank_multi*0x4000];
111  } else {
112   card_protection.bit_shifter++;
113   if (card_protection.bit_shifter==8) {
114      card_protection.bit_shifter=0;
115      card_protection.cartridge_byte='G';
116      card_protection.unprotected=true;
94   UINT8 ret=1;
95   switch (offset) {
96   case 0:
97      ret=(card_protection.cartridge_byte&0x80)?2:0;
98      card_protection.cartridge_byte<<=1;
99      card_protection.bit_shifter++;
100      if (card_protection.bit_shifter>=8) {
101         card_protection.bit_shifter=0;
102         card_protection.cartridge_byte=m_cart->get_rom_base()[card_protection.address++];
103         card_protection.unprotected=true;
104         if (!card_protection.failed) {
105         } // now protection chip on cartridge activates cartridge chip select on cpu accesses
106      }
107      break;
117108   }
118   ret=(card_protection.cartridge_byte&0x80)?2:0;
119   if (card_protection.bit_shifter==7 && !card_protection.failed) { // now protection chip on cartridge activates cartridge chip select on cpu accesses
120//        m_maincpu->space(AS_PROGRAM).install_read_handler(0x6000, 0x6000, READ8_DELEGATE(gamate_state, gamate_cart_protection_r)); // next time I will try to get this working
121   }
122   card_protection.cartridge_byte<<=1;
123  }
124  logerror("%.6f protection read %x %x address:%x data:%x shift:%d\n",machine().time().as_double(), offset, ret, card_protection.address, card_protection.cartridge_byte, card_protection.bit_shifter);
125  return ret;
109   return ret;
126110}
127111
128READ8_MEMBER( gamate_state::protection_r ) { return card_protection.set? 3: 1; } // bits 0 and 1 checked
112READ8_MEMBER( gamate_state::protection_r ) { return 1; }
129113
130WRITE8_MEMBER( gamate_state::protection_reset )
131{
132  // writes 0x20
133  card_protection.address=0x6005-0x6001;
134  card_protection.bit_shifter=0;
135  card_protection.cartridge_byte=m_cart->get_rom_base()[card_protection.address++];//m_cart_rom[card_protection.address++];
136  card_protection.failed=false;
137  card_protection.unprotected=false;
138}
139
140READ8_MEMBER( gamate_state::newer_protection_set )
141{
142  card_protection.set=true;
143  return 0;
144}
145
146
147114WRITE8_MEMBER( gamate_state::gamate_video_w )
148115{
149  video.reg[offset]=data;
150  switch (offset) {
151  case 1: video.bitmap.write=data&0xc0; // more addressing mode
116   video.reg[offset]=data;
117   switch (offset) {
118   case 1: video.bitmap.write=data&0xc0; // more addressing mode
152119      video.y_increment=data&0x40;
153120      break;
154121   case 2: video.bitmap.xpos=data;break; // at least 7 bits
155122   case 3: video.bitmap.ypos=data;break; // at least 7 bits
156  case 4: video.bitmap.page2=data&0x80;video.x=data&0x7f;break;
157  case 5: video.y=data;break;
158  case 7:
159    if (video.bitmap.write) {
160      if (video.x<ARRAY_LENGTH(video.bitmap.data[0][0]) /*&& video.y<ARRAY_LENGTH(video.bitmap.data[0])*/)
161        video.bitmap.data[video.bitmap.page2][video.y][video.x]=data;
162      else
163        logerror("%.6f %04x video bitmap x %x invalid\n",machine().time().as_double(), m_maincpu->pc(), video.x);
164    } else {
165        video.bitmap.data[0][video.y][video.x&(ARRAY_LENGTH(video.bitmap.data[0][0])-1)]=data;
166    }
167    if (video.y_increment) video.y++;
123   case 4: video.bitmap.page2=data&0x80;video.x=data&0x7f;break;
124   case 5: video.y=data;break;
125   case 7:
126   if (video.bitmap.write) {
127      if (video.x<ARRAY_LENGTH(video.bitmap.data[0][0]) /*&& video.y<ARRAY_LENGTH(video.bitmap.data[0])*/)
128      video.bitmap.data[video.bitmap.page2][video.y][video.x]=data;
129      else
130      logerror("%.6f %04x video bitmap x %x invalid\n",machine().time().as_double(), m_maincpu->pc(), video.x);
131   } else {
132      video.bitmap.data[0][video.y][video.x&(ARRAY_LENGTH(video.bitmap.data[0][0])-1)]=data;
133   }
134   if (video.y_increment) video.y++;
168135      else video.x++;
169  }
136   }
170137}
171138
172139WRITE8_MEMBER( gamate_state::cart_bankswitchmulti_w )
173140{
174  bank_multi=data;
175  membank("bankmulti")->set_base(m_cart->get_rom_base()+0x4000*data+1);
141   membank("bankmulti")->set_base(m_cart->get_rom_base()+0x4000*data);
176142}
177143
178144WRITE8_MEMBER( gamate_state::cart_bankswitch_w )
r242959r242960
183149READ8_MEMBER( gamate_state::gamate_video_r )
184150{
185151   if (offset!=6) return 0;
186  UINT8 data=0;
187  if (video.bitmap.write) {
188      if (video.x<ARRAY_LENGTH(video.bitmap.data[0][0]) /*&& video.y<ARRAY_LENGTH(video.bitmap.data[0])*/)
189        data=video.bitmap.data[video.bitmap.page2][video.y][video.x];
190      else
191        logerror("%.6f video bitmap x %x invalid\n",machine().time().as_double(),video.x);
192  } else {
193    data=video.bitmap.data[0][video.y][video.x&(ARRAY_LENGTH(video.bitmap.data[0][0])-1)];
194  }
195  if (m_maincpu->pc()<0xf000)
196    logerror("%.6f video read %04x %02x\n",machine().time().as_double(),offset, data);
197  return data;
152   UINT8 data=0;
153   if (video.bitmap.write) {
154      if (video.x<ARRAY_LENGTH(video.bitmap.data[0][0]) /*&& video.y<ARRAY_LENGTH(video.bitmap.data[0])*/)
155      data=video.bitmap.data[video.bitmap.page2][video.y][video.x];
156      else
157      logerror("%.6f video bitmap x %x invalid\n",machine().time().as_double(),video.x);
158   } else {
159   data=video.bitmap.data[0][video.y][video.x&(ARRAY_LENGTH(video.bitmap.data[0][0])-1)];
160   }
161   if (m_maincpu->pc()<0xf000)
162   logerror("%.6f video read %04x %02x\n",machine().time().as_double(),offset, data);
163   return data;
198164}
199165
200166WRITE8_MEMBER( gamate_state::gamate_audio_w )
201167{
202  logerror("%.6f %04x audio write %04x %02x\n",machine().time().as_double(),m_maincpu->pc(),offset,data);
168   logerror("%.6f %04x audio write %04x %02x\n",machine().time().as_double(),m_maincpu->pc(),offset,data);
203169}
204170
205171READ8_MEMBER( gamate_state::gamate_audio_r )
206172{
207  logerror("%.6f %04x audio read %04x \n",machine().time().as_double(),m_maincpu->pc(),offset);
173   logerror("%.6f %04x audio read %04x \n",machine().time().as_double(),m_maincpu->pc(),offset);
208174   return 0;
209175}
210176
211177
212178READ8_MEMBER( gamate_state::gamate_pad_r )
213179{
214  UINT8 data=m_io_joy->read();
215  return data;
180   UINT8 data=m_io_joy->read();
181   return data;
216182}
217183
218184static ADDRESS_MAP_START( gamate_mem, AS_PROGRAM, 8, gamate_state )
219    AM_RANGE(0x0000, 0x03ff) AM_RAM
220  AM_RANGE(0x4000, 0x400d) AM_READWRITE(gamate_audio_r, gamate_audio_w)
221  AM_RANGE(0x4400, 0x4400) AM_READ(gamate_pad_r)
222  AM_RANGE(0x5000, 0x5007) AM_READWRITE(gamate_video_r, gamate_video_w)
223  AM_RANGE(0x5800, 0x5800) AM_READ(newer_protection_set)
224  AM_RANGE(0x5900, 0x5900) AM_WRITE(protection_reset)
225  AM_RANGE(0x5a00, 0x5a00) AM_READ(protection_r)
185   AM_RANGE(0x0000, 0x03ff) AM_RAM
186   AM_RANGE(0x4000, 0x400d) AM_READWRITE(gamate_audio_r, gamate_audio_w)
187   AM_RANGE(0x4400, 0x4400) AM_READ(gamate_pad_r)
188   AM_RANGE(0x5000, 0x5007) AM_READWRITE(gamate_video_r, gamate_video_w)
189   AM_RANGE(0x5a00, 0x5a00) AM_READ(protection_r)
226190
227  AM_RANGE(0x6001, 0x9fff) AM_READ_BANK("bankmulti")
228  AM_RANGE(0xa000, 0xdfff) AM_READ_BANK("bank")
191   AM_RANGE(0x6000, 0x9fff) AM_READ_BANK("bankmulti")
192   AM_RANGE(0xa000, 0xdfff) AM_READ_BANK("bank")
229193
230   AM_RANGE(0x6000, 0x6000) AM_READWRITE(gamate_cart_protection_r, gamate_cart_protection_w)
194   AM_RANGE(0x6000, 0x6002) AM_READWRITE(gamate_cart_protection_r, gamate_cart_protection_w)
195//  AM_RANGE(0x6000, 0xdfff) AM_READWRITE(gamate_cart_r, gamate_cart_w)
231196   AM_RANGE(0x8000, 0x8000) AM_WRITE(cart_bankswitchmulti_w)
232197   AM_RANGE(0xc000, 0xc000) AM_WRITE(cart_bankswitch_w)
233198
234  AM_RANGE(0xf000, 0xffff) AM_ROM AM_SHARE("bios")
199   AM_RANGE(0xf000, 0xffff) AM_ROM AM_SHARE("bios")
235200ADDRESS_MAP_END
236201
237202
r242959r242960
247212   PORT_BIT( 0x80, IP_ACTIVE_LOW, IPT_SELECT) PORT_NAME("Select")
248213INPUT_PORTS_END
249214
250#ifdef USE_GFX
215#ifdef UNUSED_CODE
251216static const struct gfx_layout gamate_charlayout =
252217{
253        4,      /* width of object */
254        1,      /* height of object */
255        256,/* 256 characters */
256        2,      /* bits per pixel */
257        { 0,4 }, /* no bitplanes */
258        /* x offsets */
259        { 0,1,2,3 },
260        /* y offsets */
261        { 0 },
262        8*1 /* size of 1 object in bits */
218      4,      /* width of object */
219      1,      /* height of object */
220      256,/* 256 characters */
221      2,      /* bits per pixel */
222      { 0,1 }, /* no bitplanes */
223      /* x offsets */
224      { 0,2,4,6 },
225      /* y offsets */
226      { 0 },
227      8*1 /* size of 1 object in bits */
263228};
264229
265static GFXDECODE_START( gamate )
266        GFXDECODE_ENTRY( "gfx1", 0x0000, gamate_charlayout, 0, 0x100 )
230static const unsigned short gamate_palette[4] =
231{
232   0,1,2,3
233};
234
235static GFXDECODE_START( gamate_charlayout )
236      GFXDECODE_ENTRY( "gfx1", 0x0000, gamate_charlayout, 0, 0x100 )
267237GFXDECODE_END
268238#endif
269239
270240/* palette in red, green, blue tribles */
271241static const unsigned char gamate_colors[4][3] =
272242{
273  { 255,255,255 },
274  { 0xa0, 0xa0, 0xa0 },
275  { 0x60, 0x60, 0x60 },
276  { 0, 0, 0 }
243   { 255,255,255 },
244   { 0xa0, 0xa0, 0xa0 },
245   { 0x60, 0x60, 0x60 },
246   { 0, 0, 0 }
277247};
278248
279249PALETTE_INIT_MEMBER(gamate_state, gamate)
r242959r242960
284254   {
285255      palette.set_pen_color(i, gamate_colors[i][0], gamate_colors[i][1], gamate_colors[i][2]);
286256   }
257#if 0
258   for (int i = 0; i < 8; i++)
259      palette.set_indirect_color(i, arcadia_colors[i]);
260
261   for (int i = 0; i < 128+8; i++)
262      palette.set_pen_indirect(i, arcadia_palette[i]);
263#endif
287264}
288265
289#ifndef USE_GFX
266
290267static void BlitPlane(UINT16* line, UINT8 plane1, UINT8 plane2)
291268{
292269   line[3]=(plane1&1)|((plane2<<1)&2);
r242959r242960
294271   line[1]=((plane1>>2)&1)|((plane2>>1)&2);
295272   line[0]=((plane1>>3)&1)|((plane2>>2)&2);
296273}
297#endif
298274
299275UINT32 gamate_state::screen_update_gamate(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
300276{
301  int x, y, j;
302  for (y=0;y<152;y++) {
303    for (x=-(video.bitmap.xpos&7), j=0;x<160;x+=8, j++) {
304      UINT8 d1=video.bitmap.data[0][(y+video.bitmap.ypos)&0xff][(j+video.bitmap.xpos/8)&0x1f];
305      UINT8 d2=video.bitmap.data[1][(y+video.bitmap.ypos)&0xff][(j+video.bitmap.xpos/8)&0x1f];
306#ifdef USE_GFX
307      m_gfxdecode->gfx(0)->opaque(bitmap,cliprect, (d1&0xf)|((d2&0xf)<<4), 0,0,0,x+4,y);
308   m_gfxdecode->gfx(0)->opaque(bitmap,cliprect, (d1>>4)|(d2&0xf0),0,0,0,x,y);
309#else
310      BlitPlane(&bitmap.pix16(y, x+4), d1, d2);
311      BlitPlane(&bitmap.pix16(y, x), d1>>4, d2>>4);
312#endif     
313    }
314  }
315  return 0;
277   int x, y, j;
278   for (y=0;y<152;y++) {
279   for (x=-(video.bitmap.xpos&7), j=0;x<160;x+=8, j++) {
280      UINT8 d1=video.bitmap.data[0][(y+video.bitmap.ypos)&0xff][(j+video.bitmap.xpos/8)&0x1f];
281      UINT8 d2=video.bitmap.data[1][(y+video.bitmap.ypos)&0xff][(j+video.bitmap.xpos/8)&0x1f];
282      BlitPlane(&bitmap.pix16(y, x+4), d1, d2);
283      BlitPlane(&bitmap.pix16(y, x), d1>>4, d2>>4);
284   }
285   }
286   return 0;
316287}
317288
318289DRIVER_INIT_MEMBER(gamate_state,gamate)
319290{
320291   memset(&video, 0, sizeof(video));/* memset(m_ram, 0, sizeof(m_ram));*/
321#ifdef USE_GFX
322   UINT8 *gfx=memregion("gfx1")->base();
323   for (int i=0; i<256; i++) gfx[i]=i;
324#endif   
292   UINT8 *gfx=memregion("gfx1")->base();   for (int i=0; i<256; i++) gfx[i]=i;
325293   timer1 = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(gamate_state::gamate_timer),this));
326294   timer2 = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(gamate_state::gamate_timer2),this));
327295}
r242959r242960
330298void gamate_state::machine_start()
331299{
332300   if (m_cart->exists()) {
333//      m_maincpu->space(AS_PROGRAM).install_read_handler(0x6000, 0x6000, READ8_DELEGATE(gamate_state, gamate_cart_protection_r));
334      membank("bankmulti")->set_base(m_cart->get_rom_base()+1);
301//      m_maincpu->space(AS_PROGRAM).install_read_handler(0x6000, 0x6000, READ8_DELEGATE(gamate_state, gamate_cart_protection_r));
302      membank("bankmulti")->set_base(m_cart->get_rom_base());
335303      membank("bank")->set_base(m_cart->get_rom_base()+0x4000); // bankswitched games in reality no offset
336304   }
337//   m_bios[0xdf1]=0xea; m_bios[0xdf2]=0xea; // default bios: $47 protection readback
338   card_protection.set=false;
339   bank_multi=0;
305   m_bios[0xdf1]=0xea; m_bios[0xdf2]=0xea; // $47 protection readback
306   card_protection.address=0x6005-0x6001;
307   card_protection.bit_shifter=0;
308   card_protection.cartridge_byte=m_cart->get_rom_base()[card_protection.address++];//m_cart_rom[card_protection.address++];
309   card_protection.failed=false;
340310   card_protection.unprotected=false;
341311   timer2->enable(TRUE);
342312   timer2->reset(m_maincpu->cycles_to_attotime(1000));
r242959r242960
385355   MCFG_SCREEN_UPDATE_DRIVER(gamate_state, screen_update_gamate)
386356   MCFG_SCREEN_PALETTE("palette")
387357
388#ifdef USE_GFX
389   MCFG_GFXDECODE_ADD("gfxdecode", "palette", gamate )
390#endif   
358//  MCFG_GFXDECODE_ADD("gfxdecode", "palette", gamate )
391359   MCFG_PALETTE_ADD("palette", ARRAY_LENGTH(gamate_colors))
360//  MCFG_PALETTE_INDIRECT_ENTRIES(4)
392361   MCFG_PALETTE_INIT_OWNER(gamate_state, gamate)
393362   MCFG_DEFAULT_LAYOUT(layout_lcd)
394363
r242959r242960
401370
402371ROM_START(gamate)
403372   ROM_REGION(0x10000,"maincpu", 0)
404   ROM_SYSTEM_BIOS(0, "default", "DEFAULT")
405   ROMX_LOAD("gamate_bios_umc.bin", 0xf000, 0x1000, CRC(07090415) SHA1(ea449dc607601f9a68d855ad6ab53800d2e99297), ROM_BIOS(1) )
406   ROM_SYSTEM_BIOS(1, "newer", "NEWER")
407   ROMX_LOAD("gamate_bios_9130__unknown__bit_icasc00001_9130-bs_r32261.bin", 0xf000, 0x1000, CRC(03a5f3a7) SHA1(4e9dfbfe916ca485530ef4221593ab68738e2217), ROM_BIOS(2) )
408#ifdef USE_GFX   
373   ROM_LOAD("gamate_bios_umc.bin", 0xf000, 0x1000, CRC(07090415) SHA1(ea449dc607601f9a68d855ad6ab53800d2e99297) )
409374   ROM_REGION(0x100,"gfx1", ROMREGION_ERASEFF)
410#endif   
411375ROM_END
412376
413377
414378/*    YEAR  NAME      PARENT  COMPAT    MACHINE   INPUT    CLASS          INIT      COMPANY    FULLNAME */
415379CONS( 19??, gamate,  0,      0,        gamate,  gamate, gamate_state, gamate, "Bit Corp", "Gamate", GAME_NO_SOUND)
416
417
trunk/src/mess/drivers/ngen.c
r242959r242960
8383      m_dmac(*this,"dmac"),
8484      m_pic(*this,"pic"),
8585      m_pit(*this,"pit"),
86      m_disk_rom(*this,"disk"),
8786      m_vram(*this,"vram"),
8887      m_fontram(*this,"fontram"),
8988      m_fdc(*this,"fdc"),
90      m_fd0(*this,"fdc:0"),
91      m_fdc_timer(*this,"fdc_timer"),
92      m_hdc_timer(*this,"hdc_timer")
89      m_fd0(*this,"fdc:0")
9390   {}
9491
9592   DECLARE_WRITE_LINE_MEMBER(pit_out0_w);
r242959r242960
10097   DECLARE_WRITE16_MEMBER(cpu_peripheral_cb);
10198   DECLARE_WRITE16_MEMBER(peripheral_w);
10299   DECLARE_READ16_MEMBER(peripheral_r);
103   DECLARE_WRITE16_MEMBER(xbus_w);
104   DECLARE_READ16_MEMBER(xbus_r);
100   DECLARE_WRITE16_MEMBER(port00_w);
101   DECLARE_READ16_MEMBER(port00_r);
105102   DECLARE_WRITE_LINE_MEMBER(dma_hrq_changed);
106103   DECLARE_WRITE_LINE_MEMBER(dma_eop_changed);
107104   DECLARE_WRITE_LINE_MEMBER(dack0_w);
r242959r242960
115112   DECLARE_READ8_MEMBER( dma_0_dack_r ) { UINT16 ret = 0xffff; m_dma_high_byte = ret & 0xff00; return ret; }
116113   DECLARE_READ8_MEMBER( dma_1_dack_r ) { UINT16 ret = 0xffff; m_dma_high_byte = ret & 0xff00; return ret; }
117114   DECLARE_READ8_MEMBER( dma_2_dack_r ) { UINT16 ret = 0xffff; m_dma_high_byte = ret & 0xff00; return ret; }
118   DECLARE_READ8_MEMBER( dma_3_dack_r );
119   DECLARE_WRITE8_MEMBER( dma_0_dack_w ){ popmessage("IOW0: data %02x",data); }
115   DECLARE_READ8_MEMBER( dma_3_dack_r ) { UINT16 ret = 0xffff; m_dma_high_byte = ret & 0xff00; return ret; }
116   DECLARE_WRITE8_MEMBER( dma_0_dack_w ){ popmessage("IOW: data %02x",data); }
120117   DECLARE_WRITE8_MEMBER( dma_1_dack_w ){  }
121118   DECLARE_WRITE8_MEMBER( dma_2_dack_w ){  }
122   DECLARE_WRITE8_MEMBER( dma_3_dack_w ){ popmessage("IOW3: data %02x",data); }
123
124   DECLARE_WRITE16_MEMBER(hfd_w);
125   DECLARE_READ16_MEMBER(fhd_r);
119   DECLARE_WRITE8_MEMBER( dma_3_dack_w ){  }
126120   DECLARE_WRITE_LINE_MEMBER(fdc_irq_w);
127121   DECLARE_WRITE_LINE_MEMBER(fdc_drq_w);
128122   DECLARE_WRITE8_MEMBER(fdc_control_w);
129123   DECLARE_READ8_MEMBER(irq_cb);
130   DECLARE_WRITE8_MEMBER(hdc_control_w);
131   DECLARE_WRITE8_MEMBER(disk_addr_ext);
132124
133125protected:
134126   virtual void machine_reset();
r242959r242960
141133   required_device<am9517a_device> m_dmac;
142134   required_device<pic8259_device> m_pic;
143135   required_device<pit8254_device> m_pit;
144   optional_memory_region m_disk_rom;
145136   optional_shared_ptr<UINT16> m_vram;
146137   optional_shared_ptr<UINT16> m_fontram;
147138   optional_device<wd2797_t> m_fdc;
148139   optional_device<floppy_connector> m_fd0;
149   optional_device<pit8253_device> m_fdc_timer;
150   optional_device<pit8253_device> m_hdc_timer;
151140
152141   void set_dma_channel(int channel, int state);
153142
154   UINT8 m_xbus_current;  // currently selected X-Bus module
155143   UINT16 m_peripheral;
156144   UINT16 m_upper;
157145   UINT16 m_middle;
r242959r242960
161149   INT8 m_dma_channel;
162150   UINT16 m_dma_high_byte;
163151   UINT16 m_control;
164   UINT16 m_disk_rom_ptr;
165   UINT8 m_hdc_control;
166   UINT8 m_disk_page;
167152};
168153
169154class ngen386_state : public driver_device
r242959r242960
264249   case 0x0f:
265250      if(mem_mask & 0x00ff)
266251         m_dmac->write(space,offset,data & 0xff);
267      logerror("(PC=%06x) DMA write offset %04x data %04x mask %04x\n",m_maincpu->device_t::safe_pc(),offset,data,mem_mask);
252      //logerror("(PC=%06x) DMA write offset %04x data %04x mask %04x\n",m_maincpu->device_t::safe_pc(),offset,data,mem_mask);
268253      break;
269254   case 0x80: // DMA page offset?
270255   case 0x81:
r242959r242960
273258      if(mem_mask & 0x00ff)
274259         m_dma_offset[offset-0x80] = data & 0xff;
275260      break;
276   case 0xc0:  // X-Bus modules reset
277      m_xbus_current = 0;
278      break;
279261   case 0x10c:
280262      if(mem_mask & 0x00ff)
281263         m_pic->write(space,0,data & 0xff);
r242959r242960
397379
398380// X-bus module select
399381// The bootstrap ROM creates a table at 0:FC9h, with a count, followed by the module IDs of each
400// expansion module.  The base I/O address for the currently selected module is set by writing to
401// this register (bits 0-7 are ignored)
402// TODO: make expansion modules slot devices
403WRITE16_MEMBER(ngen_state::xbus_w)
382// expansion module.  The base I/O address for each module is 0x100*module number.
383// Module 0 is the main processor module, module 1 is the next module attached, and so on.
384WRITE16_MEMBER(ngen_state::port00_w)
404385{
405   UINT16 addr = (data & 0x00ff) << 8;
406   address_space& io = m_maincpu->device_t::memory().space(AS_IO);
407   switch(m_xbus_current)
408   {
409      case 0x00:  // Floppy/Hard disk module
410         io.install_readwrite_handler(addr,addr+0xff,0,0,read16_delegate(FUNC(ngen_state::fhd_r),this),write16_delegate(FUNC(ngen_state::hfd_w),this));
411         break;
412      default:
413         m_maincpu->set_input_line(INPUT_LINE_NMI,PULSE_LINE);  // reached end of the modules
414         break;
415   }
416   if(addr != 0)
417      logerror("SYS: X-Bus module %i address set %04x\n",m_xbus_current+1,addr);
418   m_xbus_current++;
386   m_port00 = data;
387   logerror("SYS: X-Bus module select %04x\n",data);
419388}
420389
421// returns X-bus module ID and info in the low byte (can indicate if the device is bootable, has a boot ROM (needs to be written to RAM via DMA), or if it supports a non-80186 CPU)
422// bit 6, I think, indicates a bootable device
423// Known module IDs:
424//  0x1070 - Floppy/Hard disk module
425//  0x3141 - QIC Tape module
426READ16_MEMBER(ngen_state::xbus_r)
390// returns X-bus module ID (what is the low byte for?)
391// For now, we'll hard code a floppy disk module (or try to)
392READ16_MEMBER(ngen_state::port00_r)
427393{
428   UINT16 ret = 0xffff;
429   
430   switch(m_xbus_current)
431   {
432      case 0x00:
433         ret = 0x1070;  // Floppy/Hard disk module
434         break;
435      default:
436         m_maincpu->set_input_line(INPUT_LINE_NMI,PULSE_LINE);  // reached the end of the modules
437         ret = 0x0080;
438         break;
439   }
440   return ret;
394   if(m_port00 > 0)
395      m_maincpu->set_input_line(INPUT_LINE_NMI,PULSE_LINE);
396   if(m_port00 == 0)
397      return 0x0040;  // module ID of 0x40 = dual floppy disk module (need hardware manual to find other module IDs)
398   else
399      return 0x0080;  // invalid device?
441400}
442401
443
444// Floppy/Hard disk module
445WRITE16_MEMBER(ngen_state::hfd_w)
446{
447   switch(offset)
448   {
449      case 0x00:
450      case 0x01:
451      case 0x02:
452      case 0x03:
453         if(mem_mask & 0x00ff)
454            m_fdc->write(space,offset,data & 0xff);
455         break;
456      case 0x04:
457         if(mem_mask & 0x00ff)
458            fdc_control_w(space,offset,data & 0xff);
459         break;
460      case 0x05:
461         if(mem_mask & 0x00ff)
462            hdc_control_w(space,offset,data & 0xff);
463         break;
464      case 0x07:
465         if(mem_mask & 0x00ff)
466            disk_addr_ext(space,offset,data & 0xff);
467         break;
468      case 0x08:
469      case 0x09:
470      case 0x0a:
471      case 0x0b:
472         if(mem_mask & 0x00ff)
473            m_fdc_timer->write(space,offset,data & 0xff);
474         break;
475      case 0x10:
476      case 0x11:
477      case 0x12:
478      case 0x13:
479      case 0x14:
480      case 0x15:
481      case 0x16:
482      case 0x17:
483         logerror("WD1010 register %i write %02x mask %04x\n",offset-0x10,data & 0xff,mem_mask);
484         break;
485      case 0x18:
486      case 0x19:
487      case 0x1a:
488      case 0x1b:
489         if(mem_mask & 0x00ff)
490            m_hdc_timer->write(space,offset,data & 0xff);
491         break;
492   }
493}
494
495READ16_MEMBER(ngen_state::fhd_r)
496{
497   UINT16 ret = 0xffff;
498
499   switch(offset)
500   {
501      case 0x00:
502      case 0x01:
503      case 0x02:
504      case 0x03:
505         if(mem_mask & 0x00ff)
506            ret = m_fdc->read(space,offset);
507         break;
508      case 0x08:
509      case 0x09:
510      case 0x0a:
511      case 0x0b:
512         if(mem_mask & 0x00ff)
513            ret = m_fdc_timer->read(space,offset);
514         break;
515      case 0x10:
516      case 0x11:
517      case 0x12:
518      case 0x13:
519      case 0x14:
520      case 0x15:
521      case 0x16:
522      case 0x17:
523         logerror("WD1010 register %i read, mask %04x\n",offset-0x10,mem_mask);
524         break;
525      case 0x18:
526      case 0x19:
527      case 0x1a:
528      case 0x1b:
529         if(mem_mask & 0x00ff)
530            ret = m_hdc_timer->read(space,offset);
531         break;
532   }
533
534   return ret;
535}
536
537402WRITE_LINE_MEMBER(ngen_state::fdc_irq_w)
538403{
539404   m_pic->ir7_w(state);
r242959r242960
544409   m_dmac->dreq3_w(state);
545410}
546411
547// Floppy disk control register
548// Bit 0 - enable drive and LED
549// Bit 2 - floppy motor
550// Bit 5 - side select
551// Bit 6 - 1 = 2Mhz for seek, 0 = 1MHz for read/write
552// Bit 7 - FDC reset
553412WRITE8_MEMBER(ngen_state::fdc_control_w)
554413{
555414   m_fdc->set_floppy(m_fd0->get_device());
556   m_fd0->get_device()->mon_w(~data & 0x04);
557   m_fd0->get_device()->ss_w(data & 0x20);
558   if(~data & 0x80)
559      m_fdc->soft_reset();
415   m_fd0->get_device()->mon_w((~data) & 0x80);
416   m_fdc->dden_w(~data & 0x04);
560417}
561418
562// Hard disk control register
563// bit 0 - Drive select 0 - selects module hard disk
564// bit 1 - Drive select 1 - selects expansion module hard disk (if available)
565// bit 2 - enable DMA transfer of module ROM contents to X-Bus master memory
566// bits 3-5 - select head / expansion module head
567// bit 6 - write enable, must be set to write to a hard disk
568// bit 7 - HDC reset
569WRITE8_MEMBER(ngen_state::hdc_control_w)
570{
571   m_hdc_control = data;
572   if(m_hdc_control & 0x04)
573   {
574      m_disk_rom_ptr = 0;
575      popmessage("HDD: DMA ROM transfer start\n");
576      m_dmac->dreq3_w(1);
577      //m_dmac->dreq3_w(0);
578   }
579}
580
581// page of system RAM to access
582// bit 7 = disables read/write signals to the WD1010
583WRITE8_MEMBER(ngen_state::disk_addr_ext)
584{
585   m_disk_page = data & 0x7f;
586}
587
588419WRITE_LINE_MEMBER( ngen_state::dma_hrq_changed )
589420{
590421   m_maincpu->set_input_line(INPUT_LINE_HALT, state ? ASSERT_LINE : CLEAR_LINE);
r242959r242960
599430      else
600431         m_control &= ~0x02;
601432   }
602   if(m_dma_channel == 3)
603   {
604      if(state)
605      {
606         if(m_hdc_control & 0x04) // ROM transfer?
607            m_hdc_control &= ~0x04;  // switch it off when done
608      }
609   }
610433}
611434
612435void ngen_state::set_dma_channel(int channel, int state)
r242959r242960
622445WRITE_LINE_MEMBER( ngen_state::dack2_w ) { set_dma_channel(2, state); }
623446WRITE_LINE_MEMBER( ngen_state::dack3_w ) { set_dma_channel(3, state); }
624447
625READ8_MEMBER(ngen_state::dma_3_dack_r)
626{
627   UINT16 ret = 0xffff;
628   
629   if((m_hdc_control & 0x04) && m_disk_rom)
630   {
631      ret = m_disk_rom->base()[m_disk_rom_ptr++] << 8;
632      printf("DMA3 DACK: returning %02x\n",ret);
633      if(m_disk_rom_ptr < 0x1000)
634      {
635         m_dmac->dreq3_w(1);
636         //m_dmac->dreq3_w(0);
637      }
638   }
639   m_dma_high_byte = ret & 0xff00;
640   return ret;
641}
642
643448READ8_MEMBER(ngen_state::dma_read_word)
644449{
645450   address_space& prog_space = m_maincpu->space(AS_PROGRAM); // get the right address space
r242959r242960
693498{
694499   m_port00 = 0;
695500   m_control = 0;
696   m_xbus_current = 0;
697501   m_viduart->write_dsr(0);
698502   m_viduart->write_cts(0);
699503   m_fd0->get_device()->set_rpm(300);
r242959r242960
708512ADDRESS_MAP_END
709513
710514static ADDRESS_MAP_START( ngen_io, AS_IO, 16, ngen_state )
711   AM_RANGE(0x0000, 0x0001) AM_READWRITE(xbus_r,xbus_w)
712   
713   // Floppy/Hard disk module
714//   AM_RANGE(0x0100, 0x0107) AM_DEVREADWRITE8("fdc",wd2797_t,read,write,0x00ff)  // a guess for now
715//   AM_RANGE(0x0108, 0x0109) AM_WRITE8(fdc_control_w,0x00ff)
716//   AM_RANGE(0x010a, 0x010b) AM_WRITE8(hdc_control_w,0x00ff)
717//   AM_RANGE(0x010e, 0x010f) AM_WRITE8(disk_addr_ext,0x00ff)  // X-Bus extended address register
718//   AM_RANGE(0x0110, 0x0117) AM_DEVREADWRITE8("fdc_timer",pit8253_device,read,write,0x00ff)
719   // 0x0120-0x012f - WD1010 Winchester disk controller (unemulated)
720//   AM_RANGE(0x0130, 0x0137) AM_DEVREADWRITE8("hdc_timer",pit8253_device,read,write,0x00ff)
721   
515   AM_RANGE(0x0000, 0x0001) AM_READWRITE(port00_r,port00_w)
516   AM_RANGE(0x0100, 0x0107) AM_DEVREADWRITE8("fdc",wd2797_t,read,write,0x00ff)  // a guess for now
517   AM_RANGE(0x0108, 0x0109) AM_WRITE8(fdc_control_w,0x00ff)
518   AM_RANGE(0x0110, 0x0117) AM_DEVREADWRITE8("fdc_timer",pit8253_device,read,write,0x00ff)
722519ADDRESS_MAP_END
723520
724521static ADDRESS_MAP_START( ngen386_mem, AS_PROGRAM, 32, ngen_state )
r242959r242960
823620
824621   // keyboard UART (patent says i8251 is used for keyboard communications, it is located on the video board)
825622   MCFG_DEVICE_ADD("videouart", I8251, 0)  // main clock unknown, Rx/Tx clocks are 19.53kHz
826//   MCFG_I8251_TXEMPTY_HANDLER(DEVWRITELINE("pic",pic8259_device,ir4_w))
623   MCFG_I8251_TXEMPTY_HANDLER(DEVWRITELINE("pic",pic8259_device,ir4_w))
827624   MCFG_I8251_TXD_HANDLER(DEVWRITELINE("keyboard", rs232_port_device, write_txd))
828625   MCFG_RS232_PORT_ADD("keyboard", keyboard, "ngen")
829626   MCFG_RS232_RXD_HANDLER(DEVWRITELINE("videouart", i8251_device, write_rxd))
r242959r242960
838635   MCFG_WD_FDC_FORCE_READY
839636   MCFG_DEVICE_ADD("fdc_timer", PIT8253, 0)
840637   MCFG_PIT8253_CLK0(XTAL_20MHz / 20)
841   MCFG_PIT8253_OUT0_HANDLER(DEVWRITELINE("pic",pic8259_device,ir7_w))
638   MCFG_PIT8253_OUT0_HANDLER(DEVWRITELINE("pic",pic8259_device,ir4_w))
842639   MCFG_PIT8253_CLK1(XTAL_20MHz / 20)
843   MCFG_PIT8253_OUT1_HANDLER(DEVWRITELINE("pic",pic8259_device,ir7_w))
640   MCFG_PIT8253_OUT1_HANDLER(DEVWRITELINE("pic",pic8259_device,ir4_w))
844641   MCFG_PIT8253_CLK2(XTAL_20MHz / 20)
845   MCFG_PIT8253_OUT2_HANDLER(DEVWRITELINE("pic",pic8259_device,ir7_w))
642   MCFG_PIT8253_OUT2_HANDLER(DEVWRITELINE("pic",pic8259_device,ir4_w))
846643   // TODO: WD1010 HDC (not implemented)
847644   MCFG_DEVICE_ADD("hdc_timer", PIT8253, 0)
848645   MCFG_FLOPPY_DRIVE_ADD("fdc:0", ngen_floppies, "525qd", floppy_image_device::default_floppy_formats)
trunk/src/mess/drivers/prestige.c
r242959r242960
779779   MCFG_SOFTWARE_LIST_COMPATIBLE_ADD("misterx_cart", "misterx")
780780MACHINE_CONFIG_END
781781
782static MACHINE_CONFIG_DERIVED( gjmovie, prestige_base )
783   MCFG_SOFTWARE_LIST_ADD("cart_list", "gjmovie")
784MACHINE_CONFIG_END
785
786782/* ROM definition */
787783ROM_START( gl6000sl )
788784   ROM_REGION(0x100000, "maincpu", 0)
r242959r242960
799795   ROM_LOAD( "27-6020-02.u2", 0x00000, 0x100000, CRC(6bb6db14) SHA1(5d51fc3fd799e7f01ee99c453f9005fb07747b1e) )
800796ROM_END
801797
802ROM_START( gwnf )
803   ROM_REGION( 0x100000, "maincpu", 0 )
804   ROM_LOAD( "27-6372-00.bin", 0x00000, 0x100000, CRC(1bb574bd) SHA1(04234a33405782e8641883ebd6dee46a24e014d5) )
805ROM_END
806
807798ROM_START( glcolor )
808799   ROM_REGION( 0x100000, "maincpu", 0 )
809800   ROM_LOAD( "27-5488-00.u5", 0x00000, 0x080000, CRC(e6cf7702) SHA1(ce40418a7777b331bf8c4c881d51732aeb384582) )
r242959r242960
829820   ROM_LOAD( "27-6019-01.u2", 0x000000, 0x80000, CRC(946e5b7d) SHA1(80963d6ad80d49e54c8996bfc77ac135c4935be5))
830821ROM_END
831822
832ROM_START( gjmovie )
833   ROM_REGION( 0x100000, "maincpu", 0 )
834   ROM_LOAD( "lh532hlk.bin", 0x000000, 0x40000, CRC(2e64c296) SHA1(604034f902e20851cb9af60964031a508ceef83e))
835ROM_END
836
837823ROM_START( gjrstar )
838824   ROM_REGION( 0x100000, "maincpu", 0 )
839825   ROM_LOAD( "27-5740-00.u1", 0x000000, 0x40000, CRC(ff3dc3bb) SHA1(bc16dfc1e12b0008456c700c431c8df6263b671f))
r242959r242960
864850COMP( 1997, gl6000sl,  0,       0,  gl6000sl,   prestige, driver_device,     0,  "VTech",   "Genius Leader 6000SL (Germany)",   GAME_NOT_WORKING | GAME_NO_SOUND)
865851COMP( 1998, gl7007sl,  0,       0,  gl7007sl,   prestige, driver_device,     0,  "VTech",   "Genius Leader 7007SL (Germany)",   GAME_NOT_WORKING | GAME_NO_SOUND)
866852COMP( 1998, prestige,  0,       0,  prestige,   prestige, driver_device,     0,  "VTech",   "PreComputer Prestige Elite",       GAME_NOT_WORKING | GAME_NO_SOUND)
867COMP( 1999, gwnf,      0,       0,  prestige,   prestige, driver_device,     0,  "VTech",   "Genius Winner Notebook Fun (Germany)", GAME_NOT_WORKING | GAME_NO_SOUND)
868853
869854
870855// these systems need to be moved into a separate driver
871856COMP( 1996, gj4000,    0,       0,  prestige,   prestige, driver_device,     0,  "VTech",   "Genius Junior 4000 (Germany)", GAME_IS_SKELETON)
872COMP( 1993, gjmovie,   0,       0,  gjmovie,    prestige, driver_device,     0,  "VTech",   "Genius Junior Movie (Germany)", GAME_IS_SKELETON)
873857COMP( 1996, gjrstar,   0,       0,  prestige,   prestige, driver_device,     0,  "VTech",   "Genius Junior Redstar(Germany)", GAME_IS_SKELETON)
874858COMP( 1996, gjrstar2,  gjrstar, 0,  prestige,   prestige, driver_device,     0,  "VTech",   "Genius Junior Redstar 2 (Germany)", GAME_IS_SKELETON)
875859COMP( 1998, gjrstar3,  0,       0,  prestige,   prestige, driver_device,     0,  "VTech",   "Genius Junior Redstar 3 (Germany)", GAME_IS_SKELETON)
trunk/src/mess/drivers/splitsec.c
r242959r242960
1// license:BSD-3-Clause
2// copyright-holders:hap
3/***************************************************************************
4
5  Parker Brothers Split Second
6  * TMS1400NLL MP7314-N2 (die labeled MP7314)
7
8
9***************************************************************************/
10
11#include "emu.h"
12#include "cpu/tms0980/tms0980.h"
13#include "sound/speaker.h"
14
15#include "splitsec.lh"
16
17// master clock is a single stage RC oscillator: R=24K, C=100pf,
18// according to the TMS 1000 series data manual this is around 375kHz
19#define MASTER_CLOCK (375000)
20
21
22class splitsec_state : public driver_device
23{
24public:
25   splitsec_state(const machine_config &mconfig, device_type type, const char *tag)
26      : driver_device(mconfig, type, tag),
27      m_maincpu(*this, "maincpu"),
28      m_button_matrix(*this, "IN"),
29      m_speaker(*this, "speaker")
30   { }
31
32   required_device<cpu_device> m_maincpu;
33   required_ioport_array<2> m_button_matrix;
34   required_device<speaker_sound_device> m_speaker;
35
36   UINT16 m_r;
37   UINT16 m_o;
38
39   UINT16 m_leds_state[0x10];
40   UINT16 m_leds_cache[0x10];
41   UINT8 m_leds_decay[0x100];
42
43   DECLARE_READ8_MEMBER(read_k);
44   DECLARE_WRITE16_MEMBER(write_o);
45   DECLARE_WRITE16_MEMBER(write_r);
46
47   TIMER_DEVICE_CALLBACK_MEMBER(leds_decay_tick);
48   void leds_update();
49
50   virtual void machine_start();
51};
52
53
54
55/***************************************************************************
56
57  LEDs
58
59***************************************************************************/
60
61// The device strobes the outputs very fast, it is unnoticeable to the user.
62// To prevent flickering here, we need to simulate a decay.
63
64// decay time, in steps of 10ms
65#define LEDS_DECAY_TIME 4
66
67void splitsec_state::leds_update()
68{
69   UINT16 active_state[0x10];
70
71   for (int i = 0; i < 0x10; i++)
72   {
73      // update current state
74      if (m_r >> i & 1)
75         m_leds_state[i] = m_o;
76
77      active_state[i] = 0;
78
79      for (int j = 0; j < 0x10; j++)
80      {
81         int di = j << 4 | i;
82
83         // turn on powered leds
84         if (m_leds_state[i] >> j & 1)
85            m_leds_decay[di] = LEDS_DECAY_TIME;
86
87         // determine active state
88         int ds = (m_leds_decay[di] != 0) ? 1 : 0;
89         active_state[i] |= (ds << j);
90      }
91   }
92
93   // on difference, send to output
94   for (int i = 0; i < 0x10; i++)
95      if (m_leds_cache[i] != active_state[i])
96      {
97         for (int j = 0; j < 8; j++)
98            output_set_lamp_value(i*10 + j, active_state[i] >> j & 1);
99      }
100
101   memcpy(m_leds_cache, active_state, sizeof(m_leds_cache));
102}
103
104TIMER_DEVICE_CALLBACK_MEMBER(splitsec_state::leds_decay_tick)
105{
106   // slowly turn off unpowered leds
107   for (int i = 0; i < 0x100; i++)
108      if (!(m_leds_state[i & 0xf] >> (i>>4) & 1) && m_leds_decay[i])
109         m_leds_decay[i]--;
110
111   leds_update();
112}
113
114
115
116/***************************************************************************
117
118  I/O
119
120***************************************************************************/
121
122READ8_MEMBER(splitsec_state::read_k)
123{
124   UINT8 k = 0;
125
126   // read selected button rows
127   for (int i = 0; i < 2; i++)
128      if (m_r >> (i+9) & 1)
129         k |= m_button_matrix[i]->read();
130
131   return k;
132}
133
134WRITE16_MEMBER(splitsec_state::write_r)
135{
136   // R8: speaker out
137   m_speaker->level_w(data >> 8 & 1);
138   
139   // R9,R10: input mux
140   // R0-R7: led columns
141   m_r = data;
142   leds_update();
143}
144
145WRITE16_MEMBER(splitsec_state::write_o)
146{
147   // O0-O6: led rows
148   // O7: N/C
149   m_o = data;
150   leds_update();
151}
152
153
154
155/***************************************************************************
156
157  Inputs
158
159***************************************************************************/
160
161static INPUT_PORTS_START( splitsec )
162   PORT_START("IN.0") // R9
163   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_RIGHT )
164   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_JOYSTICK_UP )
165   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_JOYSTICK_LEFT )
166   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNUSED )
167
168   PORT_START("IN.1") // R10
169   PORT_BIT( 0x01, IP_ACTIVE_HIGH, IPT_JOYSTICK_DOWN )
170   PORT_BIT( 0x02, IP_ACTIVE_HIGH, IPT_BUTTON1 ) PORT_NAME("Select")
171   PORT_BIT( 0x04, IP_ACTIVE_HIGH, IPT_BUTTON2 ) PORT_NAME("Start")
172   PORT_BIT( 0x08, IP_ACTIVE_HIGH, IPT_UNUSED )
173INPUT_PORTS_END
174
175
176
177/***************************************************************************
178
179  Machine Config
180
181***************************************************************************/
182
183void splitsec_state::machine_start()
184{
185   // zerofill
186   memset(m_leds_state, 0, sizeof(m_leds_state));
187   memset(m_leds_cache, 0, sizeof(m_leds_cache));
188   memset(m_leds_decay, 0, sizeof(m_leds_decay));
189
190   m_r = 0;
191   m_o = 0;
192
193   // register for savestates
194   save_item(NAME(m_leds_state));
195   save_item(NAME(m_leds_cache));
196   save_item(NAME(m_leds_decay));
197
198   save_item(NAME(m_r));
199   save_item(NAME(m_o));
200}
201
202
203static MACHINE_CONFIG_START( splitsec, splitsec_state )
204
205   /* basic machine hardware */
206   MCFG_CPU_ADD("maincpu", TMS1400, MASTER_CLOCK)
207   MCFG_TMS1XXX_READ_K_CB(READ8(splitsec_state, read_k))
208   MCFG_TMS1XXX_WRITE_O_CB(WRITE16(splitsec_state, write_o))
209   MCFG_TMS1XXX_WRITE_R_CB(WRITE16(splitsec_state, write_r))
210
211   MCFG_TIMER_DRIVER_ADD_PERIODIC("leds_decay", splitsec_state, leds_decay_tick, attotime::from_msec(10))
212
213   MCFG_DEFAULT_LAYOUT(layout_splitsec)
214
215   /* no video! */
216
217   /* sound hardware */
218   MCFG_SPEAKER_STANDARD_MONO("mono")
219   MCFG_SOUND_ADD("speaker", SPEAKER_SOUND, 0)
220   MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
221MACHINE_CONFIG_END
222
223
224
225/***************************************************************************
226
227  Game driver(s)
228
229***************************************************************************/
230
231ROM_START( splitsec )
232   ROM_REGION( 0x1000, "maincpu", 0 )
233   ROM_LOAD( "tms1400nll_mp7314", 0x0000, 0x1000, CRC(0cccdf59) SHA1(06a533134a433aaf856b80f0ca239d0498b98d5f) )
234
235   ROM_REGION( 867, "maincpu:mpla", 0 )
236   ROM_LOAD( "tms1100_default_mpla.pla", 0, 867, CRC(62445fc9) SHA1(d6297f2a4bc7a870b76cc498d19dbb0ce7d69fec) )
237   ROM_REGION( 557, "maincpu:opla", 0 )
238   ROM_LOAD( "tms1400_splitsec_opla.pla", 0, 557, CRC(7539283b) SHA1(f791fa98259fc10c393ff1961d4c93040f1a2932) )
239ROM_END
240
241
242CONS( 1980, splitsec, 0, 0, splitsec, splitsec, driver_device, 0, "Parker Brothers", "Split Second", GAME_SUPPORTS_SAVE | GAME_NOT_WORKING )
trunk/src/mess/drivers/stopthie.c
r242959r242960
8888         int di = j << 4 | i;
8989
9090         // turn on powered leds
91         if (m_power_on && m_leds_state[i] >> j & 1)
91         if (m_leds_state[i] >> j & 1)
9292            m_leds_decay[di] = LEDS_DECAY_TIME;
9393
9494         // determine active state
95         int ds = (m_leds_decay[di] != 0) ? 1 : 0;
95         int ds = (m_power_on && m_leds_decay[di] != 0) ? 1 : 0;
9696         active_state[i] |= (ds << j);
9797      }
9898   }
trunk/src/mess/drivers/ticalc1x.c
r242959r242960
8080// To prevent flickering here, we need to simulate a decay.
8181
8282// decay time, in steps of 10ms
83#define LEDS_DECAY_TIME 5
83#define LEDS_DECAY_TIME 4
8484
8585void ticalc1x_state::leds_update()
8686{
r242959r242960
9595         int di = j << 4 | i;
9696
9797         // turn on powered leds
98         if (m_power_on && m_leds_state[i] >> j & 1)
98         if (m_leds_state[i] >> j & 1)
9999            m_leds_decay[di] = LEDS_DECAY_TIME;
100100
101101         // determine active state
102         int ds = (m_leds_decay[di] != 0) ? 1 : 0;
102         int ds = (m_power_on && m_leds_decay[di] != 0) ? 1 : 0;
103103         active_state[i] |= (ds << j);
104104      }
105105   }
r242959r242960
676676static MACHINE_CONFIG_START( tisr16, ticalc1x_state )
677677
678678   /* basic machine hardware */
679   MCFG_CPU_ADD("maincpu", TMS1000, 250000) // guessed
679   MCFG_CPU_ADD("maincpu", TMS1000, 250000)
680680   MCFG_TMS1XXX_READ_K_CB(READ8(ticalc1x_state, tisr16_read_k))
681681   MCFG_TMS1XXX_WRITE_O_CB(WRITE16(ticalc1x_state, tisr16_write_o))
682682   MCFG_TMS1XXX_WRITE_R_CB(WRITE16(ticalc1x_state, tisr16_write_r))
r242959r242960
698698static MACHINE_CONFIG_DERIVED( ti1270, t9base )
699699
700700   /* basic machine hardware */
701   MCFG_CPU_ADD("maincpu", TMS0970, 250000) // guessed
701   MCFG_CPU_ADD("maincpu", TMS0970, 250000)
702702   MCFG_TMS1XXX_READ_K_CB(READ8(ticalc1x_state, ti1270_read_k))
703703   MCFG_TMS1XXX_WRITE_O_CB(WRITE16(ticalc1x_state, ti1270_write_o))
704704   MCFG_TMS1XXX_WRITE_R_CB(WRITE16(ticalc1x_state, ti1270_write_r))
r242959r242960
709709static MACHINE_CONFIG_DERIVED( wizatron, t9base )
710710
711711   /* basic machine hardware */
712   MCFG_CPU_ADD("maincpu", TMS0970, 250000) // guessed
712   MCFG_CPU_ADD("maincpu", TMS0970, 250000)
713713   MCFG_TMS1XXX_READ_K_CB(READ8(ticalc1x_state, wizatron_read_k))
714714   MCFG_TMS1XXX_WRITE_O_CB(WRITE16(ticalc1x_state, wizatron_write_o))
715715   MCFG_TMS1XXX_WRITE_R_CB(WRITE16(ticalc1x_state, wizatron_write_r))
r242959r242960
721721static MACHINE_CONFIG_DERIVED( ti30, t9base )
722722
723723   /* basic machine hardware */
724   MCFG_CPU_ADD("maincpu", TMS0980, 400000) // guessed
724   MCFG_CPU_ADD("maincpu", TMS0980, 250000)
725725   MCFG_TMS1XXX_READ_K_CB(READ8(ticalc1x_state, ti30_read_k))
726726   MCFG_TMS1XXX_WRITE_O_CB(WRITE16(ticalc1x_state, ti30_write_o))
727727   MCFG_TMS1XXX_WRITE_R_CB(WRITE16(ticalc1x_state, ti30_write_r))
trunk/src/mess/drivers/tispeak.c
r242959r242960
2121#include "bus/generic/carts.h"
2222
2323#include "lantutor.lh"
24#include "snspell.lh"
24#include "tispeak.lh"
2525
2626// The master clock is a single stage RC oscillator into TMS5100 RCOSC:
2727// In an early 1979 Speak & Spell, C is 68pf, R is a 50kohm trimpot which is set to around 33.6kohm
r242959r242960
4141      m_tms5100(*this, "tms5100"),
4242      m_tms6100(*this, "tms6100"),
4343      m_cart(*this, "cartslot"),
44      m_filoff_timer(*this, "filoff"),
4445      m_button_matrix(*this, "IN")
4546   { }
4647
r242959r242960
4849   required_device<tms5100_device> m_tms5100;
4950   required_device<tms6100_device> m_tms6100;
5051   optional_device<generic_slot_device> m_cart;
52   required_device<timer_device> m_filoff_timer;
5153   required_ioport_array<9> m_button_matrix;
5254
5355   UINT16 m_r;
5456   UINT16 m_o;
57   int m_filament_on;
5558   int m_power_on;
5659
57   UINT16 m_leds_state[0x10];
58   UINT16 m_leds_cache[0x10];
59   UINT8 m_leds_decay[0x100];
60   void leds_update();
61   TIMER_DEVICE_CALLBACK_MEMBER(leds_decay_tick);
60   UINT16 m_digit_state[0x10];
61   void display_update();
62   TIMER_DEVICE_CALLBACK_MEMBER(delayed_filament_off);
6263
6364   UINT32 m_cart_max_size;
6465   UINT8* m_cart_base;
r242959r242960
127128// The device strobes the filament-enable very fast, it is unnoticeable to the user.
128129// To prevent flickering here, we need to simulate a decay.
129130
130// decay time, in steps of 10ms
131#define LEDS_DECAY_TIME 4
131// decay time in milliseconds
132#define FILOFF_DECAY_TIME 20
132133
133void tispeak_state::leds_update()
134TIMER_DEVICE_CALLBACK_MEMBER(tispeak_state::delayed_filament_off)
134135{
135   int filament_on = (m_r & 0x8000) ? 1 : 0;
136   UINT16 active_state[0x10];
136   // turn off display
137   m_filament_on = 0;
138   display_update();
139}
137140
138   for (int i = 0; i < 0x10; i++)
141void tispeak_state::display_update()
142{
143   // filament on/off
144   if (m_r & 0x8000)
139145   {
140      // update current state
141      if (m_r >> i & 1)
142         m_leds_state[i] = m_o;
143
144      active_state[i] = 0;
145
146      for (int j = 0; j < 0x10; j++)
147      {
148         int di = j << 4 | i;
149
150         // turn on powered leds
151         if (m_power_on && filament_on && m_leds_state[i] >> j & 1)
152            m_leds_decay[di] = LEDS_DECAY_TIME;
153
154         // determine active state
155         int ds = (m_leds_decay[di] != 0) ? 1 : 0;
156         active_state[i] |= (ds << j);
157      }
146      m_filament_on = 1;
147      m_filoff_timer->reset();
158148   }
149   else if (m_filament_on && m_filoff_timer->time_left() == attotime::never)
150   {
151      // schedule delayed filament-off
152      m_filoff_timer->adjust(attotime::from_msec(FILOFF_DECAY_TIME));
153   }
159154
160   // on difference, send to output
155   // update digit state
161156   for (int i = 0; i < 0x10; i++)
162      if (m_leds_cache[i] != active_state[i])
163      {
164         output_set_digit_value(i, active_state[i] & 0x3fff);
157      if (m_r >> i & 1)
158         m_digit_state[i] = m_o;
165159
166         for (int j = 0; j < 0x10; j++)
167            output_set_lamp_value(i*0x10 + j, active_state[i] >> j & 1);
168      }
160   // send to output
161   for (int i = 0; i < 0x10; i++)
162   {
163      // standard led14seg
164      output_set_digit_value(i, m_filament_on ? m_digit_state[i] & 0x3fff : 0);
169165
170   memcpy(m_leds_cache, active_state, sizeof(m_leds_cache));
166      // DP(display point) and AP(apostrophe) segments as lamps
167      output_set_lamp_value(i*10 + 0, m_digit_state[i] >> 14 & m_filament_on);
168      output_set_lamp_value(i*10 + 1, m_digit_state[i] >> 15 & m_filament_on);
169   }
171170}
172171
173TIMER_DEVICE_CALLBACK_MEMBER(tispeak_state::leds_decay_tick)
174{
175   // slowly turn off unpowered leds
176   for (int i = 0; i < 0x100; i++)
177      if (!(m_leds_state[i & 0xf] >> (i>>4) & 1) && m_leds_decay[i])
178         m_leds_decay[i]--;
179172
180   leds_update();
181}
182173
183
184
185174/***************************************************************************
186175
187176  I/O
r242959r242960
206195WRITE16_MEMBER(tispeak_state::snspell_write_r)
207196{
208197   // R0-R7: input mux and select digit (+R8 if the device has 9 digits)
209   // R15: filament on (handled in leds_update)
198   // R15: filament on (handled in display_update)
210199   // R13: power-off request, on falling edge
211200   if ((m_r >> 13 & 1) && !(data >> 13 & 1))
212201      power_off();
213202
214203   // other bits: MCU internal use
215204   m_r = data;
216   leds_update();
205   display_update();
217206}
218207
219208WRITE16_MEMBER(tispeak_state::snspell_write_o)
r242959r242960
222211   // E,D,C,G,B,A,I,M,L,K,N,J,[AP],H,F,[DP] (sidenote: TI KLMN = MAME MLNK)
223212   m_o = BITSWAP16(data,12,15,10,7,8,9,11,6,13,3,14,0,1,2,4,5);
224213
225   leds_update();
214   display_update();
226215}
227216
228217
r242959r242960
244233   // [DP],D,C,H,F,B,I,M,L,K,N,J,[AP],E,G,A (sidenote: TI KLMN = MAME MLNK)
245234   m_o = BITSWAP16(data,12,0,10,7,8,9,11,6,3,14,4,13,1,2,5,15);
246235
247   leds_update();
236   display_update();
248237}
249238
250239
r242959r242960
254243{
255244   // same as default, except R13 is used for an extra digit
256245   m_r = data;
257   leds_update();
246   display_update();
258247}
259248
260249
r242959r242960
437426
438427void tispeak_state::machine_reset()
439428{
429   m_filament_on = 0;
440430   m_power_on = 1;
441431}
442432
443433void tispeak_state::machine_start()
444434{
445435   // zerofill
446   memset(m_leds_state, 0, sizeof(m_leds_state));
447   memset(m_leds_cache, 0, sizeof(m_leds_cache));
448   memset(m_leds_decay, 0, sizeof(m_leds_decay));
449
436   memset(m_digit_state, 0, sizeof(m_digit_state));
450437   m_r = 0;
451438   m_o = 0;
439   m_filament_on = 0;
452440   m_power_on = 0;
453441
454442   // register for savestates
455   save_item(NAME(m_leds_state));
456   save_item(NAME(m_leds_cache));
457   save_item(NAME(m_leds_decay));
458
443   save_item(NAME(m_digit_state));
459444   save_item(NAME(m_r));
460445   save_item(NAME(m_o));
446   save_item(NAME(m_filament_on));
461447   save_item(NAME(m_power_on));
462448
463449   // init cartridge
r242959r242960
483469   MCFG_TMS0270_WRITE_CTL_CB(DEVWRITE8("tms5100", tms5100_device, ctl_w))
484470   MCFG_TMS0270_WRITE_PDC_CB(DEVWRITELINE("tms5100", tms5100_device, pdc_w))
485471
486   MCFG_TIMER_DRIVER_ADD_PERIODIC("leds_decay", tispeak_state, leds_decay_tick, attotime::from_msec(10))
487   MCFG_DEFAULT_LAYOUT(layout_snspell) // max 9 digits
472   MCFG_TIMER_DRIVER_ADD("filoff", tispeak_state, delayed_filament_off)
473   MCFG_DEFAULT_LAYOUT(layout_tispeak) // max 9 digits
488474
489475   /* no video! */
490476
trunk/src/mess/includes/msx.h
r242959r242960
2424#include "formats/basicdsk.h"
2525#include "formats/fmsx_cas.h"
2626#include "formats/msx_dsk.h"
27//#include "osdepend.h"
2728#include "hashfile.h"
2829#include "machine/wd_fdc.h"
2930#include "imagedev/floppy.h"
trunk/src/mess/layout/elecdet.lay
r242959r242960
1<?xml version="1.0"?>
2<mamelayout version="2">
3
4   <element name="digit" defstate="0">
5      <led7seg><color red="1.0" green="0.2" blue="0.2" /></led7seg>
6   </element>
7
8<!-- some of the display digits are unconnected (labeled digit99 here) -->
9
10   <view name="Internal Layout">
11      <bounds left="0" right="100" top="0" bottom="15" />
12
13      <bezel name="digit6" element="digit">
14         <bounds x="0" y="0" width="10" height="15" />
15      </bezel>
16      <bezel name="digit5" element="digit">
17         <bounds x="10" y="0" width="10" height="15" />
18      </bezel>
19      <bezel name="digit99" element="digit">
20         <bounds x="20" y="0" width="10" height="15" />
21      </bezel>
22      <bezel name="digit4" element="digit">
23         <bounds x="30" y="0" width="10" height="15" />
24      </bezel>
25      <bezel name="digit3" element="digit">
26         <bounds x="40" y="0" width="10" height="15" />
27      </bezel>
28      <bezel name="digit2" element="digit">
29         <bounds x="50" y="0" width="10" height="15" />
30      </bezel>
31      <bezel name="digit99" element="digit">
32         <bounds x="60" y="0" width="10" height="15" />
33      </bezel>
34      <bezel name="digit1" element="digit">
35         <bounds x="70" y="0" width="10" height="15" />
36      </bezel>
37      <bezel name="digit0" element="digit">
38         <bounds x="80" y="0" width="10" height="15" />
39      </bezel>
40      <bezel name="digit99" element="digit">
41         <bounds x="90" y="0" width="10" height="15" />
42      </bezel>
43
44   </view>
45</mamelayout>
trunk/src/mess/layout/lantutor.lay
r242959r242960
3131      <bezel name="digit8" element="digit"><bounds x="88" y="4" width="10" height="15" /></bezel>
3232      <bezel name="digit13" element="digit"><bounds x="99" y="4" width="10" height="15" /></bezel>
3333
34      <bezel name="lamp14" element="triangle_mark"><bounds x="4" y="0" width="4" height="3" /></bezel>
35      <bezel name="lamp30" element="triangle_mark"><bounds x="15" y="0" width="4" height="3" /></bezel>
36      <bezel name="lamp46" element="triangle_mark"><bounds x="26" y="0" width="4" height="3" /></bezel>
37      <bezel name="lamp62" element="triangle_mark"><bounds x="37" y="0" width="4" height="3" /></bezel>
38      <bezel name="lamp78" element="triangle_mark"><bounds x="48" y="0" width="4" height="3" /></bezel>
39      <bezel name="lamp94" element="triangle_mark"><bounds x="59" y="0" width="4" height="3" /></bezel>
40      <bezel name="lamp110" element="triangle_mark"><bounds x="70" y="0" width="4" height="3" /></bezel>
41      <bezel name="lamp126" element="triangle_mark"><bounds x="81" y="0" width="4" height="3" /></bezel>
42      <bezel name="lamp142" element="triangle_mark"><bounds x="92" y="0" width="4" height="3" /></bezel>
43      <bezel name="lamp222" element="triangle_mark"><bounds x="103" y="0" width="4" height="3" /></bezel>
34      <bezel name="lamp0" element="triangle_mark"><bounds x="4" y="0" width="4" height="3" /></bezel>
35      <bezel name="lamp10" element="triangle_mark"><bounds x="15" y="0" width="4" height="3" /></bezel>
36      <bezel name="lamp20" element="triangle_mark"><bounds x="26" y="0" width="4" height="3" /></bezel>
37      <bezel name="lamp30" element="triangle_mark"><bounds x="37" y="0" width="4" height="3" /></bezel>
38      <bezel name="lamp40" element="triangle_mark"><bounds x="48" y="0" width="4" height="3" /></bezel>
39      <bezel name="lamp50" element="triangle_mark"><bounds x="59" y="0" width="4" height="3" /></bezel>
40      <bezel name="lamp60" element="triangle_mark"><bounds x="70" y="0" width="4" height="3" /></bezel>
41      <bezel name="lamp70" element="triangle_mark"><bounds x="81" y="0" width="4" height="3" /></bezel>
42      <bezel name="lamp80" element="triangle_mark"><bounds x="92" y="0" width="4" height="3" /></bezel>
43      <bezel name="lamp130" element="triangle_mark"><bounds x="103" y="0" width="4" height="3" /></bezel>
4444
4545   </view>
4646</mamelayout>
trunk/src/mess/layout/snspell.lay
r242959r242960
1<?xml version="1.0"?>
2<mamelayout version="2">
3
4<!-- define elements -->
5
6<!-- note: the TI Speak & Spell 14seg digits look different from MAME's default, most notably the right half is wider -->
7
8   <element name="digit" defstate="0">
9      <led14seg><color red="0.2" green="1.0" blue="0.85" /></led14seg>
10   </element>
11
12<!-- add our own for DP(display point) and the custom AP(apostrophe) segments -->
13
14   <element name="lamp_dp" defstate="0">
15      <disk state="0"><color red="0.0235" green="0.1255" blue="0.1059" /></disk>
16      <disk state="1"><color red="0.2" green="1.0" blue="0.85" /></disk>
17   </element>
18   <element name="lamp_ap" defstate="0">
19      <rect state="0"><color red="0.0235" green="0.1255" blue="0.1059" /></rect>
20      <rect state="1"><color red="0.2" green="1.0" blue="0.85" /></rect>
21   </element>
22
23
24
25<!-- build screen -->
26
27   <view name="Internal Layout">
28      <bounds left="0" right="100" top="0" bottom="15" />
29
30   <!-- 9 digits (snspell has 8, snmath has 9) -->
31
32      <bezel name="digit0" element="digit"><bounds x="0" y="0" width="10" height="15" /></bezel>
33      <bezel name="lamp14" element="lamp_dp"><bounds x="9" y="13.5" width="1.5" height="1.5" /></bezel>
34      <bezel name="lamp15" element="lamp_ap"><bounds x="10.5" y="0" width="0.5" height="3.5" /></bezel>
35
36      <bezel name="digit1" element="digit"><bounds x="11" y="0" width="10" height="15" /></bezel>
37      <bezel name="lamp30" element="lamp_dp"><bounds x="20" y="13.5" width="1.5" height="1.5" /></bezel>
38      <bezel name="lamp31" element="lamp_ap"><bounds x="21.5" y="0" width="0.5" height="3.5" /></bezel>
39
40      <bezel name="digit2" element="digit"><bounds x="22" y="0" width="10" height="15" /></bezel>
41      <bezel name="lamp46" element="lamp_dp"><bounds x="31" y="13.5" width="1.5" height="1.5" /></bezel>
42      <bezel name="lamp47" element="lamp_ap"><bounds x="32.5" y="0" width="0.5" height="3.5" /></bezel>
43
44      <bezel name="digit3" element="digit"><bounds x="33" y="0" width="10" height="15" /></bezel>
45      <bezel name="lamp62" element="lamp_dp"><bounds x="42" y="13.5" width="1.5" height="1.5" /></bezel>
46      <bezel name="lamp63" element="lamp_ap"><bounds x="43.5" y="0" width="0.5" height="3.5" /></bezel>
47
48      <bezel name="digit4" element="digit"><bounds x="44" y="0" width="10" height="15" /></bezel>
49      <bezel name="lamp78" element="lamp_dp"><bounds x="53" y="13.5" width="1.5" height="1.5" /></bezel>
50      <bezel name="lamp79" element="lamp_ap"><bounds x="54.5" y="0" width="0.5" height="3.5" /></bezel>
51
52      <bezel name="digit5" element="digit"><bounds x="55" y="0" width="10" height="15" /></bezel>
53      <bezel name="lamp94" element="lamp_dp"><bounds x="64" y="13.5" width="1.5" height="1.5" /></bezel>
54      <bezel name="lamp95" element="lamp_ap"><bounds x="65.5" y="0" width="0.5" height="3.5" /></bezel>
55
56      <bezel name="digit6" element="digit"><bounds x="66" y="0" width="10" height="15" /></bezel>
57      <bezel name="lamp110" element="lamp_dp"><bounds x="75" y="13.5" width="1.5" height="1.5" /></bezel>
58      <bezel name="lamp111" element="lamp_ap"><bounds x="76.5" y="0" width="0.5" height="3.5" /></bezel>
59
60      <bezel name="digit7" element="digit"><bounds x="77" y="0" width="10" height="15" /></bezel>
61      <bezel name="lamp126" element="lamp_dp"><bounds x="86" y="13.5" width="1.5" height="1.5" /></bezel>
62      <bezel name="lamp127" element="lamp_ap"><bounds x="87.5" y="0" width="0.5" height="3.5" /></bezel>
63
64      <bezel name="digit8" element="digit"><bounds x="88" y="0" width="10" height="15" /></bezel>
65      <bezel name="lamp142" element="lamp_dp"><bounds x="97" y="13.5" width="1.5" height="1.5" /></bezel>
66      <bezel name="lamp143" element="lamp_ap"><bounds x="98.5" y="0" width="0.5" height="3.5" /></bezel>
67
68   </view>
69</mamelayout>
trunk/src/mess/layout/splitsec.lay
r242959r242960
1<?xml version="1.0"?>
2<mamelayout version="2">
3
4<!-- define elements -->
5
6   <element name="static_black"><rect><color red="0.0" green="0.0" blue="0.0" /></rect></element>
7
8   <element name="lamp_disk" defstate="0">
9      <disk state="1"><color red="1.0" green="0.24" blue="0.26" /></disk>
10      <disk state="0"><color red="0.15" green="0.043" blue="0.047" /></disk>
11   </element>
12   <element name="lamp_rect" defstate="0">
13      <rect state="1"><color red="1.0" green="0.24" blue="0.26" /></rect>
14      <rect state="0"><color red="0.15" green="0.043" blue="0.047" /></rect>
15   </element>
16
17
18<!-- build screen -->
19
20   <view name="Internal Layout">
21      <bounds left="0" right="18" top="0" bottom="28" />
22      <bezel element="static_black">
23         <bounds left="0" right="18" top="0" bottom="28" />
24      </bezel>
25
26   <!-- maze of lamps -->
27
28      <bezel name="lamp6" element="lamp_rect"><bounds x="2" y="1" width="4" height="1" /></bezel>
29      <bezel name="lamp4" element="lamp_rect"><bounds x="7" y="1" width="4" height="1" /></bezel>
30      <bezel name="lamp2" element="lamp_rect"><bounds x="12" y="1" width="4" height="1" /></bezel>
31
32      <bezel name="lamp16" element="lamp_rect"><bounds x="1" y="2" width="1" height="4" /></bezel>
33      <bezel name="lamp5" element="lamp_disk"><bounds x="3" y="3" width="2" height="2" /></bezel>
34      <bezel name="lamp14" element="lamp_rect"><bounds x="6" y="2" width="1" height="4" /></bezel>
35      <bezel name="lamp3" element="lamp_disk"><bounds x="8" y="3" width="2" height="2" /></bezel>
36      <bezel name="lamp12" element="lamp_rect"><bounds x="11" y="2" width="1" height="4" /></bezel>
37      <bezel name="lamp1" element="lamp_disk"><bounds x="13" y="3" width="2" height="2" /></bezel>
38      <bezel name="lamp10" element="lamp_rect"><bounds x="16" y="2" width="1" height="4" /></bezel>
39
40      <bezel name="lamp15" element="lamp_rect"><bounds x="2" y="6" width="4" height="1" /></bezel>
41      <bezel name="lamp13" element="lamp_rect"><bounds x="7" y="6" width="4" height="1" /></bezel>
42      <bezel name="lamp11" element="lamp_rect"><bounds x="12" y="6" width="4" height="1" /></bezel>
43
44      <bezel name="lamp26" element="lamp_rect"><bounds x="1" y="7" width="1" height="4" /></bezel>
45      <bezel name="lamp25" element="lamp_disk"><bounds x="3" y="8" width="2" height="2" /></bezel>
46      <bezel name="lamp24" element="lamp_rect"><bounds x="6" y="7" width="1" height="4" /></bezel>
47      <bezel name="lamp23" element="lamp_disk"><bounds x="8" y="8" width="2" height="2" /></bezel>
48      <bezel name="lamp22" element="lamp_rect"><bounds x="11" y="7" width="1" height="4" /></bezel>
49      <bezel name="lamp21" element="lamp_disk"><bounds x="13" y="8" width="2" height="2" /></bezel>
50      <bezel name="lamp20" element="lamp_rect"><bounds x="16" y="7" width="1" height="4" /></bezel>
51
52      <bezel name="lamp35" element="lamp_rect"><bounds x="2" y="11" width="4" height="1" /></bezel>
53      <bezel name="lamp33" element="lamp_rect"><bounds x="7" y="11" width="4" height="1" /></bezel>
54      <bezel name="lamp31" element="lamp_rect"><bounds x="12" y="11" width="4" height="1" /></bezel>
55
56      <bezel name="lamp36" element="lamp_rect"><bounds x="1" y="12" width="1" height="4" /></bezel>
57      <bezel name="lamp45" element="lamp_disk"><bounds x="3" y="13" width="2" height="2" /></bezel>
58      <bezel name="lamp34" element="lamp_rect"><bounds x="6" y="12" width="1" height="4" /></bezel>
59      <bezel name="lamp43" element="lamp_disk"><bounds x="8" y="13" width="2" height="2" /></bezel>
60      <bezel name="lamp32" element="lamp_rect"><bounds x="11" y="12" width="1" height="4" /></bezel>
61      <bezel name="lamp41" element="lamp_disk"><bounds x="13" y="13" width="2" height="2" /></bezel>
62      <bezel name="lamp30" element="lamp_rect"><bounds x="16" y="12" width="1" height="4" /></bezel>
63
64      <bezel name="lamp55" element="lamp_rect"><bounds x="2" y="16" width="4" height="1" /></bezel>
65      <bezel name="lamp53" element="lamp_rect"><bounds x="7" y="16" width="4" height="1" /></bezel>
66      <bezel name="lamp51" element="lamp_rect"><bounds x="12" y="16" width="4" height="1" /></bezel>
67
68      <bezel name="lamp46" element="lamp_rect"><bounds x="1" y="17" width="1" height="4" /></bezel>
69      <bezel name="lamp65" element="lamp_disk"><bounds x="3" y="18" width="2" height="2" /></bezel>
70      <bezel name="lamp44" element="lamp_rect"><bounds x="6" y="17" width="1" height="4" /></bezel>
71      <bezel name="lamp63" element="lamp_disk"><bounds x="8" y="18" width="2" height="2" /></bezel>
72      <bezel name="lamp42" element="lamp_rect"><bounds x="11" y="17" width="1" height="4" /></bezel>
73      <bezel name="lamp61" element="lamp_disk"><bounds x="13" y="18" width="2" height="2" /></bezel>
74      <bezel name="lamp40" element="lamp_rect"><bounds x="16" y="17" width="1" height="4" /></bezel>
75
76      <bezel name="lamp75" element="lamp_rect"><bounds x="2" y="21" width="4" height="1" /></bezel>
77      <bezel name="lamp73" element="lamp_rect"><bounds x="7" y="21" width="4" height="1" /></bezel>
78      <bezel name="lamp71" element="lamp_rect"><bounds x="12" y="21" width="4" height="1" /></bezel>
79
80      <bezel name="lamp56" element="lamp_rect"><bounds x="1" y="22" width="1" height="4" /></bezel>
81      <bezel name="lamp66" element="lamp_disk"><bounds x="3" y="23" width="2" height="2" /></bezel>
82      <bezel name="lamp54" element="lamp_rect"><bounds x="6" y="22" width="1" height="4" /></bezel>
83      <bezel name="lamp64" element="lamp_disk"><bounds x="8" y="23" width="2" height="2" /></bezel>
84      <bezel name="lamp52" element="lamp_rect"><bounds x="11" y="22" width="1" height="4" /></bezel>
85      <bezel name="lamp62" element="lamp_disk"><bounds x="13" y="23" width="2" height="2" /></bezel>
86      <bezel name="lamp50" element="lamp_rect"><bounds x="16" y="22" width="1" height="4" /></bezel>
87
88      <bezel name="lamp76" element="lamp_rect"><bounds x="2" y="26" width="4" height="1" /></bezel>
89      <bezel name="lamp74" element="lamp_rect"><bounds x="7" y="26" width="4" height="1" /></bezel>
90      <bezel name="lamp72" element="lamp_rect"><bounds x="12" y="26" width="4" height="1" /></bezel>
91
92   </view>
93</mamelayout>
trunk/src/mess/layout/tispeak.lay
r0r242960
1<?xml version="1.0"?>
2<mamelayout version="2">
3
4<!-- define elements -->
5
6<!-- note: the TI Speak & Spell 14seg digits look different from MAME's default, most notably the right half is wider -->
7
8   <element name="digit" defstate="0">
9      <led14seg><color red="0.2" green="1.0" blue="0.85" /></led14seg>
10   </element>
11
12<!-- add our own for DP(display point) and the custom AP(apostrophe) segments -->
13
14   <element name="lamp_dp" defstate="0">
15      <disk state="0"><color red="0.0235" green="0.1255" blue="0.1059" /></disk>
16      <disk state="1"><color red="0.2" green="1.0" blue="0.85" /></disk>
17   </element>
18   <element name="lamp_ap" defstate="0">
19      <rect state="0"><color red="0.0235" green="0.1255" blue="0.1059" /></rect>
20      <rect state="1"><color red="0.2" green="1.0" blue="0.85" /></rect>
21   </element>
22
23
24
25<!-- build screen -->
26
27   <view name="Internal Layout">
28      <bounds left="0" right="100" top="0" bottom="15" />
29
30   <!-- 9 digits (snspell has 8, snmath has 9) -->
31
32      <bezel name="digit0" element="digit"><bounds x="0" y="0" width="10" height="15" /></bezel>
33      <bezel name="lamp0" element="lamp_dp"><bounds x="9" y="13.5" width="1.5" height="1.5" /></bezel>
34      <bezel name="lamp1" element="lamp_ap"><bounds x="10.5" y="0" width="0.5" height="3.5" /></bezel>
35
36      <bezel name="digit1" element="digit"><bounds x="11" y="0" width="10" height="15" /></bezel>
37      <bezel name="lamp10" element="lamp_dp"><bounds x="20" y="13.5" width="1.5" height="1.5" /></bezel>
38      <bezel name="lamp11" element="lamp_ap"><bounds x="21.5" y="0" width="0.5" height="3.5" /></bezel>
39
40      <bezel name="digit2" element="digit"><bounds x="22" y="0" width="10" height="15" /></bezel>
41      <bezel name="lamp20" element="lamp_dp"><bounds x="31" y="13.5" width="1.5" height="1.5" /></bezel>
42      <bezel name="lamp21" element="lamp_ap"><bounds x="32.5" y="0" width="0.5" height="3.5" /></bezel>
43
44      <bezel name="digit3" element="digit"><bounds x="33" y="0" width="10" height="15" /></bezel>
45      <bezel name="lamp30" element="lamp_dp"><bounds x="42" y="13.5" width="1.5" height="1.5" /></bezel>
46      <bezel name="lamp31" element="lamp_ap"><bounds x="43.5" y="0" width="0.5" height="3.5" /></bezel>
47
48      <bezel name="digit4" element="digit"><bounds x="44" y="0" width="10" height="15" /></bezel>
49      <bezel name="lamp40" element="lamp_dp"><bounds x="53" y="13.5" width="1.5" height="1.5" /></bezel>
50      <bezel name="lamp41" element="lamp_ap"><bounds x="54.5" y="0" width="0.5" height="3.5" /></bezel>
51
52      <bezel name="digit5" element="digit"><bounds x="55" y="0" width="10" height="15" /></bezel>
53      <bezel name="lamp50" element="lamp_dp"><bounds x="64" y="13.5" width="1.5" height="1.5" /></bezel>
54      <bezel name="lamp51" element="lamp_ap"><bounds x="65.5" y="0" width="0.5" height="3.5" /></bezel>
55
56      <bezel name="digit6" element="digit"><bounds x="66" y="0" width="10" height="15" /></bezel>
57      <bezel name="lamp60" element="lamp_dp"><bounds x="75" y="13.5" width="1.5" height="1.5" /></bezel>
58      <bezel name="lamp61" element="lamp_ap"><bounds x="76.5" y="0" width="0.5" height="3.5" /></bezel>
59
60      <bezel name="digit7" element="digit"><bounds x="77" y="0" width="10" height="15" /></bezel>
61      <bezel name="lamp70" element="lamp_dp"><bounds x="86" y="13.5" width="1.5" height="1.5" /></bezel>
62      <bezel name="lamp71" element="lamp_ap"><bounds x="87.5" y="0" width="0.5" height="3.5" /></bezel>
63
64      <bezel name="digit8" element="digit"><bounds x="88" y="0" width="10" height="15" /></bezel>
65      <bezel name="lamp80" element="lamp_dp"><bounds x="97" y="13.5" width="1.5" height="1.5" /></bezel>
66      <bezel name="lamp81" element="lamp_ap"><bounds x="98.5" y="0" width="0.5" height="3.5" /></bezel>
67
68   </view>
69</mamelayout>
trunk/src/mess/machine/ngen_kb.c
r242959r242960
1212void ngen_keyboard_device::write(UINT8 data)
1313{
1414   // To be figured out
15   // Code 0x92 is sent on startup, perhaps resets the keyboard MCU
16   // Codes 0xAx and 0xBx appear to control the keyboard LEDs, lower nibbles controlling the state of the LEDs
17   // When setting an error code via the LEDs, 0xB0 then 0xAE is sent (presumably for error code 0xE0),
18   // so that means that 0xAx controls the Overtype, Lock, F1 and F2 LEDs, and 0xBx controls the F3, F8, F9 and F10 LEDs.
1915   logerror("KB: received character %02x\n",data);
2016}
2117
trunk/src/mess/mess.lst
r242959r242960
13201320gmtt     // 1998 Genius Master Table Top (Germany)
13211321gbs5505x // 2001 Genius BrainStation 5505X (Germany)
13221322prestige // PreComputer Prestige Elite
1323gwnf     // Genius Winner Notebook Fun (Germany)
13241323gl6000sl // Genius Leader 6000SL (Germany)
13251324gl7007sl // Genius Leader 7007SL (Germany)
13261325glcolor  // Genius Leader Color (Germany)
r242959r242960
13281327glscolor // Genius Leader Super Color (Germany)
13291328gjrstar3 // Genius Junior Redstar 3 (Germany)
13301329gj4000   // Genius Junior 4000 (Germany)
1331gjmovie  // Genius Junior Movie (Germany)
13321330gjrstar  // Genius Junior Redstar(Germany)
13331331gjrstar2 // Genius Junior Redstar 2 (Germany)
13341332gj5000   // Genius Junior 5000 (Germany)
r242959r242960
22692267starwbcp
22702268stopthie
22712269stopthiep
2272splitsec
22732270amico2k
22742271jtc
22752272jtces88
r242959r242960
26012598bitgrpha
26022599bitgrphb
26032600unk3403
2604elecdet
trunk/src/mess/mess.mak
r242959r242960
729729   $(MESSOBJ)/homebrew.a \
730730   $(MESSOBJ)/homelab.a \
731731   $(MESSOBJ)/hp.a \
732   $(MESSOBJ)/ideal.a \
733732   $(MESSOBJ)/imp.a \
734733   $(MESSOBJ)/intel.a \
735734   $(MESSOBJ)/interton.a \
r242959r242960
13061305   $(MESS_DRIVERS)/hp9k.o      \
13071306   $(MESS_DRIVERS)/hp9k_3xx.o  \
13081307
1308
13091309$(MESSOBJ)/hec2hrp.a:           \
13101310   $(MESS_DRIVERS)/hec2hrp.o   \
13111311   $(MESS_MACHINE)/hec2hrp.o   \
r242959r242960
13231323   $(MESS_DRIVERS)/sdk85.o     \
13241324   $(MESS_DRIVERS)/sdk86.o     \
13251325
1326$(MESSOBJ)/ideal.a:             \
1327   $(MESS_DRIVERS)/elecdet.o   \
1328
13291326$(MESSOBJ)/imp.a:               \
13301327   $(MESS_DRIVERS)/tim011.o    \
13311328   $(MESS_DRIVERS)/tim100.o    \
r242959r242960
14901487$(MESSOBJ)/parker.a:            \
14911488   $(MESS_DRIVERS)/cnsector.o  \
14921489   $(MESS_DRIVERS)/merlin.o    \
1493   $(MESS_DRIVERS)/splitsec.o  \
14941490   $(MESS_DRIVERS)/stopthie.o  \
14951491
14961492$(MESSOBJ)/pitronic.a:          \
r242959r242960
21102106$(MESS_DRIVERS)/dmv.o:      $(MESS_LAYOUT)/dmv.lh
21112107$(MESS_DRIVERS)/dolphunk.o: $(MESS_LAYOUT)/dolphunk.lh
21122108$(MESS_DRIVERS)/eacc.o:     $(MESS_LAYOUT)/eacc.lh
2113$(MESS_DRIVERS)/elecdet.o:  $(MESS_LAYOUT)/elecdet.lh
2114$(MESS_DRIVERS)/elekscmp.o: $(MESS_LAYOUT)/elekscmp.lh
21152109$(MESS_DRIVERS)/elf.o:      $(MESS_LAYOUT)/elf2.lh
2110$(MESS_DRIVERS)/elekscmp.o: $(MESS_LAYOUT)/elekscmp.lh
21162111$(MESS_MACHINE)/esqvfd.o:   $(MESS_LAYOUT)/esq2by40.lh \
21172112                     $(MESS_LAYOUT)/esq1by22.lh
21182113$(MESS_DRIVERS)/et3400.o:   $(MESS_LAYOUT)/et3400.lh
r242959r242960
21722167$(MESS_DRIVERS)/sitcom.o:   $(MESS_LAYOUT)/sitcom.lh
21732168$(MESS_DRIVERS)/slc1.o:     $(MESS_LAYOUT)/slc1.lh
21742169$(MESS_DRIVERS)/sms.o:      $(MESS_LAYOUT)/sms1.lh
2175$(MESS_DRIVERS)/splitsec.o: $(MESS_LAYOUT)/splitsec.lh
21762170$(MESS_DRIVERS)/starwbc.o:  $(MESS_LAYOUT)/starwbc.lh
21772171$(MESS_DRIVERS)/stopthie.o: $(MESS_LAYOUT)/stopthie.lh
21782172$(MESS_DRIVERS)/super80.o:  $(MESS_LAYOUT)/super80.lh
r242959r242960
21912185                     $(MESS_LAYOUT)/tisr16.lh \
21922186                     $(MESS_LAYOUT)/wizatron.lh
21932187$(MESS_DRIVERS)/tispeak.o:  $(MESS_LAYOUT)/lantutor.lh \
2194                     $(MESS_LAYOUT)/snspell.lh
2188                     $(MESS_LAYOUT)/tispeak.lh
21952189$(MESS_DRIVERS)/tk80.o:     $(MESS_LAYOUT)/tk80.lh
21962190$(MESS_DRIVERS)/tm990189.o: $(MESS_LAYOUT)/tm990189.lh \
21972191                     $(MESS_LAYOUT)/tm990189v.lh
trunk/src/osd/modules/debugger/debugint.c
r242959r242960
851851   }
852852   if (debug_font != NULL)
853853   {
854      m_machine->render().font_free(debug_font);
854      m_osd.machine().render().font_free(debug_font);
855855      debug_font = NULL;
856856   }
857857   if (menu)
858858      global_free(menu);
859859}
860860
861void debugger_internal::init_debugger(running_machine &machine)
861void debugger_internal::init_debugger()
862862{
863863   unicode_char ch;
864864   int chw;
865
866   m_machine = &machine;
867
868   debug_font = m_machine->render().font_alloc("ui.bdf"); //ui_get_font(machine);
865   debug_font = m_osd.machine().render().font_alloc("ui.bdf"); //ui_get_font(machine);
869866   debug_font_width = 0;
870867   debug_font_height = 15;
871868
r242959r242960
874871   list = NULL;
875872   focus_view = NULL;
876873
877   debug_font_aspect = m_machine->render().ui_aspect();
874   debug_font_aspect = m_osd.machine().render().ui_aspect();
878875
879876   for (ch=0;ch<=127;ch++)
880877   {
r242959r242960
14451442
14461443void debugger_internal::debugger_update()
14471444{
1448   if (!debug_cpu_is_stopped(*m_machine) && m_machine->phase() == MACHINE_PHASE_RUNNING)
1445   if (!debug_cpu_is_stopped(m_osd.machine()) && m_osd.machine().phase() == MACHINE_PHASE_RUNNING)
14491446   {
14501447      update_views();
14511448   }
r242959r242960
14551452//  debugger_internal - constructor
14561453//-------------------------------------------------
14571454debugger_internal::debugger_internal(const osd_interface &osd)
1458   : osd_debugger_interface(osd), m_machine(NULL)
1455   : osd_debugger_interface(osd)
14591456{
14601457}
trunk/src/osd/modules/debugger/debugint.h
r242959r242960
1515#define __DEBUGGER_INTERNAL_H__
1616
1717#include "osdepend.h"
18#include "modules/lib/osdobj_common.h"
1918
2019class debugger_internal : public osd_debugger_interface
2120{
r242959r242960
2423   debugger_internal(const osd_interface &osd);
2524   virtual ~debugger_internal() { }
2625
27   virtual void init_debugger(running_machine &machine);
26   virtual void init_debugger();
2827   virtual void wait_for_debugger(device_t &device, bool firststop);
2928   virtual void debugger_update();
3029   virtual void debugger_exit();
31private:
32   running_machine *m_machine;
3330};
3431
3532extern const osd_debugger_type OSD_DEBUGGER_INTERNAL;
trunk/src/osd/modules/debugger/debugosx.h
r242959r242960
1818// MAME headers
1919#include "emu.h"
2020#include "debug/debugvw.h"
21#include "modules/lib/osdobj_common.h"
2221
2322
2423#ifdef __OBJC__
r242959r242960
374373   debugger_osx(const osd_interface &osd);
375374   virtual ~debugger_osx() { }
376375
377   virtual void init_debugger(running_machine &machine);
376   virtual void init_debugger();
378377   virtual void wait_for_debugger(device_t &device, bool firststop);
379378   virtual void debugger_update();
380379   virtual void debugger_exit();
381private:
382   running_machine *m_machine;
383380};
384381
385382extern const osd_debugger_type OSD_DEBUGGER_OSX;
trunk/src/osd/modules/debugger/debugosx.m
r242959r242960
7373//  debugger_osx - constructor
7474//-------------------------------------------------
7575debugger_osx::debugger_osx(const osd_interface &osd)
76   : osd_debugger_interface(osd), m_machine(NULL)
76   : osd_debugger_interface(osd)
7777{
7878}
7979
r242959r242960
8181//  debugger_osx::init_debugger
8282//============================================================
8383
84void debugger_osx::init_debugger(running_machine &machine)
84void debugger_osx::init_debugger()
8585{
86    m_machine = &machine;
8786}
8887
8988//============================================================
r242959r242960
9493{
9594   // create a console window
9695   if (main_console == nil)
97      console_create_window(*m_machine);
96      console_create_window(m_osd.machine());
9897
9998   // make sure the debug windows are visible
10099   waiting_for_debugger = YES;
trunk/src/osd/modules/debugger/debugqt.c
r242959r242960
1919#include "emu.h"
2020#include "config.h"
2121#include "debugger.h"
22#include "modules/lib/osdobj_common.h"
2322
2423#include "qt/debugqtlogwindow.h"
2524#include "qt/debugqtmainwindow.h"
r242959r242960
5150//  debugger_qt - constructor
5251//-------------------------------------------------
5352debugger_qt::debugger_qt(const osd_interface &osd)
54   : osd_debugger_interface(osd), m_machine(NULL)
53   : osd_debugger_interface(osd)
5554{
5655}
5756
r242959r242960
228227bool winwindow_qt_filter(void *message);
229228#endif
230229
231void debugger_qt::init_debugger(running_machine &machine)
230void debugger_qt::init_debugger()
232231{
233232   if (qApp == NULL)
234233   {
r242959r242960
250249      oneShot = true;
251250   }
252251
253   m_machine = &machine;
254252   // Setup the configuration XML saving and loading
255   config_register(machine,
253   config_register(m_osd.machine(),
256254               "debugger",
257               config_saveload_delegate(FUNC(xml_configuration_load), &machine),
258               config_saveload_delegate(FUNC(xml_configuration_save), &machine));
255               config_saveload_delegate(FUNC(xml_configuration_load), &m_osd.machine()),
256               config_saveload_delegate(FUNC(xml_configuration_save), &m_osd.machine()));
259257}
260258
261259
r242959r242960
278276   // Dialog initialization
279277   if (oneShot)
280278   {
281      mainQtWindow = new MainWindow(m_machine);
279      mainQtWindow = new MainWindow(&m_osd.machine());
282280      load_and_clear_main_window_config(xmlConfigurations);
283      setup_additional_startup_windows(*m_machine, xmlConfigurations);
281      setup_additional_startup_windows(m_osd.machine(), xmlConfigurations);
284282      mainQtWindow->show();
285283      oneShot = false;
286284   }
r242959r242960
327325   }
328326
329327   // Exit if the machine has been instructed to do so (scheduled event == exit || hard_reset)
330   if (m_machine->scheduled_event_pending())
328   if (m_osd.machine().scheduled_event_pending())
331329   {
332330      // Keep a list of windows we want to save.
333331      // We need to do this here because by the time xml_configuration_save gets called
r242959r242960
335333      gather_save_configurations();
336334   }
337335#if defined(WIN32) && !defined(SDLMAME_WIN32)
338      winwindow_update_cursor_state(*m_machine); // make sure the cursor isn't hidden while in debugger
336      winwindow_update_cursor_state(m_osd.machine()); // make sure the cursor isn't hidden while in debugger
339337#endif
340338}
341339
trunk/src/osd/modules/debugger/debugqt.h
r242959r242960
1414#ifndef __DEBUGGER_QT_H__
1515#define __DEBUGGER_QT_H__
1616
17#include "emu.h"
17#include "osdepend.h"
1818
1919class debugger_qt : public osd_debugger_interface
2020{
r242959r242960
2323   debugger_qt(const osd_interface &osd);
2424   virtual ~debugger_qt();
2525
26   virtual void init_debugger(running_machine &machine);
26   virtual void init_debugger();
2727   virtual void wait_for_debugger(device_t &device, bool firststop);
2828   virtual void debugger_update();
2929   virtual void debugger_exit();
30
31private:
32   running_machine *m_machine;
3330};
3431
3532extern const osd_debugger_type OSD_DEBUGGER_QT;
trunk/src/osd/modules/debugger/debugwin.c
r242959r242960
257257
258258   // create a console window
259259   if (main_console == NULL)
260      console_create_window(*m_machine);
260      console_create_window(m_osd.machine());
261261
262262   // update the views in the console to reflect the current CPU
263263   if (main_console != NULL)
r242959r242960
276276   smart_show_all(TRUE);
277277
278278   // run input polling to ensure that our status is in sync
279   wininput_poll(*m_machine);
279   wininput_poll(m_osd.machine());
280280
281281   // get and process messages
282282   GetMessage(&message, NULL, 0, 0);
r242959r242960
294294
295295      // process everything else
296296      default:
297         winwindow_dispatch_message(*m_machine, &message);
297         winwindow_dispatch_message(m_osd.machine(), &message);
298298         break;
299299   }
300300
r242959r242960
368368//  debugwin_init_windows
369369//============================================================
370370
371void debugger_windows::init_debugger(running_machine &machine)
371void debugger_windows::init_debugger()
372372{
373373   static int class_registered;
374374
375   m_machine = &machine;
376375   // register the window classes
377376   if (!class_registered)
378377   {
r242959r242960
415414
416415      if (temp_dc != NULL)
417416      {
418         windows_options &options = downcast<windows_options &>(m_machine->options());
417         windows_options &options = downcast<windows_options &>(m_osd.machine().options());
419418         int size = options.debugger_font_size();
420419         TCHAR *t_face;
421420
r242959r242960
475474void debugger_windows::debugger_update()
476475{
477476   // if we're running live, do some checks
478   if (!winwindow_has_focus() && !debug_cpu_is_stopped(*m_machine) && m_machine->phase() == MACHINE_PHASE_RUNNING)
477   if (!winwindow_has_focus() && !debug_cpu_is_stopped(m_osd.machine()) && m_osd.machine().phase() == MACHINE_PHASE_RUNNING)
479478   {
480479      // see if the interrupt key is pressed and break if it is
481      if (debugwin_seq_pressed(*m_machine))
480      if (debugwin_seq_pressed(m_osd.machine()))
482481      {
483482         HWND focuswnd = GetFocus();
484483         debugwin_info *info;
485484
486         debug_cpu_get_visible_cpu(*m_machine)->debug()->halt_on_next_instruction("User-initiated break\n");
485         debug_cpu_get_visible_cpu(m_osd.machine())->debug()->halt_on_next_instruction("User-initiated break\n");
487486
488487         // if we were focused on some window's edit box, reset it to default
489488         for (info = window_list; info != NULL; info = info->next)
trunk/src/osd/modules/debugger/debugwin.h
r242959r242960
1313#define __DEBUGGER_WINDOWS_H__
1414
1515#include "osdepend.h"
16#include "modules/lib/osdobj_common.h"
1716
1817class debugger_windows : public osd_debugger_interface
1918{
r242959r242960
2221   debugger_windows(const osd_interface &osd);
2322   virtual ~debugger_windows() { }
2423
25   virtual void init_debugger(running_machine &machine);
24   virtual void init_debugger();
2625   virtual void wait_for_debugger(device_t &device, bool firststop);
2726   virtual void debugger_update();
2827   virtual void debugger_exit();
29private:
30   running_machine *m_machine;
3128};
3229
3330extern const osd_debugger_type OSD_DEBUGGER_WINDOWS;
trunk/src/osd/modules/debugger/none.c
r242959r242960
1313//  debugger_none - constructor
1414//-------------------------------------------------
1515debugger_none::debugger_none(const osd_interface &osd)
16   : osd_debugger_interface(osd), m_machine(NULL)
16   : osd_debugger_interface(osd)
1717{
1818}
1919
20void debugger_none::init_debugger(running_machine &machine)
20void debugger_none::init_debugger()
2121{
22    m_machine = &machine;
2322}
2423
2524void debugger_none::wait_for_debugger(device_t &device, bool firststop)
2625{
27   debug_cpu_get_visible_cpu(*m_machine)->debug()->go();
26   debug_cpu_get_visible_cpu(m_osd.machine())->debug()->go();
2827}
2928
3029void debugger_none::debugger_update()
trunk/src/osd/modules/debugger/none.h
r242959r242960
1414#define __DEBUGGER_NONE_H__
1515
1616#include "osdepend.h"
17#include "modules/lib/osdobj_common.h"
1817
1918class debugger_none : public osd_debugger_interface
2019{
r242959r242960
2322   debugger_none(const osd_interface &osd);
2423   virtual ~debugger_none() { }
2524
26   virtual void init_debugger(running_machine &machine);
25   virtual void init_debugger();
2726   virtual void wait_for_debugger(device_t &device, bool firststop);
2827   virtual void debugger_update();
2928   virtual void debugger_exit();
30private:
31   running_machine *m_machine;
3229};
3330
3431extern const osd_debugger_type OSD_DEBUGGER_NONE;
trunk/src/osd/modules/lib/osdobj_common.c
r242959r242960
1// license:BSD-3-Clause
2// copyright-holders:Aaron Giles
3/***************************************************************************
4
5    osdepend.c
6
7    OS-dependent code interface.
8
9*******************************************************************c********/
10
11
12#include "emu.h"
13#include "osdepend.h"
14#include "modules/sound/none.h"
15#include "modules/debugger/none.h"
16#include "modules/debugger/debugint.h"
17#include "modules/lib/osdobj_common.h"
18
19extern bool g_print_verbose;
20
21const options_entry osd_options::s_option_entries[] =
22{
23    { NULL,                                   NULL,       OPTION_HEADER,     "OSD CLI OPTIONS" },
24    { OSDCOMMAND_LIST_MIDI_DEVICES ";mlist",  "0",        OPTION_COMMAND,    "list available MIDI I/O devices" },
25    { OSDCOMMAND_LIST_NETWORK_ADAPTERS ";nlist", "0",     OPTION_COMMAND,    "list available network adapters" },
26
27    // debugging options
28    { NULL,                                   NULL,       OPTION_HEADER,     "OSD DEBUGGING OPTIONS" },
29    { OSDOPTION_DEBUGGER,                     OSDOPTVAL_AUTO,      OPTION_STRING,    "debugger used : " },
30    { OSDOPTION_WATCHDOG ";wdog",             "0",        OPTION_INTEGER,    "force the program to terminate if no updates within specified number of seconds" },
31
32    // performance options
33    { NULL,                                   NULL,       OPTION_HEADER,     "OSD PERFORMANCE OPTIONS" },
34    { OSDOPTION_MULTITHREADING ";mt",         "0",        OPTION_BOOLEAN,    "enable multithreading; this enables rendering and blitting on a separate thread" },
35    { OSDOPTION_NUMPROCESSORS ";np",          OSDOPTVAL_AUTO,      OPTION_STRING,     "number of processors; this overrides the number the system reports" },
36    { OSDOPTION_BENCH,                        "0",        OPTION_INTEGER,    "benchmark for the given number of emulated seconds; implies -video none -sound none -nothrottle" },
37    // video options
38    { NULL,                                   NULL,       OPTION_HEADER,     "OSD VIDEO OPTIONS" },
39// OS X can be trusted to have working hardware OpenGL, so default to it on for the best user experience
40    { OSDOPTION_VIDEO,                        OSDOPTVAL_AUTO,     OPTION_STRING,     "video output method: " },
41    { OSDOPTION_NUMSCREENS "(1-4)",           "1",        OPTION_INTEGER,    "number of screens to create; usually, you want just one" },
42    { OSDOPTION_WINDOW ";w",                  "0",        OPTION_BOOLEAN,    "enable window mode; otherwise, full screen mode is assumed" },
43    { OSDOPTION_MAXIMIZE ";max",              "1",        OPTION_BOOLEAN,    "default to maximized windows; otherwise, windows will be minimized" },
44    { OSDOPTION_KEEPASPECT ";ka",             "1",        OPTION_BOOLEAN,    "constrain to the proper aspect ratio" },
45    { OSDOPTION_UNEVENSTRETCH ";ues",         "1",        OPTION_BOOLEAN,    "allow non-integer stretch factors" },
46    { OSDOPTION_WAITVSYNC ";vs",              "0",        OPTION_BOOLEAN,    "enable waiting for the start of VBLANK before flipping screens; reduces tearing effects" },
47    { OSDOPTION_SYNCREFRESH ";srf",           "0",        OPTION_BOOLEAN,    "enable using the start of VBLANK for throttling instead of the game time" },
48
49    // per-window options
50    { NULL,                                   NULL,             OPTION_HEADER,    "OSD PER-WINDOW VIDEO OPTIONS" },
51    { OSDOPTION_SCREEN,                   OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the first screen; 'auto' here will try to make a best guess" },
52    { OSDOPTION_ASPECT ";screen_aspect",  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio for all screens; 'auto' here will try to make a best guess" },
53    { OSDOPTION_RESOLUTION ";r",          OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution for all screens; format is <width>x<height>[@<refreshrate>] or 'auto'" },
54    { OSDOPTION_VIEW,                     OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for all screens" },
55
56    { OSDOPTION_SCREEN "0",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the first screen; 'auto' here will try to make a best guess" },
57    { OSDOPTION_ASPECT "0",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio of the first screen; 'auto' here will try to make a best guess" },
58    { OSDOPTION_RESOLUTION "0;r0",        OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution of the first screen; format is <width>x<height>[@<refreshrate>] or 'auto'" },
59    { OSDOPTION_VIEW "0",                    OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for the first screen" },
60
61    { OSDOPTION_SCREEN "1",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the second screen; 'auto' here will try to make a best guess" },
62    { OSDOPTION_ASPECT "1",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio of the second screen; 'auto' here will try to make a best guess" },
63    { OSDOPTION_RESOLUTION "1;r1",        OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution of the second screen; format is <width>x<height>[@<refreshrate>] or 'auto'" },
64    { OSDOPTION_VIEW "1",                    OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for the second screen" },
65
66    { OSDOPTION_SCREEN "2",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the third screen; 'auto' here will try to make a best guess" },
67    { OSDOPTION_ASPECT "2",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio of the third screen; 'auto' here will try to make a best guess" },
68    { OSDOPTION_RESOLUTION "2;r2",        OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution of the third screen; format is <width>x<height>[@<refreshrate>] or 'auto'" },
69    { OSDOPTION_VIEW "2",                    OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for the third screen" },
70
71    { OSDOPTION_SCREEN "3",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the fourth screen; 'auto' here will try to make a best guess" },
72    { OSDOPTION_ASPECT "3",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio of the fourth screen; 'auto' here will try to make a best guess" },
73    { OSDOPTION_RESOLUTION "3;r3",        OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution of the fourth screen; format is <width>x<height>[@<refreshrate>] or 'auto'" },
74    { OSDOPTION_VIEW "3",                    OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for the fourth screen" },
75
76    // full screen options
77    { NULL,                                   NULL,  OPTION_HEADER,     "OSD FULL SCREEN OPTIONS" },
78    { OSDOPTION_SWITCHRES,                    "0",   OPTION_BOOLEAN,    "enable resolution switching" },
79
80    // sound options
81    { NULL,                                   NULL,  OPTION_HEADER,     "OSD SOUND OPTIONS" },
82    { OSDOPTION_SOUND,                        OSDOPTVAL_AUTO, OPTION_STRING,     "sound output method: " },
83    { OSDOPTION_AUDIO_LATENCY "(1-5)",        "2",   OPTION_INTEGER,    "set audio latency (increase to reduce glitches, decrease for responsiveness)" },
84
85    // End of list
86    { NULL }
87};
88
89osd_options::osd_options()
90: cli_options()
91{
92    add_entries(osd_options::s_option_entries);
93};
94
95
96//-------------------------------------------------
97//  osd_interface - constructor
98//-------------------------------------------------
99
100osd_common_t::osd_common_t(osd_options &options)
101   : m_machine(NULL),
102     m_options(options),
103     m_sound(NULL),
104     m_debugger(NULL)
105
106{
107}
108
109
110void osd_common_t::register_options()
111{
112    // Register video options and update options
113    video_options_add("none", NULL);
114    video_register();
115    update_option(OSDOPTION_VIDEO, m_video_names);
116
117    // Register sound options and update options
118    sound_options_add("none", OSD_SOUND_NONE);
119    sound_register();
120    update_option(OSDOPTION_SOUND, m_sound_names);
121
122    // Register debugger options and update options
123    debugger_options_add("none", OSD_DEBUGGER_NONE);
124    debugger_options_add("internal", OSD_DEBUGGER_INTERNAL);
125    debugger_register();
126    update_option(OSDOPTION_DEBUGGER, m_debugger_names);
127}
128
129void osd_common_t::update_option(const char * key, dynamic_array<const char *> &values)
130{
131   astring current_value(m_options.description(key));
132   astring new_option_value("");
133   for (int index = 0; index < values.count(); index++)
134   {
135      astring t(values[index]);
136      if (new_option_value.len() > 0)
137      {
138         if( index != (values.count()-1))
139            new_option_value.cat(", ");
140         else
141            new_option_value.cat(" or ");
142      }
143      new_option_value.cat(t);
144   }
145   // TODO: core_strdup() is leaked
146   m_options.set_description(key, core_strdup(current_value.cat(new_option_value).cstr()));
147}
148
149//-------------------------------------------------
150//  osd_interface - destructor
151//-------------------------------------------------
152
153osd_common_t::~osd_common_t()
154{
155   for(int i= 0; i < m_video_names.count(); ++i)
156      osd_free(const_cast<char*>(m_video_names[i]));
157   //m_video_options,reset();
158
159   for(int i= 0; i < m_sound_names.count(); ++i)
160      osd_free(const_cast<char*>(m_sound_names[i]));
161   m_sound_options.reset();
162
163   for(int i= 0; i < m_debugger_names.count(); ++i)
164      osd_free(const_cast<char*>(m_debugger_names[i]));
165   m_debugger_options.reset();
166}
167
168
169//-------------------------------------------------
170//  init - initialize the OSD system.
171//-------------------------------------------------
172
173void osd_common_t::init(running_machine &machine)
174{
175   //
176   // This function is responsible for initializing the OSD-specific
177   // video and input functionality, and registering that functionality
178   // with the MAME core.
179   //
180   // In terms of video, this function is expected to create one or more
181   // render_targets that will be used by the MAME core to provide graphics
182   // data to the system. Although it is possible to do this later, the
183   // assumption in the MAME core is that the user interface will be
184   // visible starting at init() time, so you will have some work to
185   // do to avoid these assumptions.
186   //
187   // In terms of input, this function is expected to enumerate all input
188   // devices available and describe them to the MAME core by adding
189   // input devices and their attached items (buttons/axes) via the input
190   // system.
191   //
192   // Beyond these core responsibilities, init() should also initialize
193   // any other OSD systems that require information about the current
194   // running_machine.
195   //
196   // This callback is also the last opportunity to adjust the options
197   // before they are consumed by the rest of the core.
198   //
199   // Future work/changes:
200   //
201   // Audio initialization may eventually move into here as well,
202   // instead of relying on independent callbacks from each system.
203   //
204
205   m_machine = &machine;
206
207   osd_options &options = downcast<osd_options &>(machine.options());
208   // extract the verbose printing option
209   if (options.verbose())
210      g_print_verbose = true;
211
212   // ensure we get called on the way out
213   machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(osd_common_t::osd_exit), this));
214}
215
216
217//-------------------------------------------------
218//  update - periodic system update
219//-------------------------------------------------
220
221void osd_common_t::update(bool skip_redraw)
222{
223   //
224   // This method is called periodically to flush video updates to the
225   // screen, and also to allow the OSD a chance to update other systems
226   // on a regular basis. In general this will be called at the frame
227   // rate of the system being run; however, it may be called at more
228   // irregular intervals in some circumstances (e.g., multi-screen games
229   // or games with asynchronous updates).
230   //
231}
232
233
234//-------------------------------------------------
235//  init_debugger - perform debugger-specific
236//  initialization
237//-------------------------------------------------
238
239void osd_common_t::init_debugger()
240{
241   //
242   // Unlike init() above, this method is only called if the debugger
243   // is active. This gives any OSD debugger interface a chance to
244   // create all of its structures.
245   //
246   osd_debugger_type debugger = m_debugger_options.find(options().debugger());
247   if (debugger==NULL)
248   {
249      osd_printf_warning("debugger_init: option %s not found switching to auto\n",options().debugger());
250      debugger = m_debugger_options.find("auto");
251   }
252   m_debugger = (*debugger)(*this);
253
254   m_debugger->init_debugger(machine());
255}
256
257
258//-------------------------------------------------
259//  wait_for_debugger - wait for a debugger
260//  command to be processed
261//-------------------------------------------------
262
263void osd_common_t::wait_for_debugger(device_t &device, bool firststop)
264{
265   //
266   // When implementing an OSD-driver debugger, this method should be
267   // overridden to wait for input, process it, and return. It will be
268   // called repeatedly until a command is issued that resumes
269   // execution.
270   //
271   m_debugger->wait_for_debugger(device, firststop);
272}
273
274void osd_common_t::debugger_update()
275{
276   if (m_debugger) m_debugger->debugger_update();
277}
278
279void osd_common_t::debugger_exit()
280{
281   if (m_debugger)
282   {
283      m_debugger->debugger_exit();
284      global_free(m_debugger);
285      m_debugger = NULL;
286   }
287}
288
289//-------------------------------------------------
290//  update_audio_stream - update the stereo audio
291//  stream
292//-------------------------------------------------
293
294void osd_common_t::update_audio_stream(const INT16 *buffer, int samples_this_frame)
295{
296   //
297   // This method is called whenever the system has new audio data to stream.
298   // It provides an array of stereo samples in L-R order which should be
299   // output at the configured sample_rate.
300   //
301    if (m_sound != NULL)
302        m_sound->update_audio_stream(buffer,samples_this_frame);
303}
304
305
306//-------------------------------------------------
307//  set_mastervolume - set the system volume
308//-------------------------------------------------
309
310void osd_common_t::set_mastervolume(int attenuation)
311{
312   //
313   // Attenuation is the attenuation in dB (a negative number).
314   // To convert from dB to a linear volume scale do the following:
315   //    volume = MAX_VOLUME;
316   //    while (attenuation++ < 0)
317   //       volume /= 1.122018454;      //  = (10 ^ (1/20)) = 1dB
318   //
319    if (m_sound != NULL)
320        m_sound->set_mastervolume(attenuation);
321}
322
323
324//-------------------------------------------------
325//  customize_input_type_list - provide OSD
326//  additions/modifications to the input list
327//-------------------------------------------------
328
329void osd_common_t::customize_input_type_list(simple_list<input_type_entry> &typelist)
330{
331   //
332   // inptport.c defines some general purpose defaults for key and joystick bindings.
333   // They may be further adjusted by the OS dependent code to better match the
334   // available keyboard, e.g. one could map pause to the Pause key instead of P, or
335   // snapshot to PrtScr instead of F12. Of course the user can further change the
336   // settings to anything he/she likes.
337   //
338   // This function is called on startup, before reading the configuration from disk.
339   // Scan the list, and change the keys/joysticks you want.
340   //
341}
342
343
344//-------------------------------------------------
345//  font_open - attempt to "open" a handle to the
346//  font with the given name
347//-------------------------------------------------
348
349osd_font *osd_common_t::font_open(const char *name, int &height)
350{
351   return NULL;
352}
353
354
355//-------------------------------------------------
356//  font_close - release resources associated with
357//  a given OSD font
358//-------------------------------------------------
359
360void osd_common_t::font_close(osd_font *font)
361{
362}
363
364
365//-------------------------------------------------
366//  font_get_bitmap - allocate and populate a
367//  BITMAP_FORMAT_ARGB32 bitmap containing the
368//  pixel values rgb_t(0xff,0xff,0xff,0xff)
369//  or rgb_t(0x00,0xff,0xff,0xff) for each
370//  pixel of a black & white font
371//-------------------------------------------------
372
373bool osd_common_t::font_get_bitmap(osd_font *font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs)
374{
375   return false;
376}
377
378//-------------------------------------------------
379//  get_slider_list - allocate and populate a
380//  list of OS-dependent slider values.
381//-------------------------------------------------
382
383void *osd_common_t::get_slider_list()
384{
385   return NULL;
386}
387
388//-------------------------------------------------
389//  execute_command - execute a command not yet
390//  handled by the core
391//-------------------------------------------------
392
393bool osd_common_t::execute_command(const char *command)
394{
395    if (strcmp(command, OSDCOMMAND_LIST_NETWORK_ADAPTERS) == 0)
396    {
397        network_init();
398        osd_list_network_adapters();
399        network_exit();
400        return true;
401    }
402    else if (strcmp(command, OSDCOMMAND_LIST_MIDI_DEVICES) == 0)
403    {
404        osd_list_midi_devices();
405        return true;
406    }
407
408    return false;
409
410}
411
412void osd_common_t::init_subsystems()
413{
414   if (!video_init())
415   {
416      video_exit();
417      osd_printf_error("video_init: Initialization failed!\n\n\n");
418      fflush(stderr);
419      fflush(stdout);
420      exit(-1);
421   }
422
423   sound_init();
424   input_init();
425   // we need pause callbacks
426   machine().add_notifier(MACHINE_NOTIFY_PAUSE, machine_notify_delegate(FUNC(osd_common_t::input_pause), this));
427   machine().add_notifier(MACHINE_NOTIFY_RESUME, machine_notify_delegate(FUNC(osd_common_t::input_resume), this));
428
429   output_init();
430#ifdef USE_NETWORK
431   network_init();
432#endif
433   midi_init();
434}
435
436bool osd_common_t::video_init()
437{
438   return true;
439}
440
441bool osd_common_t::window_init()
442{
443   return true;
444}
445
446bool osd_common_t::sound_init()
447{
448   osd_sound_type sound = m_sound_options.find(options().sound());
449   if (sound==NULL)
450   {
451      osd_printf_warning("sound_init: option %s not found switching to auto\n",options().sound());
452      sound = m_sound_options.find("auto");
453   }
454   if (sound != NULL)
455       m_sound = (*sound)(*this, machine());
456   else
457       m_sound = NULL;
458   return true;
459}
460
461bool osd_common_t::no_sound()
462{
463   return (strcmp(options().sound(),"none")==0) ? true : false;
464}
465
466void osd_common_t::video_register()
467{
468}
469
470void osd_common_t::sound_register()
471{
472}
473
474void osd_common_t::debugger_register()
475{
476}
477
478bool osd_common_t::input_init()
479{
480   return true;
481}
482
483void osd_common_t::input_pause()
484{
485}
486
487void osd_common_t::input_resume()
488{
489}
490
491bool osd_common_t::output_init()
492{
493   return true;
494}
495
496bool osd_common_t::network_init()
497{
498   return true;
499}
500
501void osd_common_t::exit_subsystems()
502{
503   video_exit();
504   sound_exit();
505   input_exit();
506   output_exit();
507   #ifdef USE_NETWORK
508   network_exit();
509   #endif
510   midi_exit();
511   debugger_exit();
512}
513
514void osd_common_t::video_exit()
515{
516}
517
518void osd_common_t::window_exit()
519{
520}
521
522void osd_common_t::sound_exit()
523{
524    if (m_sound != NULL)
525        global_free(m_sound);
526}
527
528void osd_common_t::input_exit()
529{
530}
531
532void osd_common_t::output_exit()
533{
534}
535
536void osd_common_t::network_exit()
537{
538}
539
540void osd_common_t::osd_exit()
541{
542   exit_subsystems();
543}
544
545void osd_common_t::video_options_add(const char *name, void *type)
546{
547   //m_video_options.add(name, type, false);
548   m_video_names.append(core_strdup(name));
549}
550
551void osd_common_t::sound_options_add(const char *name, osd_sound_type type)
552{
553   m_sound_options.add(name, type, false);
554   m_sound_names.append(core_strdup(name));
555}
556
557void osd_common_t::debugger_options_add(const char *name, osd_debugger_type type)
558{
559   m_debugger_options.add(name, type, false);
560   m_debugger_names.append(core_strdup(name));
561}
562
563bool osd_common_t::midi_init()
564{
565    // this should be done on the OS_level
566    return osd_midi_init();
567}
568
569void osd_common_t::midi_exit()
570{
571    osd_midi_exit();
572}
573
574//-------------------------------------------------
575//  osd_sound_interface - constructor
576//-------------------------------------------------
577
578osd_sound_interface::osd_sound_interface(const osd_interface &osd, running_machine &machine)
579    : m_osd(osd), m_machine(machine)
580{
581}
582
583//-------------------------------------------------
584//  osd_sound_interface - destructor
585//-------------------------------------------------
586
587osd_sound_interface::~osd_sound_interface()
588{
589}
590
591//-------------------------------------------------
592//  osd_debugger_interface - constructor
593//-------------------------------------------------
594
595osd_debugger_interface::osd_debugger_interface(const osd_interface &osd)
596    : m_osd(osd)
597{
598}
599
600//-------------------------------------------------
601//  osd_debugger_interface - destructor
602//-------------------------------------------------
603
604osd_debugger_interface::~osd_debugger_interface()
605{
606}
607
trunk/src/osd/modules/lib/osdobj_common.h
r242959r242960
1// license:BSD-3-Clause
2// copyright-holders:Aaron Giles
3/***************************************************************************
4
5    osdepend.h
6
7    OS-dependent code interface.
8
9*******************************************************************c********/
10
11#pragma once
12
13#ifndef __OSDOBJ_COMMON_H__
14#define __OSDOBJ_COMMON__
15
16#include "osdepend.h"
17#include "cliopts.h"
18
19//============================================================
20//  Defines
21//============================================================
22
23#define OSDCOMMAND_LIST_MIDI_DEVICES    "listmidi"
24#define OSDCOMMAND_LIST_NETWORK_ADAPTERS "listnetwork"
25
26#define OSDOPTION_DEBUGGER              "debugger"
27#define OSDOPTION_WATCHDOG              "watchdog"
28
29#define OSDOPTION_MULTITHREADING        "multithreading"
30#define OSDOPTION_NUMPROCESSORS         "numprocessors"
31#define OSDOPTION_BENCH                 "bench"
32
33#define OSDOPTION_VIDEO                 "video"
34#define OSDOPTION_NUMSCREENS            "numscreens"
35#define OSDOPTION_WINDOW                "window"
36#define OSDOPTION_MAXIMIZE              "maximize"
37#define OSDOPTION_KEEPASPECT            "keepaspect"
38#define OSDOPTION_UNEVENSTRETCH         "unevenstretch"
39#define OSDOPTION_WAITVSYNC             "waitvsync"
40#define OSDOPTION_SYNCREFRESH           "syncrefresh"
41
42#define OSDOPTION_SCREEN                "screen"
43#define OSDOPTION_ASPECT                "aspect"
44#define OSDOPTION_RESOLUTION            "resolution"
45#define OSDOPTION_VIEW                  "view"
46
47#define OSDOPTION_SWITCHRES             "switchres"
48
49#define OSDOPTION_SOUND                 "sound"
50#define OSDOPTION_AUDIO_LATENCY         "audio_latency"
51
52#define OSDOPTVAL_AUTO                  "auto"
53
54//============================================================
55//  TYPE DEFINITIONS
56//============================================================
57
58/* FIXME: core_options inherits from osd_options. This will force any
59 * future osd implementation to use the options below. Actually, these
60 * options are *private* to the osd_core. This object should actually be an
61 * accessor object. Later ...
62 */
63
64/* FIXME: core_options inherits from osd_options. This will force any
65 * future osd implementation to use the options below. Actually, these
66 * options are *private* to the osd_core. This object should actually be an
67 * accessor object. Later ...
68 */
69
70class osd_options : public cli_options
71{
72public:
73    // construction/destruction
74    osd_options();
75
76    // debugging options
77    const char *debugger() const { return value(OSDOPTION_DEBUGGER); }
78    int watchdog() const { return int_value(OSDOPTION_WATCHDOG); }
79
80    // performance options
81    bool multithreading() const { return bool_value(OSDOPTION_MULTITHREADING); }
82    const char *numprocessors() const { return value(OSDOPTION_NUMPROCESSORS); }
83    int bench() const { return int_value(OSDOPTION_BENCH); }
84
85    // video options
86    const char *video() const { return value(OSDOPTION_VIDEO); }
87    int numscreens() const { return int_value(OSDOPTION_NUMSCREENS); }
88    bool window() const { return bool_value(OSDOPTION_WINDOW); }
89    bool maximize() const { return bool_value(OSDOPTION_MAXIMIZE); }
90    bool keep_aspect() const { return bool_value(OSDOPTION_KEEPASPECT); }
91    bool uneven_stretch() const { return bool_value(OSDOPTION_UNEVENSTRETCH); }
92    bool wait_vsync() const { return bool_value(OSDOPTION_WAITVSYNC); }
93    bool sync_refresh() const { return bool_value(OSDOPTION_SYNCREFRESH); }
94
95    // per-window options
96    const char *screen() const { return value(OSDOPTION_SCREEN); }
97    const char *aspect() const { return value(OSDOPTION_ASPECT); }
98    const char *resolution() const { return value(OSDOPTION_RESOLUTION); }
99    const char *view() const { return value(OSDOPTION_VIEW); }
100    const char *screen(int index) const { astring temp; return value(temp.format("%s%d", OSDOPTION_SCREEN, index)); }
101    const char *aspect(int index) const { astring temp; return value(temp.format("%s%d", OSDOPTION_ASPECT, index)); }
102    const char *resolution(int index) const { astring temp; return value(temp.format("%s%d", OSDOPTION_RESOLUTION, index)); }
103    const char *view(int index) const { astring temp; return value(temp.format("%s%d", OSDOPTION_VIEW, index)); }
104
105    // full screen options
106    bool switch_res() const { return bool_value(OSDOPTION_SWITCHRES); }
107
108    // sound options
109    const char *sound() const { return value(OSDOPTION_SOUND); }
110    int audio_latency() const { return int_value(OSDOPTION_AUDIO_LATENCY); }
111
112private:
113    static const options_entry s_option_entries[];
114};
115
116class osd_sound_interface;
117class osd_debugger_interface;
118
119// a osd_sound_type is simply a pointer to its alloc function
120typedef osd_sound_interface *(*osd_sound_type)(const osd_interface &osd, running_machine &machine);
121
122// a osd_sound_type is simply a pointer to its alloc function
123typedef osd_debugger_interface *(*osd_debugger_type)(const osd_interface &osd);
124
125
126// ======================> osd_interface
127
128// description of the currently-running machine
129class osd_common_t : public osd_interface
130{
131public:
132   // construction/destruction
133   osd_common_t(osd_options &options);
134   virtual ~osd_common_t();
135
136   // FIXME: simply option handling
137   virtual void register_options();
138
139   // general overridables
140   virtual void init(running_machine &machine);
141   virtual void update(bool skip_redraw);
142
143   // debugger overridables
144   virtual void init_debugger();
145   virtual void wait_for_debugger(device_t &device, bool firststop);
146
147   // audio overridables
148   virtual void update_audio_stream(const INT16 *buffer, int samples_this_frame);
149   virtual void set_mastervolume(int attenuation);
150   virtual bool no_sound();
151
152   // input overridables
153   virtual void customize_input_type_list(simple_list<input_type_entry> &typelist);
154
155   // font overridables
156   virtual osd_font *font_open(const char *name, int &height);
157   virtual void font_close(osd_font *font);
158   virtual bool font_get_bitmap(osd_font *font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs);
159
160   // video overridables
161   virtual void *get_slider_list();
162
163    // command option overrides
164    virtual bool execute_command(const char *command);
165
166   // FIXME: everything below seems to be osd specific and not part of
167   //        this INTERFACE but part of the osd IMPLEMENTATION
168
169    // getters
170    running_machine &machine() { assert(m_machine != NULL); return *m_machine; }
171
172
173    virtual void debugger_update();
174    virtual void debugger_exit();
175    virtual void debugger_register();
176
177    virtual void init_subsystems();
178
179    virtual bool video_init();
180    virtual void video_register();
181    virtual bool window_init();
182
183    virtual bool sound_init();
184    virtual void sound_register();
185
186    virtual void input_resume();
187    virtual bool output_init();
188    virtual bool network_init();
189    virtual bool midi_init();
190
191    virtual void exit_subsystems();
192    virtual void video_exit();
193    virtual void window_exit();
194    virtual void sound_exit();
195    virtual void input_exit();
196    virtual void output_exit();
197    virtual void network_exit();
198    virtual void midi_exit();
199
200    virtual void osd_exit();
201
202    virtual void video_options_add(const char *name, void *type);
203    virtual void sound_options_add(const char *name, osd_sound_type type);
204    virtual void debugger_options_add(const char *name, osd_debugger_type type);
205
206    osd_options &options() { return m_options; }
207
208protected:
209    virtual bool input_init();
210    virtual void input_pause();
211
212private:
213   // internal state
214   running_machine *   m_machine;
215   osd_options& m_options;
216
217   void update_option(const char * key, dynamic_array<const char *> &values);
218
219protected:
220   osd_sound_interface* m_sound;
221   osd_debugger_interface* m_debugger;
222private:
223   //tagmap_t<osd_video_type>  m_video_options;
224   dynamic_array<const char *> m_video_names;
225   tagmap_t<osd_sound_type>  m_sound_options;
226   dynamic_array<const char *> m_sound_names;
227   tagmap_t<osd_debugger_type>  m_debugger_options;
228   dynamic_array<const char *> m_debugger_names;
229};
230
231
232class osd_sound_interface
233{
234public:
235   // construction/destruction
236   osd_sound_interface(const osd_interface &osd, running_machine &machine);
237   virtual ~osd_sound_interface();
238
239   virtual void update_audio_stream(const INT16 *buffer, int samples_this_frame) = 0;
240   virtual void set_mastervolume(int attenuation) = 0;
241protected:
242   const osd_interface& m_osd;
243   running_machine& m_machine;
244};
245
246// this template function creates a stub which constructs a sound subsystem
247template<class _DeviceClass>
248osd_sound_interface *osd_sound_creator(const osd_interface &osd, running_machine &machine)
249{
250   return global_alloc(_DeviceClass(osd, machine));
251}
252
253class osd_debugger_interface
254{
255public:
256   // construction/destruction
257   osd_debugger_interface(const osd_interface &osd);
258   virtual ~osd_debugger_interface();
259
260   virtual void init_debugger(running_machine &machine) = 0;
261   virtual void wait_for_debugger(device_t &device, bool firststop) = 0;
262   virtual void debugger_update() = 0;
263   virtual void debugger_exit() = 0;
264
265protected:
266   const osd_interface& m_osd;
267};
268
269// this template function creates a stub which constructs a debugger
270template<class _DeviceClass>
271osd_debugger_interface *osd_debugger_creator(const osd_interface &osd)
272{
273   return global_alloc(_DeviceClass(osd));
274}
275
276#endif  /* __OSDOBJ_COMMON_H__ */
trunk/src/osd/modules/sound/direct_sound.c
r242959r242960
7878//-------------------------------------------------
7979//  sound_direct_sound - constructor
8080//-------------------------------------------------
81sound_direct_sound::sound_direct_sound(const osd_interface &osd, running_machine &machine)
82   : osd_sound_interface(osd, machine)
81sound_direct_sound::sound_direct_sound(const osd_interface &osd)
82   : osd_sound_interface(osd)
8383{
8484   // attempt to initialize directsound
8585   // don't make it fatal if we can't -- we'll just run without sound
r242959r242960
268268   stream_format.wBitsPerSample    = 16;
269269   stream_format.wFormatTag        = WAVE_FORMAT_PCM;
270270   stream_format.nChannels         = 2;
271   stream_format.nSamplesPerSec    = m_machine.sample_rate();
271   stream_format.nSamplesPerSec    = m_osd.machine().sample_rate();
272272   stream_format.nBlockAlign       = stream_format.wBitsPerSample * stream_format.nChannels / 8;
273273   stream_format.nAvgBytesPerSec   = stream_format.nSamplesPerSec * stream_format.nBlockAlign;
274274
r242959r242960
276276   // compute the buffer size based on the output sample rate
277277   int audio_latency;
278278   #ifdef SDLMAME_WIN32
279   audio_latency = downcast<sdl_options &>(m_machine.options()).audio_latency();
279   audio_latency = downcast<sdl_options &>(m_osd.machine().options()).audio_latency();
280280   #else
281   audio_latency = downcast<windows_options &>(m_machine.options()).audio_latency();
281   audio_latency = downcast<windows_options &>(m_osd.machine().options()).audio_latency();
282282   #endif
283283   stream_buffer_size = stream_format.nSamplesPerSec * stream_format.nBlockAlign * audio_latency / 10;
284284   stream_buffer_size = (stream_buffer_size / 1024) * 1024;
trunk/src/osd/modules/sound/direct_sound.h
r242959r242960
2121#undef interface
2222
2323#include "osdepend.h"
24#include "modules/lib/osdobj_common.h"
2524
2625class sound_direct_sound : public osd_sound_interface
2726{
2827public:
2928   // construction/destruction
30   sound_direct_sound(const osd_interface &osd, running_machine &machine);
29   sound_direct_sound(const osd_interface &osd);
3130   virtual ~sound_direct_sound();
3231
3332   virtual void update_audio_stream(const INT16 *buffer, int samples_this_frame);
trunk/src/osd/modules/sound/none.c
r242959r242960
1414//-------------------------------------------------
1515//  sound_none - constructor
1616//-------------------------------------------------
17sound_none::sound_none(const osd_interface &osd, running_machine &machine)
18   : osd_sound_interface(osd, machine)
17sound_none::sound_none(const osd_interface &osd)
18   : osd_sound_interface(osd)
1919{
2020}
2121
trunk/src/osd/modules/sound/none.h
r242959r242960
1414#define __SOUND_NONE_H__
1515
1616#include "osdepend.h"
17#include "modules/lib/osdobj_common.h"
1817
1918class sound_none : public osd_sound_interface
2019{
2120public:
2221   // construction/destruction
23   sound_none(const osd_interface &osd, running_machine &machine);
22   sound_none(const osd_interface &osd);
2423   virtual ~sound_none() { }
2524
2625   virtual void update_audio_stream(const INT16 *buffer, int samples_this_frame) { }
trunk/src/osd/modules/sound/sdl_sound.c
r242959r242960
8080//-------------------------------------------------
8181//  sound_sdl - constructor
8282//-------------------------------------------------
83sound_sdl::sound_sdl(const osd_interface &osd, running_machine &machine)
84   : osd_sound_interface(osd, machine)
83sound_sdl::sound_sdl(const osd_interface &osd)
84   : osd_sound_interface(osd)
8585{
8686   if (LOG_SOUND)
8787      sound_log = fopen(SDLMAME_SOUND_LOG, "w");
8888
8989   // skip if sound disabled
90   if (m_machine.sample_rate() != 0)
90   if (osd.machine().sample_rate() != 0)
9191   {
9292      if (initialized_audio)
9393      {
r242959r242960
9595      }
9696
9797      // attempt to initialize SDL
98      if (sdl_init(m_machine))
98      if (sdl_init(osd.machine()))
9999         return;
100100
101101      // set the startup volume
r242959r242960
112112sound_sdl::~sound_sdl()
113113{
114114   // if nothing to do, don't do it
115   if (m_machine.sample_rate() == 0)
115   if (m_osd.machine().sample_rate() == 0)
116116      return;
117117
118118   // kill the buffers and dsound
119   sdl_kill(m_machine);
119   sdl_kill(m_osd.machine());
120120   sdl_destroy_buffers();
121121
122122   // print out over/underflow stats
r242959r242960
267267void sound_sdl::update_audio_stream(const INT16 *buffer, int samples_this_frame)
268268{
269269   // if nothing to do, don't do it
270   if (m_machine.sample_rate() != 0 && stream_buffer)
270   if (m_osd.machine().sample_rate() != 0 && stream_buffer)
271271   {
272272      int bytes_this_frame = samples_this_frame * sizeof(INT16) * 2;
273273      int play_position, write_position, stream_in;
r242959r242960
275275
276276      play_position = stream_playpos;
277277
278      write_position = stream_playpos + ((m_machine.sample_rate() / 50) * sizeof(INT16) * 2);
278      write_position = stream_playpos + ((m_osd.machine().sample_rate() / 50) * sizeof(INT16) * 2);
279279      orig_write = write_position;
280280
281281      if (!stream_in_initialized)
r242959r242960
336336
337337      // now we know where to copy; let's do it
338338      stream_buffer_in = stream_in;
339      copy_sample_data(m_machine, buffer, bytes_this_frame);
339      copy_sample_data(m_osd.machine(), buffer, bytes_this_frame);
340340   }
341341}
342342
trunk/src/osd/modules/sound/sdl_sound.h
r242959r242960
1414#define __SOUND_SDL_H__
1515
1616#include "osdepend.h"
17#include "modules/lib/osdobj_common.h"
1817
1918class sound_sdl : public osd_sound_interface
2019{
2120public:
2221   // construction/destruction
23   sound_sdl(const osd_interface &osd, running_machine &machine);
22   sound_sdl(const osd_interface &osd);
2423   virtual ~sound_sdl();
2524
2625   virtual void update_audio_stream(const INT16 *buffer, int samples_this_frame);
trunk/src/osd/osdcore.c
r242959r242960
5353
5454output_delegate osd_set_output_channel(output_channel channel, output_delegate callback)
5555{
56   if (!(channel < OSD_OUTPUT_CHANNEL_COUNT) || callback.isnull())
57    {
58       throw std::exception();
59    }
56   assert(channel < OSD_OUTPUT_CHANNEL_COUNT);
57   assert(!callback.isnull());
6058
6159   /* return the originals if requested */
6260   output_delegate prevcb = output_cb[channel];
trunk/src/osd/osdepend.c
r0r242960
1// license:BSD-3-Clause
2// copyright-holders:Aaron Giles
3/***************************************************************************
4
5    osdepend.c
6
7    OS-dependent code interface.
8
9*******************************************************************c********/
10
11
12#include "emu.h"
13#include "osdepend.h"
14#include "modules/sound/none.h"
15#include "modules/debugger/none.h"
16#include "modules/debugger/debugint.h"
17
18extern bool g_print_verbose;
19
20const options_entry osd_options::s_option_entries[] =
21{
22   // debugging options
23   { NULL,                                   NULL,       OPTION_HEADER,     "OSD DEBUGGING OPTIONS" },
24   { OSDOPTION_LOG,                          "0",        OPTION_BOOLEAN,    "generate an error.log file" },
25   { OSDOPTION_VERBOSE ";v",                 "0",        OPTION_BOOLEAN,    "display additional diagnostic information" },
26   { OSDOPTION_DEBUG ";d",                   "0",        OPTION_BOOLEAN,    "enable/disable debugger" },
27   { OSDOPTION_DEBUGGER,                     OSDOPTVAL_AUTO,      OPTION_STRING,    "debugger used : " },
28   { OSDOPTION_OSLOG,                        "0",        OPTION_BOOLEAN,    "output error.log data to the system debugger" },
29   { OSDOPTION_WATCHDOG ";wdog",             "0",        OPTION_INTEGER,    "force the program to terminate if no updates within specified number of seconds" },
30
31   // performance options
32   { NULL,                                   NULL,       OPTION_HEADER,     "OSD PERFORMANCE OPTIONS" },
33   { OSDOPTION_MULTITHREADING ";mt",         "0",        OPTION_BOOLEAN,    "enable multithreading; this enables rendering and blitting on a separate thread" },
34   { OSDOPTION_NUMPROCESSORS ";np",          OSDOPTVAL_AUTO,      OPTION_STRING,     "number of processors; this overrides the number the system reports" },
35   { OSDOPTION_BENCH,                        "0",        OPTION_INTEGER,    "benchmark for the given number of emulated seconds; implies -video none -sound none -nothrottle" },
36   // video options
37   { NULL,                                   NULL,       OPTION_HEADER,     "OSD VIDEO OPTIONS" },
38// OS X can be trusted to have working hardware OpenGL, so default to it on for the best user experience
39   { OSDOPTION_VIDEO,                        OSDOPTVAL_AUTO,     OPTION_STRING,     "video output method: " },
40   { OSDOPTION_NUMSCREENS "(1-4)",           "1",        OPTION_INTEGER,    "number of screens to create; usually, you want just one" },
41   { OSDOPTION_WINDOW ";w",                  "0",        OPTION_BOOLEAN,    "enable window mode; otherwise, full screen mode is assumed" },
42   { OSDOPTION_MAXIMIZE ";max",              "1",        OPTION_BOOLEAN,    "default to maximized windows; otherwise, windows will be minimized" },
43   { OSDOPTION_KEEPASPECT ";ka",             "1",        OPTION_BOOLEAN,    "constrain to the proper aspect ratio" },
44   { OSDOPTION_UNEVENSTRETCH ";ues",         "1",        OPTION_BOOLEAN,    "allow non-integer stretch factors" },
45   { OSDOPTION_WAITVSYNC ";vs",              "0",        OPTION_BOOLEAN,    "enable waiting for the start of VBLANK before flipping screens; reduces tearing effects" },
46   { OSDOPTION_SYNCREFRESH ";srf",           "0",        OPTION_BOOLEAN,    "enable using the start of VBLANK for throttling instead of the game time" },
47
48   // per-window options
49   { NULL,                                   NULL,             OPTION_HEADER,    "OSD PER-WINDOW VIDEO OPTIONS" },
50   { OSDOPTION_SCREEN,                   OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the first screen; 'auto' here will try to make a best guess" },
51   { OSDOPTION_ASPECT ";screen_aspect",  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio for all screens; 'auto' here will try to make a best guess" },
52   { OSDOPTION_RESOLUTION ";r",          OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution for all screens; format is <width>x<height>[@<refreshrate>] or 'auto'" },
53   { OSDOPTION_VIEW,                     OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for all screens" },
54
55   { OSDOPTION_SCREEN "0",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the first screen; 'auto' here will try to make a best guess" },
56   { OSDOPTION_ASPECT "0",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio of the first screen; 'auto' here will try to make a best guess" },
57   { OSDOPTION_RESOLUTION "0;r0",        OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution of the first screen; format is <width>x<height>[@<refreshrate>] or 'auto'" },
58   { OSDOPTION_VIEW "0",                    OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for the first screen" },
59
60   { OSDOPTION_SCREEN "1",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the second screen; 'auto' here will try to make a best guess" },
61   { OSDOPTION_ASPECT "1",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio of the second screen; 'auto' here will try to make a best guess" },
62   { OSDOPTION_RESOLUTION "1;r1",        OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution of the second screen; format is <width>x<height>[@<refreshrate>] or 'auto'" },
63   { OSDOPTION_VIEW "1",                    OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for the second screen" },
64
65   { OSDOPTION_SCREEN "2",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the third screen; 'auto' here will try to make a best guess" },
66   { OSDOPTION_ASPECT "2",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio of the third screen; 'auto' here will try to make a best guess" },
67   { OSDOPTION_RESOLUTION "2;r2",        OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution of the third screen; format is <width>x<height>[@<refreshrate>] or 'auto'" },
68   { OSDOPTION_VIEW "2",                    OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for the third screen" },
69
70   { OSDOPTION_SCREEN "3",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "explicit name of the fourth screen; 'auto' here will try to make a best guess" },
71   { OSDOPTION_ASPECT "3",                  OSDOPTVAL_AUTO,   OPTION_STRING,    "aspect ratio of the fourth screen; 'auto' here will try to make a best guess" },
72   { OSDOPTION_RESOLUTION "3;r3",        OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred resolution of the fourth screen; format is <width>x<height>[@<refreshrate>] or 'auto'" },
73   { OSDOPTION_VIEW "3",                    OSDOPTVAL_AUTO,   OPTION_STRING,    "preferred view for the fourth screen" },
74
75   // full screen options
76   { NULL,                                   NULL,  OPTION_HEADER,     "OSD FULL SCREEN OPTIONS" },
77   { OSDOPTION_SWITCHRES,                    "0",   OPTION_BOOLEAN,    "enable resolution switching" },
78
79   // sound options
80   { NULL,                                   NULL,  OPTION_HEADER,     "OSD SOUND OPTIONS" },
81   { OSDOPTION_SOUND,                        OSDOPTVAL_AUTO, OPTION_STRING,     "sound output method: " },
82   { OSDOPTION_AUDIO_LATENCY "(1-5)",        "2",   OPTION_INTEGER,    "set audio latency (increase to reduce glitches, decrease for responsiveness)" },
83
84   // End of list
85   { NULL }
86};
87
88//============================================================
89//  osd_options
90//============================================================
91
92osd_options::osd_options()
93{
94}
95
96
97void osd_options::add_osd_options()
98{
99   add_entries(s_option_entries);
100}
101
102//-------------------------------------------------
103//  osd_interface - constructor
104//-------------------------------------------------
105
106osd_interface::osd_interface()
107   : m_machine(NULL),
108      m_sound(NULL),
109      m_debugger(NULL)
110
111{
112}
113
114void osd_interface::update_option(osd_options &options, const char * key, dynamic_array<const char *> &values)
115{
116   astring current_value(options.description(key));
117   astring new_option_value("");
118   for (int index = 0; index < values.count(); index++)
119   {
120      astring t(values[index]);
121      if (new_option_value.len() > 0)
122      {
123         if( index != (values.count()-1))
124            new_option_value.cat(", ");
125         else
126            new_option_value.cat(" or ");
127      }
128      new_option_value.cat(t);
129   }
130   // TODO: core_strdup() is leaked
131   options.set_description(key, core_strdup(current_value.cat(new_option_value).cstr()));
132}
133
134void osd_interface::register_options(osd_options &options)
135{
136   // Register video options and update options
137   video_options_add("none", NULL);
138   video_register();
139   update_option(options, OSDOPTION_VIDEO, m_video_names);
140
141   // Register sound options and update options
142   sound_options_add("none", OSD_SOUND_NONE);
143   sound_register();
144   update_option(options, OSDOPTION_SOUND, m_sound_names);
145
146   // Register debugger options and update options
147   debugger_options_add("none", OSD_DEBUGGER_NONE);
148   debugger_options_add("internal", OSD_DEBUGGER_INTERNAL);
149   debugger_register();
150   update_option(options, OSDOPTION_DEBUGGER, m_debugger_names);
151}
152
153
154//-------------------------------------------------
155//  osd_interface - destructor
156//-------------------------------------------------
157
158osd_interface::~osd_interface()
159{
160   for(int i= 0; i < m_video_names.count(); ++i)
161      osd_free(const_cast<char*>(m_video_names[i]));
162   //m_video_options,reset();
163
164   for(int i= 0; i < m_sound_names.count(); ++i)
165      osd_free(const_cast<char*>(m_sound_names[i]));
166   m_sound_options.reset();
167
168   for(int i= 0; i < m_debugger_names.count(); ++i)
169      osd_free(const_cast<char*>(m_debugger_names[i]));
170   m_debugger_options.reset();
171}
172
173
174//-------------------------------------------------
175//  init - initialize the OSD system.
176//-------------------------------------------------
177
178void osd_interface::init(running_machine &machine)
179{
180   //
181   // This function is responsible for initializing the OSD-specific
182   // video and input functionality, and registering that functionality
183   // with the MAME core.
184   //
185   // In terms of video, this function is expected to create one or more
186   // render_targets that will be used by the MAME core to provide graphics
187   // data to the system. Although it is possible to do this later, the
188   // assumption in the MAME core is that the user interface will be
189   // visible starting at init() time, so you will have some work to
190   // do to avoid these assumptions.
191   //
192   // In terms of input, this function is expected to enumerate all input
193   // devices available and describe them to the MAME core by adding
194   // input devices and their attached items (buttons/axes) via the input
195   // system.
196   //
197   // Beyond these core responsibilities, init() should also initialize
198   // any other OSD systems that require information about the current
199   // running_machine.
200   //
201   // This callback is also the last opportunity to adjust the options
202   // before they are consumed by the rest of the core.
203   //
204   // Future work/changes:
205   //
206   // Audio initialization may eventually move into here as well,
207   // instead of relying on independent callbacks from each system.
208   //
209
210   m_machine = &machine;
211
212   osd_options &options = downcast<osd_options &>(machine.options());
213   // extract the verbose printing option
214   if (options.verbose())
215      g_print_verbose = true;
216
217   // ensure we get called on the way out
218   machine.add_notifier(MACHINE_NOTIFY_EXIT, machine_notify_delegate(FUNC(osd_interface::osd_exit), this));
219}
220
221
222//-------------------------------------------------
223//  update - periodic system update
224//-------------------------------------------------
225
226void osd_interface::update(bool skip_redraw)
227{
228   //
229   // This method is called periodically to flush video updates to the
230   // screen, and also to allow the OSD a chance to update other systems
231   // on a regular basis. In general this will be called at the frame
232   // rate of the system being run; however, it may be called at more
233   // irregular intervals in some circumstances (e.g., multi-screen games
234   // or games with asynchronous updates).
235   //
236}
237
238
239//-------------------------------------------------
240//  init_debugger - perform debugger-specific
241//  initialization
242//-------------------------------------------------
243
244void osd_interface::init_debugger()
245{
246   //
247   // Unlike init() above, this method is only called if the debugger
248   // is active. This gives any OSD debugger interface a chance to
249   // create all of its structures.
250   //
251   osd_debugger_type debugger = m_debugger_options.find(machine().options().debugger());
252   if (debugger==NULL)
253   {
254      osd_printf_warning("debugger_init: option %s not found switching to auto\n",machine().options().debugger());
255      debugger = m_debugger_options.find("auto");
256   }
257   m_debugger = (*debugger)(*this);
258
259   m_debugger->init_debugger();
260}
261
262
263//-------------------------------------------------
264//  wait_for_debugger - wait for a debugger
265//  command to be processed
266//-------------------------------------------------
267
268void osd_interface::wait_for_debugger(device_t &device, bool firststop)
269{
270   //
271   // When implementing an OSD-driver debugger, this method should be
272   // overridden to wait for input, process it, and return. It will be
273   // called repeatedly until a command is issued that resumes
274   // execution.
275   //
276   m_debugger->wait_for_debugger(device, firststop);
277}
278
279void osd_interface::debugger_update()
280{
281   if (m_debugger) m_debugger->debugger_update();
282}
283
284void osd_interface::debugger_exit()
285{
286   if (m_debugger)
287   {
288      m_debugger->debugger_exit();
289      global_free(m_debugger);
290      m_debugger = NULL;
291   }
292}
293
294//-------------------------------------------------
295//  update_audio_stream - update the stereo audio
296//  stream
297//-------------------------------------------------
298
299void osd_interface::update_audio_stream(const INT16 *buffer, int samples_this_frame)
300{
301   //
302   // This method is called whenever the system has new audio data to stream.
303   // It provides an array of stereo samples in L-R order which should be
304   // output at the configured sample_rate.
305   //
306   m_sound->update_audio_stream(buffer,samples_this_frame);
307}
308
309
310//-------------------------------------------------
311//  set_mastervolume - set the system volume
312//-------------------------------------------------
313
314void osd_interface::set_mastervolume(int attenuation)
315{
316   //
317   // Attenuation is the attenuation in dB (a negative number).
318   // To convert from dB to a linear volume scale do the following:
319   //    volume = MAX_VOLUME;
320   //    while (attenuation++ < 0)
321   //       volume /= 1.122018454;      //  = (10 ^ (1/20)) = 1dB
322   //
323   m_sound->set_mastervolume(attenuation);
324}
325
326
327//-------------------------------------------------
328//  customize_input_type_list - provide OSD
329//  additions/modifications to the input list
330//-------------------------------------------------
331
332void osd_interface::customize_input_type_list(simple_list<input_type_entry> &typelist)
333{
334   //
335   // inptport.c defines some general purpose defaults for key and joystick bindings.
336   // They may be further adjusted by the OS dependent code to better match the
337   // available keyboard, e.g. one could map pause to the Pause key instead of P, or
338   // snapshot to PrtScr instead of F12. Of course the user can further change the
339   // settings to anything he/she likes.
340   //
341   // This function is called on startup, before reading the configuration from disk.
342   // Scan the list, and change the keys/joysticks you want.
343   //
344}
345
346
347//-------------------------------------------------
348//  font_open - attempt to "open" a handle to the
349//  font with the given name
350//-------------------------------------------------
351
352osd_font osd_interface::font_open(const char *name, int &height)
353{
354   return NULL;
355}
356
357
358//-------------------------------------------------
359//  font_close - release resources associated with
360//  a given OSD font
361//-------------------------------------------------
362
363void osd_interface::font_close(osd_font font)
364{
365}
366
367
368//-------------------------------------------------
369//  font_get_bitmap - allocate and populate a
370//  BITMAP_FORMAT_ARGB32 bitmap containing the
371//  pixel values rgb_t(0xff,0xff,0xff,0xff)
372//  or rgb_t(0x00,0xff,0xff,0xff) for each
373//  pixel of a black & white font
374//-------------------------------------------------
375
376bool osd_interface::font_get_bitmap(osd_font font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs)
377{
378   return false;
379}
380
381//-------------------------------------------------
382//  get_slider_list - allocate and populate a
383//  list of OS-dependent slider values.
384//-------------------------------------------------
385void *osd_interface::get_slider_list()
386{
387   return NULL;
388}
389
390void osd_interface::init_subsystems()
391{
392   if (!video_init())
393   {
394      video_exit();
395      osd_printf_error("video_init: Initialization failed!\n\n\n");
396      fflush(stderr);
397      fflush(stdout);
398      exit(-1);
399   }
400
401   sound_init();
402   input_init();
403   // we need pause callbacks
404   machine().add_notifier(MACHINE_NOTIFY_PAUSE, machine_notify_delegate(FUNC(osd_interface::input_pause), this));
405   machine().add_notifier(MACHINE_NOTIFY_RESUME, machine_notify_delegate(FUNC(osd_interface::input_resume), this));
406
407   output_init();
408#ifdef USE_NETWORK
409   network_init();
410#endif
411   midi_init();
412}
413
414bool osd_interface::video_init()
415{
416   return true;
417}
418
419bool osd_interface::window_init()
420{
421   return true;
422}
423
424bool osd_interface::sound_init()
425{
426   osd_sound_type sound = m_sound_options.find(machine().options().sound());
427   if (sound==NULL)
428   {
429      osd_printf_warning("sound_init: option %s not found switching to auto\n",machine().options().sound());
430      sound = m_sound_options.find("auto");
431   }
432   m_sound = (*sound)(*this);
433   return true;
434}
435
436bool osd_interface::no_sound()
437{
438   return (strcmp(machine().options().sound(),"none")==0) ? true : false;
439}
440
441void osd_interface::video_register()
442{
443}
444
445void osd_interface::sound_register()
446{
447}
448
449void osd_interface::debugger_register()
450{
451}
452
453bool osd_interface::input_init()
454{
455   return true;
456}
457
458void osd_interface::input_pause()
459{
460}
461
462void osd_interface::input_resume()
463{
464}
465
466bool osd_interface::output_init()
467{
468   return true;
469}
470
471bool osd_interface::network_init()
472{
473   return true;
474}
475
476void osd_interface::exit_subsystems()
477{
478   video_exit();
479   sound_exit();
480   input_exit();
481   output_exit();
482   #ifdef USE_NETWORK
483   network_exit();
484   #endif
485   midi_exit();
486   debugger_exit();
487}
488
489void osd_interface::video_exit()
490{
491}
492
493void osd_interface::window_exit()
494{
495}
496
497void osd_interface::sound_exit()
498{
499   global_free(m_sound);
500}
501
502void osd_interface::input_exit()
503{
504}
505
506void osd_interface::output_exit()
507{
508}
509
510void osd_interface::network_exit()
511{
512}
513
514void osd_interface::osd_exit()
515{
516   exit_subsystems();
517}
518
519void osd_interface::video_options_add(const char *name, void *type)
520{
521   //m_video_options.add(name, type, false);
522   m_video_names.append(core_strdup(name));
523}
524
525void osd_interface::sound_options_add(const char *name, osd_sound_type type)
526{
527   m_sound_options.add(name, type, false);
528   m_sound_names.append(core_strdup(name));
529}
530
531void osd_interface::debugger_options_add(const char *name, osd_debugger_type type)
532{
533   m_debugger_options.add(name, type, false);
534   m_debugger_names.append(core_strdup(name));
535}
536//-------------------------------------------------
537//  osd_sound_interface - constructor
538//-------------------------------------------------
539
540osd_sound_interface::osd_sound_interface(const osd_interface &osd)
541   : m_osd(osd)
542{
543}
544
545//-------------------------------------------------
546//  osd_sound_interface - destructor
547//-------------------------------------------------
548
549osd_sound_interface::~osd_sound_interface()
550{
551}
552
553//-------------------------------------------------
554//  osd_debugger_interface - constructor
555//-------------------------------------------------
556
557osd_debugger_interface::osd_debugger_interface(const osd_interface &osd)
558   : m_osd(osd)
559{
560}
561
562//-------------------------------------------------
563//  osd_debugger_interface - destructor
564//-------------------------------------------------
565
566osd_debugger_interface::~osd_debugger_interface()
567{
568}
trunk/src/osd/osdepend.h
r242959r242960
1616#include "emucore.h"
1717#include "osdcore.h"
1818#include "unicode.h"
19#include "cliopts.h"
19#include "options.h"
2020
21// forward references
22class input_type_entry;     // FIXME: including emu.h does not work because emu.h includes osdepend.h
21//============================================================
22//  Defines
23//============================================================
2324
25#define OSDOPTION_LOG                   "log"
26#define OSDOPTION_VERBOSE               "verbose"
27#define OSDOPTION_DEBUG                 "debug"
28#define OSDOPTION_DEBUGGER              "debugger"
29#define OSDOPTION_OSLOG                 "oslog"
30#define OSDOPTION_WATCHDOG              "watchdog"
2431
32#define OSDOPTION_MULTITHREADING        "multithreading"
33#define OSDOPTION_NUMPROCESSORS         "numprocessors"
34#define OSDOPTION_BENCH                 "bench"
35
36#define OSDOPTION_VIDEO                 "video"
37#define OSDOPTION_NUMSCREENS            "numscreens"
38#define OSDOPTION_WINDOW                "window"
39#define OSDOPTION_MAXIMIZE              "maximize"
40#define OSDOPTION_KEEPASPECT            "keepaspect"
41#define OSDOPTION_UNEVENSTRETCH         "unevenstretch"
42#define OSDOPTION_WAITVSYNC             "waitvsync"
43#define OSDOPTION_SYNCREFRESH           "syncrefresh"
44
45#define OSDOPTION_SCREEN                "screen"
46#define OSDOPTION_ASPECT                "aspect"
47#define OSDOPTION_RESOLUTION            "resolution"
48#define OSDOPTION_VIEW                  "view"
49
50#define OSDOPTION_SWITCHRES             "switchres"
51
52#define OSDOPTION_SOUND                 "sound"
53#define OSDOPTION_AUDIO_LATENCY         "audio_latency"
54
55#define OSDOPTVAL_AUTO                  "auto"
56
2557//============================================================
2658//  TYPE DEFINITIONS
2759//============================================================
2860
29// FIXME: We can do better than this
30class osd_font;
61class osd_options : public core_options
62{
63public:
64   // construction/destruction
65   osd_options();
3166
67   // debugging options
68   bool verbose() const { return bool_value(OSDOPTION_VERBOSE); }
69   bool log() const { return bool_value(OSDOPTION_LOG); }
70   bool debug() const { return bool_value(OSDOPTION_DEBUG); }
71   const char *debugger() const { return value(OSDOPTION_DEBUGGER); }
72   bool oslog() const { return bool_value(OSDOPTION_OSLOG); }
73   int watchdog() const { return int_value(OSDOPTION_WATCHDOG); }
74
75   // performance options
76   bool multithreading() const { return bool_value(OSDOPTION_MULTITHREADING); }
77   const char *numprocessors() const { return value(OSDOPTION_NUMPROCESSORS); }
78   int bench() const { return int_value(OSDOPTION_BENCH); }
79
80   // video options
81   const char *video() const { return value(OSDOPTION_VIDEO); }
82   int numscreens() const { return int_value(OSDOPTION_NUMSCREENS); }
83   bool window() const { return bool_value(OSDOPTION_WINDOW); }
84   bool maximize() const { return bool_value(OSDOPTION_MAXIMIZE); }
85   bool keep_aspect() const { return bool_value(OSDOPTION_KEEPASPECT); }
86   bool uneven_stretch() const { return bool_value(OSDOPTION_UNEVENSTRETCH); }
87   bool wait_vsync() const { return bool_value(OSDOPTION_WAITVSYNC); }
88   bool sync_refresh() const { return bool_value(OSDOPTION_SYNCREFRESH); }
89
90   // per-window options
91   const char *screen() const { return value(OSDOPTION_SCREEN); }
92   const char *aspect() const { return value(OSDOPTION_ASPECT); }
93   const char *resolution() const { return value(OSDOPTION_RESOLUTION); }
94   const char *view() const { return value(OSDOPTION_VIEW); }
95   const char *screen(int index) const { astring temp; return value(temp.format("%s%d", OSDOPTION_SCREEN, index)); }
96   const char *aspect(int index) const { astring temp; return value(temp.format("%s%d", OSDOPTION_ASPECT, index)); }
97   const char *resolution(int index) const { astring temp; return value(temp.format("%s%d", OSDOPTION_RESOLUTION, index)); }
98   const char *view(int index) const { astring temp; return value(temp.format("%s%d", OSDOPTION_VIEW, index)); }
99
100   // full screen options
101   bool switch_res() const { return bool_value(OSDOPTION_SWITCHRES); }
102
103   // sound options
104   const char *sound() const { return value(OSDOPTION_SOUND); }
105   int audio_latency() const { return int_value(OSDOPTION_AUDIO_LATENCY); }
106
107   void add_osd_options();
108private:
109   static const options_entry s_option_entries[];
110};
111
112
113// forward references
114class input_type_entry;
115class device_t;
116class osd_interface;
117class osd_sound_interface;
118class osd_debugger_interface;
119
120typedef void *osd_font;
121
122// a osd_sound_type is simply a pointer to its alloc function
123typedef osd_sound_interface *(*osd_sound_type)(const osd_interface &osd);
124
125// a osd_sound_type is simply a pointer to its alloc function
126typedef osd_debugger_interface *(*osd_debugger_type)(const osd_interface &osd);
127
128
32129// ======================> osd_interface
33130
34131// description of the currently-running machine
35132class osd_interface
36133{
37134public:
135   // construction/destruction
136   osd_interface();
137   virtual ~osd_interface();
38138
139   void register_options(osd_options &options);
140
141   // getters
142   running_machine &machine() const { assert(m_machine != NULL); return *m_machine; }
143
39144   // general overridables
40   virtual void init(running_machine &machine) = 0;
41   virtual void update(bool skip_redraw) = 0;
145   virtual void init(running_machine &machine);
146   virtual void update(bool skip_redraw);
42147
43148   // debugger overridables
44   virtual void init_debugger() = 0;
45   virtual void wait_for_debugger(device_t &device, bool firststop) = 0;
149   void init_debugger();
150   void wait_for_debugger(device_t &device, bool firststop);
151   void debugger_update();
152   void debugger_exit();
153   virtual void debugger_register();
46154
47155   // audio overridables
48   virtual void update_audio_stream(const INT16 *buffer, int samples_this_frame) = 0;
49   virtual void set_mastervolume(int attenuation) = 0;
50   virtual bool no_sound() = 0;
156   void update_audio_stream(const INT16 *buffer, int samples_this_frame);
157   void set_mastervolume(int attenuation);
51158
52159   // input overridables
53   virtual void customize_input_type_list(simple_list<input_type_entry> &typelist) = 0;
160   virtual void customize_input_type_list(simple_list<input_type_entry> &typelist);
54161
55162   // font overridables
56   virtual osd_font *font_open(const char *name, int &height) = 0;
57   virtual void font_close(osd_font *font) = 0;
58   virtual bool font_get_bitmap(osd_font *font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs) = 0;
163   virtual osd_font font_open(const char *name, int &height);
164   virtual void font_close(osd_font font);
165   virtual bool font_get_bitmap(osd_font font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs);
59166
60167   // video overridables
61   virtual void *get_slider_list() = 0; // FIXME: returns slider_state *
168   virtual void *get_slider_list();
62169
63   // command option overrides
64   virtual bool execute_command(const char *command) = 0;
170   // midi overridables
171   // FIXME: this should return a list of devices, not list them on stdout
172   virtual void list_midi_devices(void);
65173
174   // FIXME: everything below seems to be osd specific and not part of
175   //        this INTERFACE but part of the osd IMPLEMENTATION
176
177   void init_subsystems();
178
179   virtual bool video_init();
180   virtual void video_register();
181   virtual bool window_init();
182
183   bool sound_init();
184   virtual void sound_register();
185   bool no_sound();
186
187   virtual bool input_init();
188   virtual void input_pause();
189   virtual void input_resume();
190   virtual bool output_init();
191   virtual bool network_init();
192   virtual bool midi_init();
193
194   void exit_subsystems();
195   virtual void video_exit();
196   virtual void window_exit();
197   void sound_exit();
198   virtual void input_exit();
199   virtual void output_exit();
200   virtual void network_exit();
201   virtual void midi_exit();
202
203   virtual void osd_exit();
204
205   void video_options_add(const char *name, void *type);
206   void sound_options_add(const char *name, osd_sound_type type);
207   void debugger_options_add(const char *name, osd_debugger_type type);
208
209private:
210   // internal state
211   running_machine *   m_machine;
212
213   void update_option(osd_options &options, const char * key, dynamic_array<const char *> &values);
214
215protected:
216   osd_sound_interface* m_sound;
217   osd_debugger_interface* m_debugger;
218private:
219   //tagmap_t<osd_video_type>  m_video_options;
220   dynamic_array<const char *> m_video_names;
221   tagmap_t<osd_sound_type>  m_sound_options;
222   dynamic_array<const char *> m_sound_names;
223   tagmap_t<osd_debugger_type>  m_debugger_options;
224   dynamic_array<const char *> m_debugger_names;
66225};
67226
227class osd_sound_interface
228{
229public:
230   // construction/destruction
231   osd_sound_interface(const osd_interface &osd);
232   virtual ~osd_sound_interface();
233
234   virtual void update_audio_stream(const INT16 *buffer, int samples_this_frame) = 0;
235   virtual void set_mastervolume(int attenuation) = 0;
236protected:
237   const osd_interface& m_osd;
238};
239
240// this template function creates a stub which constructs a sound subsystem
241template<class _DeviceClass>
242osd_sound_interface *osd_sound_creator(const osd_interface &osd)
243{
244   return global_alloc(_DeviceClass(osd));
245}
246
247class osd_debugger_interface
248{
249public:
250   // construction/destruction
251   osd_debugger_interface(const osd_interface &osd);
252   virtual ~osd_debugger_interface();
253
254   virtual void init_debugger() = 0;
255   virtual void wait_for_debugger(device_t &device, bool firststop) = 0;
256   virtual void debugger_update() = 0;
257   virtual void debugger_exit() = 0;
258
259protected:
260   const osd_interface& m_osd;
261};
262
263// this template function creates a stub which constructs a debugger
264template<class _DeviceClass>
265osd_debugger_interface *osd_debugger_creator(const osd_interface &osd)
266{
267   return global_alloc(_DeviceClass(osd));
268}
269
68270#endif  /* __OSDEPEND_H__ */
trunk/src/osd/osdmini/minimain.c
r242959r242960
5555
5656
5757//============================================================
58//  mini_osd_options
59//============================================================
60
61mini_osd_options::mini_osd_options()
62: osd_options()
63{
64   //add_entries(s_option_entries);
65}
66
67//============================================================
6858//  main
6959//============================================================
7060
r242959r242960
7262{
7363   // cli_frontend does the heavy lifting; if we have osd-specific options, we
7464   // create a derivative of cli_options and add our own
75   mini_osd_options options;
76   mini_osd_interface osd(options);
77   osd.register_options();
65   cli_options options;
66   mini_osd_interface osd;
67   osd.register_options(options);
7868   cli_frontend frontend(options, osd);
7969   return frontend.execute(argc, argv);
8070}
r242959r242960
8474//  constructor
8575//============================================================
8676
87mini_osd_interface::mini_osd_interface(mini_osd_options &options)
88: osd_common_t(options)
77mini_osd_interface::mini_osd_interface()
8978{
9079}
9180
r242959r242960
10695void mini_osd_interface::init(running_machine &machine)
10796{
10897   // call our parent
109   osd_common_t::init(machine);
98   osd_interface::init(machine);
11099
111100   // initialize the video system by allocating a rendering target
112101   our_target = machine.render().target_alloc();
trunk/src/osd/osdmini/osdmini.h
r242959r242960
88
99#include "options.h"
1010#include "osdepend.h"
11#include "modules/lib/osdobj_common.h"
1211
1312
14class mini_osd_options : public osd_options
15{
16public:
17   // construction/destruction
18   mini_osd_options();
19
20};
21
2213//============================================================
2314//  TYPE DEFINITIONS
2415//============================================================
2516
26class mini_osd_interface : public osd_common_t
17class mini_osd_interface : public osd_interface
2718{
2819public:
2920   // construction/destruction
30   mini_osd_interface(mini_osd_options &options);
21   mini_osd_interface();
3122   virtual ~mini_osd_interface();
3223
3324   // general overridables
trunk/src/osd/osdmini/osdmini.mak
r242959r242960
5050OSDSRC = $(SRC)/osd
5151OSDOBJ = $(OBJ)/osd
5252
53OBJDIRS += $(MINIOBJ) \
54   $(OSDOBJ)/modules/sync \
55   $(OSDOBJ)/modules/lib \
56   $(OSDOBJ)/modules/midi
53OBJDIRS += $(MINIOBJ) $(OSDOBJ)/modules/sync
5754
55
56
5857#-------------------------------------------------
5958# OSD core library
6059#-------------------------------------------------
r242959r242960
6564   $(MINIOBJ)/minimisc.o \
6665   $(MINIOBJ)/minisync.o \
6766   $(MINIOBJ)/minitime.o \
67   $(OSDOBJ)/modules/sync/work_mini.o \
6868
6969#-------------------------------------------------
7070# OSD mini library
7171#-------------------------------------------------
7272
7373OSDOBJS = \
74   $(MINIOBJ)/minimain.o \
75   $(OSDOBJ)/modules/sync/work_mini.o \
76   $(OSDOBJ)/modules/lib/osdobj_common.o  \
77   $(OSDOBJ)/modules/midi/none.o \
74   $(MINIOBJ)/minimain.o
7875
7976ifeq ($(OS),Windows_NT)
8077LIBS += -lwinmm -lwsock32
trunk/src/osd/sdl/draw13.c
r242959r242960
134134    const HashT hash() const { return m_hash; }
135135    const UINT32 flags() const { return m_flags; }
136136    const bool is_pixels_owned() const { // do we own / allocated it ?
137        return false && ((m_sdl_access == SDL_TEXTUREACCESS_STATIC)
138                && (m_copyinfo->func != NULL)) ;
137        return m_sdl_access == SDL_TEXTUREACCESS_STATIC
138                && m_copyinfo->func != NULL ;
139139    }
140140
141141private:
142    Uint32              m_sdl_access;
143142    SDL_Renderer *      m_renderer;
144143    render_texinfo      m_texinfo;            // copy of the texture info
145144    HashT               m_hash;               // hash value for the texture (must be >= pointer size)
r242959r242960
150149
151150    int                 m_format;             // texture format
152151    SDL_BlendMode       m_sdl_blendmode;
152    Uint32              m_sdl_access;
153153
154154    texture_info *      m_next;               // next texture in the list
155155};
r242959r242960
490490   }
491491}
492492
493// FIXME: machine only used to access options.
494493int drawsdl2_init(running_machine &machine, sdl_draw_info *callbacks)
495494{
496495   const char *stemp;
r242959r242960
10081007
10091008texture_info::~texture_info()
10101009{
1011    if ( is_pixels_owned() && (m_pixels != NULL) )
1012        free(m_pixels);
10131010    SDL_DestroyTexture(m_texture_id);
1011    if ( is_pixels_owned() && m_pixels != NULL )
1012        free(m_pixels);
10141013}
10151014
10161015//============================================================
trunk/src/osd/sdl/input.c
r242959r242960
14161416   }
14171417
14181418   // get Sixaxis special mode info
1419   sixaxis_mode = options().sixaxis();
1419   sixaxis_mode = downcast<sdl_options &>(machine().options()).sixaxis();
14201420
14211421   // register the joysticks
14221422   sdlinput_register_joysticks(machine());
r242959r242960
20862086      {
20872087         // configurable UI mode switch
20882088         case IPT_UI_TOGGLE_UI:
2089            uimode = options().ui_mode_key();
2089            uimode = downcast<sdl_options &>(machine().options()).ui_mode_key();
20902090            if(!strcmp(uimode,"auto"))
20912091            {
20922092               #if defined(__APPLE__) && defined(__MACH__)
trunk/src/osd/sdl/osdsdl.h
r242959r242960
55
66#include "watchdog.h"
77#include "clifront.h"
8#include "modules/lib/osdobj_common.h"
9#include "video.h"
108
119//============================================================
1210//  System dependent defines
r242959r242960
115113//  TYPE DEFINITIONS
116114//============================================================
117115
118class sdl_options : public osd_options
116typedef void *osd_font;
117
118//============================================================
119//  TYPE DEFINITIONS
120//============================================================
121
122class sdl_options : public cli_options
119123{
120124public:
121125   // construction/destruction
r242959r242960
172176};
173177
174178
175class sdl_osd_interface : public osd_common_t
179class sdl_osd_interface : public osd_interface
176180{
177181public:
178182   // construction/destruction
179   sdl_osd_interface(sdl_options &options);
183   sdl_osd_interface();
180184   virtual ~sdl_osd_interface();
181185
182186   // general overridables
r242959r242960
187191   virtual void customize_input_type_list(simple_list<input_type_entry> &typelist);
188192
189193   // font overridables
190   virtual osd_font *font_open(const char *name, int &height);
191   virtual void font_close(osd_font *font);
192   virtual bool font_get_bitmap(osd_font *font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs);
194   virtual osd_font font_open(const char *name, int &height);
195   virtual void font_close(osd_font font);
196   virtual bool font_get_bitmap(osd_font font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs);
193197
194198   virtual void video_register();
195199   virtual void sound_register();
r242959r242960
204208   #ifdef USE_NETWORK
205209   virtual bool network_init();
206210   #endif
207    //virtual bool midi_init();
208211
209212   virtual void video_exit();
210213   virtual void window_exit();
r242959r242960
213216   #ifdef USE_NETWORK
214217   virtual void network_exit();
215218   #endif
216    //virtual void midi_exit();
217219
218    sdl_options &options() { return m_options; }
219
220220private:
221221   virtual void osd_exit();
222222
223   void extract_window_config(int index, sdl_window_config *conf);
223   watchdog *m_watchdog;
224224
225   // FIXME: remove machine usage
226   void extract_video_config(running_machine &machine);
225};
227226
228227
229    sdl_options &m_options;
230228
231   watchdog *m_watchdog;
229//============================================================
230//  sound.c
231//============================================================
232232
233};
233void sdlaudio_init(running_machine &machine);
234234
235235//============================================================
236236//  sdlwork.c
trunk/src/osd/sdl/output.c
r242959r242960
8686      output = fdopen(fildes, "w");
8787
8888      osd_printf_verbose("output: opened output notifier file %s\n", SDLMAME_OUTPUT);
89      fprintf(output, "MAME " PID_FMT " START %s\n", osd_getpid(), this->machine().system().name);
89      fprintf(output, "MAME " PID_FMT " START %s\n", osd_getpid(), machine().system().name);
9090      fflush(output);
9191   }
9292
trunk/src/osd/sdl/sdl.mak
r242959r242960
432432   $(SDLOBJ)/window.o \
433433   $(SDLOBJ)/output.o \
434434   $(SDLOBJ)/watchdog.o \
435   $(OSDOBJ)/modules/lib/osdobj_common.o  \
436435
437436ifdef NO_USE_MIDI
438437   OSDOBJS += $(OSDOBJ)/modules/midi/none.o
trunk/src/osd/sdl/sdlmain.c
r242959r242960
255255//============================================================
256256
257257sdl_options::sdl_options()
258: osd_options()
259258{
260259   astring ini_path(INI_PATH);
261   add_entries(sdl_options::s_option_entries);
260   add_entries(s_option_entries);
262261   ini_path.replace(0, "APP_NAME", emulator_info::get_appname_lower());
263262   set_default_value(SDLOPTION_INIPATH, ini_path.cstr());
264263}
r242959r242960
334333#endif
335334
336335   {
337       sdl_options options;
338      sdl_osd_interface osd(options);
339      osd.register_options();
336      sdl_osd_interface osd;
337      sdl_options options;
338      osd.register_options(options);
340339      cli_frontend frontend(options, osd);
341340      res = frontend.execute(argc, argv);
342341   }
r242959r242960
381380//  constructor
382381//============================================================
383382
384sdl_osd_interface::sdl_osd_interface(sdl_options &options)
385: osd_common_t(options), m_options(options)
383sdl_osd_interface::sdl_osd_interface()
386384{
387385   m_watchdog = NULL;
388386}
r242959r242960
403401
404402void sdl_osd_interface::osd_exit()
405403{
406   osd_common_t::osd_exit();
404   osd_interface::osd_exit();
407405
408406   if (!SDLMAME_INIT_IN_WORKER_THREAD)
409407   {
r242959r242960
587585void sdl_osd_interface::init(running_machine &machine)
588586{
589587   // call our parent
590   osd_common_t::init(machine);
588   osd_interface::init(machine);
591589
590   sdl_options &options = downcast<sdl_options &>(machine.options());
592591   const char *stemp;
593592
594593   // determine if we are benchmarking, and adjust options appropriately
595   int bench = options().bench();
594   int bench = options.bench();
596595   astring error_string;
597596   if (bench > 0)
598597   {
599      options().set_value(OPTION_THROTTLE, false, OPTION_PRIORITY_MAXIMUM, error_string);
600      options().set_value(OSDOPTION_SOUND, "none", OPTION_PRIORITY_MAXIMUM, error_string);
601      options().set_value(OSDOPTION_VIDEO, "none", OPTION_PRIORITY_MAXIMUM, error_string);
602      options().set_value(OPTION_SECONDS_TO_RUN, bench, OPTION_PRIORITY_MAXIMUM, error_string);
598      options.set_value(OPTION_THROTTLE, false, OPTION_PRIORITY_MAXIMUM, error_string);
599      options.set_value(OSDOPTION_SOUND, "none", OPTION_PRIORITY_MAXIMUM, error_string);
600      options.set_value(OSDOPTION_VIDEO, "none", OPTION_PRIORITY_MAXIMUM, error_string);
601      options.set_value(OPTION_SECONDS_TO_RUN, bench, OPTION_PRIORITY_MAXIMUM, error_string);
603602      assert(!error_string);
604603   }
605604
606605   // Some driver options - must be before audio init!
607   stemp = options().audio_driver();
606   stemp = options.audio_driver();
608607   if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
609608   {
610609      osd_printf_verbose("Setting SDL audiodriver '%s' ...\n", stemp);
611610      osd_setenv(SDLENV_AUDIODRIVER, stemp, 1);
612611   }
613612
614   stemp = options().video_driver();
613   stemp = options.video_driver();
615614   if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
616615   {
617616      osd_printf_verbose("Setting SDL videodriver '%s' ...\n", stemp);
r242959r242960
619618   }
620619
621620#if (SDLMAME_SDL2)
622      stemp = options().render_driver();
621      stemp = options.render_driver();
623622      if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
624623      {
625624         osd_printf_verbose("Setting SDL renderdriver '%s' ...\n", stemp);
r242959r242960
634633#if USE_OPENGL
635634   /* FIXME: move lib loading code from drawogl.c here */
636635
637   stemp = options().gl_lib();
636   stemp = options.gl_lib();
638637   if (stemp != NULL && strcmp(stemp, SDLOPTVAL_AUTO) != 0)
639638   {
640639      osd_setenv("SDL_VIDEO_GL_DRIVER", stemp, 1);
r242959r242960
643642#endif
644643
645644   /* get number of processors */
646   stemp = options().numprocessors();
645   stemp = options.numprocessors();
647646
648647   osd_num_processors = 0;
649648
r242959r242960
682681         exit(-1);
683682      }
684683
685   osd_common_t::init_subsystems();
684   osd_interface::init_subsystems();
686685
687   if (options().oslog())
686   if (options.oslog())
688687      machine.add_logerror_callback(output_oslog);
689688
690689   /* now setup watchdog */
691690
692   int watchdog_timeout = options().watchdog();
691   int watchdog_timeout = options.watchdog();
693692
694693   if (watchdog_timeout != 0)
695694   {
r242959r242960
717716//  font with the given name
718717//-------------------------------------------------
719718
720class osd_font
719osd_font sdl_osd_interface::font_open(const char *_name, int &height)
721720{
722public:
723    CTFontRef m_font;
724};
725
726osd_font *sdl_osd_interface::font_open(const char *_name, int &height)
727{
728721   CFStringRef font_name = NULL;
729722   CTFontRef ct_font = NULL;
730723   CTFontDescriptorRef font_descriptor;
r242959r242960
776769   line_height += CTFontGetLeading(ct_font);
777770   height = ceilf(line_height * EXTRA_HEIGHT);
778771
779   osd_font *ret = global_alloc(osd_font);
780   ret->m_font = ct_font;
781   return ret;
772   return (osd_font)ct_font;
782773}
783774
784775//-------------------------------------------------
r242959r242960
786777//  a given OSD font
787778//-------------------------------------------------
788779
789void sdl_osd_interface::font_close(osd_font *font)
780void sdl_osd_interface::font_close(osd_font font)
790781{
791   CTFontRef ct_font = font->m_font;
782   CTFontRef ct_font = (CTFontRef)font;
792783
793784   if( ct_font != NULL )
794785   {
795786      CFRelease( ct_font );
796787   }
797   global_free(font);
798788}
799789
800790//-------------------------------------------------
r242959r242960
805795//  pixel of a black & white font
806796//-------------------------------------------------
807797
808bool sdl_osd_interface::font_get_bitmap(osd_font *font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs)
798bool sdl_osd_interface::font_get_bitmap(osd_font font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs)
809799{
810800   UniChar uni_char;
811801   CGGlyph glyph;
812   CTFontRef ct_font = font->m_font;
802   CTFontRef ct_font = (CTFontRef)font;
813803   const CFIndex count = 1;
814804   CGRect bounding_rect, success_rect;
815805   CGContextRef context_ref;
r242959r242960
10181008//  font with the given name
10191009//-------------------------------------------------
10201010
1021class osd_font
1011osd_font sdl_osd_interface::font_open(const char *_name, int &height)
10221012{
1023public:
1024    TTF_Font *m_font;
1025};
1026
1027osd_font *sdl_osd_interface::font_open(const char *_name, int &height)
1028{
10291013   TTF_Font *font = (TTF_Font *)NULL;
10301014   bool bakedstyles = false;
10311015   int style = 0;
r242959r242960
10511035   if (!font)
10521036   {
10531037      osd_printf_verbose("Searching font %s in -%s\n", name.cstr(), OPTION_FONTPATH);
1054      emu_file file(options().font_path(), OPEN_FLAG_READ);
1038      emu_file file(machine().options().font_path(), OPEN_FLAG_READ);
10551039      if (file.open(name) == FILERR_NONE)
10561040      {
10571041         astring full_name = file.fullpath();
r242959r242960
10961080
10971081   height = TTF_FontLineSkip(font);
10981082
1099   osd_font *ret = global_alloc(osd_font);
1100   ret->m_font = font;
1101   return ret;
1083   return (osd_font)font;
11021084}
11031085
11041086//-------------------------------------------------
r242959r242960
11061088//  a given OSD font
11071089//-------------------------------------------------
11081090
1109void sdl_osd_interface::font_close(osd_font *font)
1091void sdl_osd_interface::font_close(osd_font font)
11101092{
1111   TTF_CloseFont(font->m_font);
1112   global_free(font);
1093   TTF_Font *ttffont;
1094
1095   ttffont = (TTF_Font *)font;
1096
1097   TTF_CloseFont(ttffont);
11131098}
11141099
11151100//-------------------------------------------------
r242959r242960
11201105//  pixel of a black & white font
11211106//-------------------------------------------------
11221107
1123bool sdl_osd_interface::font_get_bitmap(osd_font *font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs)
1108bool sdl_osd_interface::font_get_bitmap(osd_font font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs)
11241109{
11251110   TTF_Font *ttffont;
11261111   SDL_Surface *drawsurf;
11271112   SDL_Color fcol = { 0xff, 0xff, 0xff };
11281113   UINT16 ustr[16];
11291114
1130   ttffont = font->m_font;
1115   ttffont = (TTF_Font *)font;
11311116
11321117   memset(ustr,0,sizeof(ustr));
11331118   ustr[0] = (UINT16)chnum;
r242959r242960
14541439#endif
14551440#endif
14561441
1442//-------------------------------------------------
1443// FIXME: Doesn't belong here but there's no better
1444//        place currently.
1445//-------------------------------------------------
14571446
1447bool osd_interface::midi_init()
1448{
1449    // this should be done on the OS_level
1450    return osd_midi_init();
1451}
1452
1453//-------------------------------------------------
1454//  list_midi_devices - list available midi devices
1455//-------------------------------------------------
1456
1457void osd_interface::list_midi_devices(void)
1458{
1459    osd_list_midi_devices();
1460}
1461
1462void osd_interface::midi_exit()
1463{
1464    osd_midi_exit();
1465}
trunk/src/osd/sdl/video.c
r242959r242960
8585
8686static void check_osd_inputs(running_machine &machine);
8787
88static void extract_video_config(running_machine &machine);
89static void extract_window_config(running_machine &machine, int index, sdl_window_config *conf);
8890static float get_aspect(const char *defdata, const char *data, int report_error);
8991static void get_resolution(const char *defdata, const char *data, sdl_window_config *config, int report_error);
9092
r242959r242960
104106   init_monitors();
105107
106108   // we need the beam width in a float, contrary to what the core does.
107   video_config.beamwidth = options().beam();
109   video_config.beamwidth = machine().options().beam();
108110
109111   // initialize the window system so we can make windows
110112   if (!window_init())
111113      return false;
112114
113115   // create the windows
116   sdl_options &options = downcast<sdl_options &>(machine().options());
114117   for (index = 0; index < video_config.numscreens; index++)
115118   {
116119      sdl_window_config conf;
117120      memset(&conf, 0, sizeof(conf));
118      extract_window_config(index, &conf);
119      if (sdlwindow_video_window_create(machine(), index, pick_monitor(options(), index), &conf))
121      extract_window_config(machine(), index, &conf);
122      if (sdlwindow_video_window_create(machine(), index, pick_monitor(options, index), &conf))
120123         return false;
121124   }
122125
r242959r242960
612615//  extract_window_config
613616//============================================================
614617
615void sdl_osd_interface::extract_window_config(int index, sdl_window_config *conf)
618static void extract_window_config(running_machine &machine, int index, sdl_window_config *conf)
616619{
620   sdl_options &options = downcast<sdl_options &>(machine.options());
617621   // per-window options: extract the data
618   get_resolution(options().resolution(), options().resolution(index), conf, TRUE);
622   get_resolution(options.resolution(), options.resolution(index), conf, TRUE);
619623}
620624
621625//============================================================
622626//  extract_video_config
623627//============================================================
624628
625void sdl_osd_interface::extract_video_config(running_machine &machine)
629static void extract_video_config(running_machine &machine)
626630{
627631   const char *stemp;
632   sdl_options &options = downcast<sdl_options &>(machine.options());
628633
629   video_config.perftest    = options().video_fps();
634   video_config.perftest    = options.video_fps();
630635
631636   // global options: extract the data
632   video_config.windowed      = options().window();
633   video_config.keepaspect    = options().keep_aspect();
634   video_config.numscreens    = options().numscreens();
635   video_config.fullstretch   = options().uneven_stretch();
637   video_config.windowed      = options.window();
638   video_config.keepaspect    = options.keep_aspect();
639   video_config.numscreens    = options.numscreens();
640   video_config.fullstretch   = options.uneven_stretch();
636641   #ifdef SDLMAME_X11
637   video_config.restrictonemonitor = !options().use_all_heads();
642   video_config.restrictonemonitor = !options.use_all_heads();
638643   #endif
639644
640645
r242959r242960
645650   video_config.novideo = 0;
646651
647652   // d3d options: extract the data
648   stemp = options().video();
653   stemp = options.video();
649654   if (strcmp(stemp, "auto") == 0)
650655   {
651656#ifdef SDLMAME_MACOSX
r242959r242960
661666      video_config.mode = VIDEO_MODE_SOFT;
662667      video_config.novideo = 1;
663668
664      if (options().seconds_to_run() == 0)
669      if (options.seconds_to_run() == 0)
665670         osd_printf_warning("Warning: -video none doesn't make much sense without -seconds_to_run\n");
666671   }
667672   else if (USE_OPENGL && (strcmp(stemp, SDLOPTVAL_OPENGL) == 0))
r242959r242960
676681      video_config.mode = VIDEO_MODE_SOFT;
677682   }
678683
679   video_config.switchres     = options().switch_res();
680   video_config.centerh       = options().centerh();
681   video_config.centerv       = options().centerv();
682   video_config.waitvsync     = options().wait_vsync();
683   video_config.syncrefresh   = options().sync_refresh();
684   video_config.switchres     = options.switch_res();
685   video_config.centerh       = options.centerh();
686   video_config.centerv       = options.centerv();
687   video_config.waitvsync     = options.wait_vsync();
688   video_config.syncrefresh   = options.sync_refresh();
684689   if (!video_config.waitvsync && video_config.syncrefresh)
685690   {
686691      osd_printf_warning("-syncrefresh specified without -waitsync. Reverting to -nosyncrefresh\n");
r242959r242960
688693   }
689694
690695   #if (USE_OPENGL || SDLMAME_SDL2)
691      video_config.filter        = options().filter();
696      video_config.filter        = options.filter();
692697   #endif
693698
694699   #if (USE_OPENGL)
695      video_config.prescale      = options().prescale();
700      video_config.prescale      = options.prescale();
696701      if (video_config.prescale < 1 || video_config.prescale > 3)
697702      {
698703         osd_printf_warning("Invalid prescale option, reverting to '1'\n");
699704         video_config.prescale = 1;
700705      }
701706      // default to working video please
702      video_config.forcepow2texture = options().gl_force_pow2_texture();
703      video_config.allowtexturerect = !(options().gl_no_texture_rect());
704      video_config.vbo         = options().gl_vbo();
705      video_config.pbo         = options().gl_pbo();
706      video_config.glsl        = options().gl_glsl();
707      video_config.forcepow2texture = options.gl_force_pow2_texture();
708      video_config.allowtexturerect = !(options.gl_no_texture_rect());
709      video_config.vbo         = options.gl_vbo();
710      video_config.pbo         = options.gl_pbo();
711      video_config.glsl        = options.gl_glsl();
707712      if ( video_config.glsl )
708713      {
709714         int i;
710715
711         video_config.glsl_filter = options().glsl_filter();
716         video_config.glsl_filter = options.glsl_filter();
712717
713718         video_config.glsl_shader_mamebm_num=0;
714719
715720         for(i=0; i<GLSL_SHADER_MAX; i++)
716721         {
717            stemp = options().shader_mame(i);
722            stemp = options.shader_mame(i);
718723            if (stemp && strcmp(stemp, SDLOPTVAL_NONE) != 0 && strlen(stemp)>0)
719724            {
720725               video_config.glsl_shader_mamebm[i] = (char *) malloc(strlen(stemp)+1);
r242959r242960
729734
730735         for(i=0; i<GLSL_SHADER_MAX; i++)
731736         {
732            stemp = options().shader_screen(i);
737            stemp = options.shader_screen(i);
733738            if (stemp && strcmp(stemp, SDLOPTVAL_NONE) != 0 && strlen(stemp)>0)
734739            {
735740               video_config.glsl_shader_scrn[i] = (char *) malloc(strlen(stemp)+1);
r242959r242960
772777   }
773778#endif
774779   // yuv settings ...
775   stemp = options().scale_mode();
780   stemp = options.scale_mode();
776781   video_config.scale_mode = drawsdl_scale_mode(stemp);
777782   if (video_config.scale_mode < 0)
778783   {
trunk/src/osd/sdl/window.c
r242959r242960
222222{
223223   osd_printf_verbose("Enter sdlwindow_init\n");
224224   // determine if we are using multithreading or not
225   multithreading_enabled = options().multithreading();
225   multithreading_enabled = downcast<sdl_options &>(machine().options()).multithreading();
226226
227227   // get the main thread ID before anything else
228228   main_threadid = SDL_ThreadID();
trunk/src/osd/windows/windows.mak
r242959r242960
378378   $(WINOBJ)/winmenu.o \
379379   $(WINOBJ)/winmain.o \
380380   $(OSDOBJ)/modules/midi/portmidi.o \
381   $(OSDOBJ)/modules/lib/osdobj_common.o  \
382381
383382ifdef USE_SDL
384383OSDOBJS += \
trunk/src/osd/windows/winmain.c
r242959r242960
421421   DWORD result = 0;
422422   {
423423      windows_options options;
424      windows_osd_interface osd(options);
425      osd.register_options();
424      windows_osd_interface osd;
425      osd.register_options(options);
426426      cli_frontend frontend(options, osd);
427427      result = frontend.execute(argc, argv);
428428   }
r242959r242960
437437//============================================================
438438
439439windows_options::windows_options()
440: osd_options()
441440{
442441   add_entries(s_option_entries);
443442}
r242959r242960
513512//  constructor
514513//============================================================
515514
516windows_osd_interface::windows_osd_interface(windows_options &options)
517: osd_common_t(options)
515windows_osd_interface::windows_osd_interface()
518516{
519517}
520518
r242959r242960
574572void windows_osd_interface::init(running_machine &machine)
575573{
576574   // call our parent
577   osd_common_t::init(machine);
575   osd_interface::init(machine);
578576
579577   const char *stemp;
580578   windows_options &options = downcast<windows_options &>(machine.options());
r242959r242960
621619   }
622620
623621   // initialize the subsystems
624   osd_common_t::init_subsystems();
622   osd_interface::init_subsystems();
625623
626624   // notify listeners of screen configuration
627625   astring tempstring;
r242959r242960
682680   // cleanup sockets
683681   win_cleanup_sockets();
684682
685   osd_common_t::osd_exit();
683   osd_interface::osd_exit();
686684
687685   // take down the watchdog thread if it exists
688686   if (watchdog_thread != NULL)
r242959r242960
719717//  font with the given name
720718//-------------------------------------------------
721719
722osd_font *windows_osd_interface::font_open(const char *_name, int &height)
720osd_font windows_osd_interface::font_open(const char *_name, int &height)
723721{
724722   // accept qualifiers from the name
725723   astring name(_name);
r242959r242960
751749
752750   // create the font
753751   height = logfont.lfHeight;
754   osd_font *font = reinterpret_cast<osd_font *>(CreateFontIndirect(&logfont));
752   osd_font font = reinterpret_cast<osd_font>(CreateFontIndirect(&logfont));
755753   if (font == NULL)
756754      return NULL;
757755
r242959r242960
783781//  a given OSD font
784782//-------------------------------------------------
785783
786void windows_osd_interface::font_close(osd_font *font)
784void windows_osd_interface::font_close(osd_font font)
787785{
788786   // delete the font ojbect
789787   if (font != NULL)
r242959r242960
799797//  pixel of a black & white font
800798//-------------------------------------------------
801799
802bool windows_osd_interface::font_get_bitmap(osd_font *font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs)
800bool windows_osd_interface::font_get_bitmap(osd_font font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs)
803801{
804802   // create a dummy DC to work with
805803   HDC dummyDC = CreateCompatibleDC(NULL);
r242959r242960
18261824      Sleep(1);
18271825   }
18281826}
1827
1828//-------------------------------------------------
1829// FIXME: Doesn't belong here but there's no better
1830//        place currently.
1831//-------------------------------------------------
1832
1833bool osd_interface::midi_init()
1834{
1835    // this should be done on the OS_level
1836    return osd_midi_init();
1837}
1838
1839//-------------------------------------------------
1840//  list_midi_devices - list available midi devices
1841//-------------------------------------------------
1842
1843void osd_interface::list_midi_devices(void)
1844{
1845    osd_list_midi_devices();
1846}
1847
1848void osd_interface::midi_exit()
1849{
1850    osd_midi_exit();
1851}
trunk/src/osd/windows/winmain.h
r242959r242960
88
99#include "clifront.h"
1010#include "osdepend.h"
11#include "modules/lib/osdobj_common.h"
1211
1312
1413//============================================================
r242959r242960
114113//  TYPE DEFINITIONS
115114//============================================================
116115
117class windows_options : public osd_options
116class windows_options : public cli_options
118117{
119118public:
120119   // construction/destruction
r242959r242960
235234//  TYPE DEFINITIONS
236235//============================================================
237236
238class windows_osd_interface : public osd_common_t
237class windows_osd_interface : public osd_interface
239238{
240239public:
241240   // construction/destruction
242   windows_osd_interface(windows_options &options);
241   windows_osd_interface();
243242   virtual ~windows_osd_interface();
244243
245244   // general overridables
r242959r242960
253252   virtual void customize_input_type_list(simple_list<input_type_entry> &typelist);
254253
255254   // font overridables
256   virtual osd_font *font_open(const char *name, int &height);
257   virtual void font_close(osd_font *font);
258   virtual bool font_get_bitmap(osd_font *font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs);
255   virtual osd_font font_open(const char *name, int &height);
256   virtual void font_close(osd_font font);
257   virtual bool font_get_bitmap(osd_font font, unicode_char chnum, bitmap_argb32 &bitmap, INT32 &width, INT32 &xoffs, INT32 &yoffs);
259258
260259   virtual void video_register();
261260   virtual void sound_register();
trunk/src/osd/windows/winprefix.h
r242959r242960
66//
77//============================================================
88
9#ifndef _WIN32_WINNT
10#define _WIN32_WINNT 0x0501 // Windows XP
11#endif
9#define _WIN32_WINNT 0x0501
1210
1311#ifdef _MSC_VER
1412#include <assert.h>
trunk/src/tools/chdman.c
r242959r242960
8787#define OPTION_VERBOSE "verbose"
8888#define OPTION_FIX "fix"
8989#define OPTION_NUMPROCESSORS "numprocessors"
90#define OPTION_SIZE "size"
9190
9291
9392//**************************************************************************
r242959r242960
529528   { OPTION_NO_CHECKSUM,           "nocs", false, ": do not include this metadata information in the overall SHA-1" },
530529   { OPTION_FIX,                   "f",    false, ": fix the SHA-1 if it is incorrect" },
531530   { OPTION_VERBOSE,               "v",    false, ": output additional information" },
532   { OPTION_SIZE,                  "s",    true, ": <bytes>: size of the output file" },
533531};
534532
535533
r242959r242960
581579         OPTION_COMPRESSION,
582580         OPTION_IDENT,
583581         OPTION_CHS,
584         OPTION_SIZE,
585582         OPTION_SECTOR_SIZE,
586583         OPTION_NUMPROCESSORS
587584      }
r242959r242960
904901   if (filesize == 0)
905902      report_error(1, "Can't guess CHS values because there is no input file");
906903
904   // validate the size
905   if (filesize % sectorsize != 0)
906      report_error(1, "Can't guess CHS values because data size is not divisible by %d", sectorsize);
907   ;
908
907909   // now find a valid value
908910   for (UINT32 totalsectors = filesize / sectorsize; ; totalsectors++)
909911      for (UINT32 cursectors = 63; cursectors > 1; cursectors--)
r242959r242960
16851687   parse_hunk_size(params, sector_size, hunk_size);
16861688
16871689   // process input start/end (needs to know hunk_size)
1688   UINT64 filesize = 0;
16891690   UINT64 input_start = 0;
16901691   UINT64 input_end = 0;
16911692   if (input_file != NULL)
1692   {
16931693      parse_input_start_end(params, core_fsize(input_file), hunk_size, hunk_size, input_start, input_end);
1694      filesize = input_end - input_start;
1695   }
1696   else
1697   {
1698      astring *size_str = params.find(OPTION_SIZE);
1699      if (size_str != NULL)
1700      {
1701         if (sscanf(*size_str, "%"I64FMT"d", &filesize) != 1)
1702            report_error(1, "Invalid size string");
1703      }
1704   }
1705   
1694
17061695   // process compression
17071696   chd_codec_type compression[4];
17081697   memcpy(compression, s_default_hd_compression, sizeof(compression));
r242959r242960
17571746      if (sscanf(metadata, HARD_DISK_METADATA_FORMAT, &cylinders, &heads, &sectors, &sector_size) != 4)
17581747         report_error(1, "Error parsing hard disk metadata in parent CHD");
17591748   }
1760     
1761   // validate the size
1762   if (filesize % sector_size != 0)
1763      report_error(1, "Data size is not divisible by sector size %d", sector_size);
17641749
17651750   // if no CHS values, try to guess them
17661751   if (cylinders == 0)
17671752   {
1768      if (input_file == NULL && filesize == 0)
1753      if (input_file == NULL && input_end - input_start == 0)
17691754         report_error(1, "Blank hard drives must specify either a length or a set of CHS values");
1770      guess_chs(input_file_str, filesize, sector_size, cylinders, heads, sectors, sector_size);
1755      guess_chs(input_file_str, input_end - input_start, sector_size, cylinders, heads, sectors, sector_size);
17711756   }
17721757   UINT32 totalsectors = cylinders * heads * sectors;
17731758
r242959r242960
17821767      if (input_start != 0 || input_end != core_fsize(input_file))
17831768      {
17841769         printf("Input start:  %s\n", big_int_string(tempstr, input_start));
1785         printf("Input length: %s\n", big_int_string(tempstr, filesize));
1770         printf("Input length: %s\n", big_int_string(tempstr, input_end - input_start));
17861771      }
17871772   }
17881773   printf("Compression:  %s\n", compression_string(tempstr, compression));
r242959r242960
29232908            (*s_commands[cmdnum].handler)(parameters);
29242909            return 0;
29252910         }
2926         catch (chd_error &err)
2927         {
2928            fprintf(stderr, "CHD error occured (main): %s\n", chd_file::error_string(err));
2929            return 1;
2930         }
29312911         catch (fatal_error &err)
29322912         {
2933            fprintf(stderr, "Fatal error occured: %d\n", err.error());
29342913            return err.error();
29352914         }
29362915         catch (std::exception& ex)


Previous 199869 Revisions Next


© 1997-2024 The MAME Team