This page documents various lua functions in lsnes.
Unless otherwise noted, functions are in rr1 version and work anywhere.
Table of contents

Bit manipulation functions

(Generic remarks)

Bit manipulation functions work on 48-bit numbers and return 48-bit results. Negative numbers are interpreted as two's complement.

bit.none / bit.bnot

Syntax: Number bit.none(Number n...)
Syntax: Number bit.bnot(Number n...)
Returns number that has bit i set exactly when none of the arguments has the bit i set.
When called with one argument, this is the same as the bitwise NOT.

bit.any / bit.bor

Syntax: Number bit.any(Number n...)
Syntax: Number bit.bor(Number n...)
Returns number that has bit i set exactly when any of the arguments has the bit i set.
If called with two arguments, this is the same as bitwise OR.

bit.all / bit.band

Syntax: Number bit.all(Number n...)
Syntax: Number bit.band(Number n...)
Returns number that has bit i set exactly when all of the arguments have the bit i set.
If called with two arguments, this is the same as bitwise AND.

bit.parity

Syntax: Number bit.parity(Number n...)
Syntax: Number bit.bxor(Number n...)
Returns number that has bit i set exactly when odd number of the arguments has the bit i set.
If called with two arguments, this is the same as bitwise XOR.

bit.lrotate

Syntax: Number bit.lrotate(Number base, [Number nplaces], [Number nbits])
Returns base, assumed to be nbits bits, rotated left by nplaces places.
Behavior is undefined if nbits is greater than 48 or if nplaces is greater than 47.

bit.rrotate

Syntax: Number bit.rrotate(Number base, [Number nplaces], [Number nbits])
Returns base, assumed to be nbits bits, rotated right by nplaces places.
Behavior is undefined if nbits is greater than 48 or if nplaces is greater than 47.

bit.lshift

Syntax: Number bit.lshift(Number base, [Number nplaces], [Number nbits])
Returns base, assumed to be nbits bits, shifted left by nplaces places.
The bits that leave nbits least significant bits are discarded. The shifted in bits are zeroes.
Behavior is undefined if nbits is greater than 48 or if nplaces is greater than 47.

bit.lrshift

Syntax: Number bit.lrshift(Number base, [Number nplaces], [Number nbits])
Returns base, assumed to be nbits bits, shifted logically right by nplaces places.
The bits that drop off the right end are discarded. The shifted in bits are zeroes.
Behavior is undefined if nbits is greater than 48 or if nplaces is greater than 47.

bit.arshift

Syntax: Number bit.arshift(Number base, [Number nplaces], [Number nbits])
Returns base, assumed to be nbits bits, shifted arithmetically right by nplaces places.
The bits that drop off the right end are discarded. The shifted in bits are copies of the most significant bit.
Behavior is undefined if nbits is greater than 48 or if nplaces is greater than 47.

bit.extract

Syntax: Number bit.extract(Number base, Number/Boolean place...)
Returns a number where ith bit is taken from the ith placeth bit of base.
As special case, if ith place is boolean, the ith returned bit is that value (1 if argument was true, 0 if false).

bit.value

Syntax: Number bit.value(Number/nil place...)
Returns number that has all placeth bits set.
As special case, any nil arguments are ignored.

bit.test_any

Syntax: Boolean bit.test_any(Number a, Number b)
Returns true if a and b have common set bit or bits.

bit.test_all

Syntax: Boolean bit.test_all(Number a, Number b)
Returns true if a has all the bits set in b set.

bit.popcount

Syntax: Number bit.popcount(Number a)
Returns population count (number of set bits) of a.

bit.clshift

Syntax: Number,Number bit.clshift(Number a, Number b, [Number places], [Number bits])
Chained shift of a and b left by specified number of places (default 1). The numbers are treated as having specified number of bits (default 48).

bit.crshift

Syntax: Number,Number bit.crshift(Number a, Number b, [Number places], [Number bits])
Chained shift of a and b right by specified number of places (default 1). The numbers are treated as having specified number of bits (default 48).

bit.flagdecode

Syntax: String bit.flagdecode(Number a, Number bits, [String set], [String clear])
Returns string where ith character is ith character (only character or '*') of set if corresponding bit is set, otherwise corresponding character of clear.

bit.rflagdecode

Syntax: String bit.rflagdecode(Number a, Number bits, [String set], [String clear])
Same as bit.flagdecode, but reverses the output string.

GUI functions

(Color notation)

(Coordinate system)

(Draw order)

(Valid in)

gui.screenshot

Syntax: none gui.screenshot(string filename)
Take a screenshot in PNG format and save it to filename

gui.circle

Syntax: none gui.circle(Number x, Number y, Number r, [Number thickness], [Number outline_color], [Number fill_color])
Draws a circle centered at (x,y) with radius r.
The outline is of thickness thickness and is drawn using color specified by outline_color
The interior region is filled with color fill_color.

gui.resolution

Syntax (number width, number height) gui.resolution()
Returns the width (width) and height (height) of game area.

gui.left_gap / gui.top_gap / gui.right_gap / gui.bottom_gap

Syntax none gui.left_gap(number pixels)
Syntax none gui.top_gap(number pixels)
Syntax none gui.right_gap(number pixels)
Syntax none gui.bottom_gap(number pixels)
Sets the width of drawable blank area to the left/top/right/bottom of the game area to pixels.

gui.repaint

Syntax: none gui.repaint()
Arranges on_paint hook to be called as soon as possible.

gui.subframe_update

Syntax: none gui.subframe_update(boolean enabled)
Enables (enabled=true)/Disables (enabled=false) calling of on_paint on every subframe (as opposed to just when new frame is available).

gui.color

Syntax: Number gui.color(Number r, Number g, Number b, [Number a])
Returns the color code for color (r,g,b) (0-255 each channel) with alpha of a (0-256).

gui.status

Syntax: none gui.status(String name, String value)
Set status name to value value.
If value is "", the status name is erased.

gui.crosshair

Syntax: none gui.crosshair(Number x, Number y, Number size, [Number color])
Draws a crosshair of size size at (x,y) using color color.

gui.line

Syntax: none gui.color(Number x1, Number y1, Number x2, Number y2, [Number color])
Draws a line from (x1,y1) to (x2,y2) using color color.

gui.pixel

Syntax: none gui.pixel(Number x, Number y, [Number color])
Draws pixel at (x,y) using color color.
Be careful with this function. Even if it is the lightest of all draw functions, lots of draw functions don't do any good to performance.

gui.rectangle

Syntax: none gui.rectangle(Number x, Number y, Number w, Number h, [Number thickness], [Number outline_color], [Number fill_color])
Draws rectangle of size (w,h) with top-left corner at (x,y). Outline is of thickness thickness and is colored with color outline_color.
The interior is filled with color fill_color.

gui.box

Syntax: none gui.box(Number x, Number y, Number w, Number h, [Number thickness], [Number hilight_color], [Number shadow_color], [Number fill_color])
Draws rectangle of size (w,h) with top-left corner at (x,y).
The outline is of thickness thickness and is colored with hilight_color/shadow_color to create a 3D effect.
The interior is filled with fill_color.

gui.text / gui.textH / gui.textV / gui.textHV

Syntax: none gui.text(Number x, Number y, String text, [Number fgcolor], [Number bgcolor])
Syntax: none gui.textH(Number x, Number y, String text, [Number fgcolor], [Number bgcolor])
Syntax: none gui.textV(Number x, Number y, String text, [Number fgcolor], [Number bgcolor])
Syntax: none gui.textHV(Number x, Number y, String text, [Number fgcolor], [Number bgcolor])
Draws text string text starting from (x, y).
The text will be colored using color fgcolor and the text background is colored using bgcolor.
The H variants will draw the text using double width, and the V variants will draw the text using double height.

gui.bitmap_draw

Syntax: none gui.bitmap_draw(Number x, Number y, BITMAP bmp, PALETTE pal)
Syntax: none gui.bitmap_draw(Number x, Number y, DBITMAP bmp)
Render bitmap bmp with upper-left corner at (x,y).
If the bitmap is indexed, it will be rendered using palette pal.

gui.palette_new

Syntax: PALETTE gui.palette_new()
Returns a new PALETTE object. All colors are initialized to transparent.

gui.palette_set

Syntax: none gui.palette_set(PALETTE pal, number idx, number color)
Sets the color index idx in palette pal to color color.

gui.bitmap_new

Syntax: BITMAP gui.bitmap_new(number width, number height, false)
Syntax: DBITMAP gui.bitmap_new(number width, number height, true)
Returns a new bitmap of size width by height.
The third argument determines if the bitmap is indexed (false) or not (true).

gui.bitmap_pset

Syntax: none gui.bitmap_pset(BITMAP/DBITMAP bmp, number x, number y, number c)
Sets the pixel at (x,y) in bitmap bmp to color c.
The c is color index for indexed bitmaps and color for non-indexed ones.

gui.bitmap_size

Syntax: (Number w, Number h) gui.bitmap_size(BITMAP/DBITMAP bmp)
Returns the width (w) and height (h) of bitmap bmp.

gui.bitmap_blit

Syntax: none gui.bitmap_blit(BITMAP target, number dx, number dy, BITMAP source, number sx, number sy, number w, number h, [number colorkey])
Syntax: none gui.bitmap_blit(DBITMAP target, number dx, number dy, DBITMAP source, number sx, number sy, number w, number h, [number colorkey])
Blits region of size w by h starting from (sx,sy) from source to region starting from (dx,dy) in target.
If colorkey is specified, the pixels with that color are not blitted.
Note that this copies pixels, not composites those. This matters when copying (partially) transparent regions.

gui.bitmap_load

Syntax: BITMAP/DBITMAP gui.bitmap_load(string filename)
Loads BITMAP or DBITMAP from file filename and returns the result.
If the result is indexed or not depends on the file.

gui.rainbow

Syntax: Number gui.rainbow(Number step, Number steps, Number base)
Performs hue rotation on color base.
The rotation is step/steps of full hue circle. The positive direction is red->yellow->green->cyan->blue->magenta->red.
The rotation will preserve saturation, value and opacity.

Hostmemory functions

(Generic)

These read/write memory space that is preserved over saves and loads.
All functions use little-endian byte order.
The data types are:

hostmemory.read / hostmemory.readbyte / hostmemory.readword / hostmemory.readdword / hostmemory.readqword

Syntax: Number hostmemory.read(Number address)
Syntax: Number hostmemory.readbyte(Number address)
Syntax: Number hostmemory.readword(Number address)
Syntax: Number hostmemory.readdword(Number address)
Syntax: Number hostmemory.readqword(Number address)
Returns the unsigned value read from address address (or false if out of bounds).

hostmemory.readsbyte / hostmemory.readsword / hostmemory.readsdword / hostmemory.readsqword

Syntax: Number hostmemory.readsbyte(Number address)
Syntax: Number hostmemory.readsword(Number address)
Syntax: Number hostmemory.readsdword(Number address)
Syntax: Number hostmemory.readsqword(Number address)
Returns the signed (two's complement) value read from address address (or false if out of bounds).

hostmemory.write / hostmemory.writebyte / hostmemory.writeword / hostmemory.writedword / hostmemory.writeqword

Syntax: Number hostmemory.write(Number address, Number value)
Syntax: Number hostmemory.writebyte(Number address, Number value)
Syntax: Number hostmemory.writeword(Number address, Number value)
Syntax: Number hostmemory.writedword(Number address, Number value)
Syntax: Number hostmemory.writeqword(Number address, Number value)
Writes the value value (two's complement if negative) to address address (extending memory if out of bounds).

Input functions

(Generic)

Unless otherwise noted, these are only valid in on_input callback.
Physical controllers 0-3 are on port #1 and controllers 4-7 are on port #2.
The control indices are:
IndexSNES gamepadGB(C) gamepadmousejustifiersuperscope
0BAxaxisxaxisxaxis
1YByaxisyaxisyaxis
2selectselectLtriggertrigger
3startstartRstartcursor
4upright--turbo
5downleft--pause
6leftup---
7rightdown---
8A----
9X----
10L----
11R----

input.set

Syntax: none input.set(number controller, number index, number value)
Set input on physical controller controller control index index to value value.
In case of buttons, zero is released, anything else is pressed.

input.get

Syntax: number input.get(number controller, number index)
Returns the value of physical controller controller input index index.

input.reset

Syntax: none input.reset([number delay])
Resets console. If delay is specified and delayed reset is supported, the reset will be delayed by that amount (but still at most one frame).

input.raw

Syntax: table input.raw()
Returns a table of tables. The outer table is indexed by key name.
The inner table has the following fields:
 * For keys, this is 0 for released, 1 for pressed.
 * For mouse, this is coordinate relative to top left of draw area (note that this may be negative!).
 * For axis types, this is raw value of axis.
 * For hats, 1 is up, 2 is right, 4 is down, 8 is left. Diagonals are OR of primary directions.
 * disabled: Disabled axis.
 * key: Key
 * axis: Axis
 * axis-inverse: Axis (inverted).
 * hat: Hat
 * mouse: Mouse axis.
 * pressure-mp: Pressure-sensitive button, reads cal_left when released, cal_right when pressed.
 * pressure-m0: Pressure-sensitive button, reads cal_left when released, cal_center when pressed.
 * pressure-0m: Pressure-sensitive button, reads cal_center when released, cal_left when pressed.
 * pressure-0p: Pressure-sensitive button, reads cal_center when released, cal_right when pressed.
 * pressure-pm: Pressure-sensitive button, reads cal_right when released, cal_left when pressed.
 * pressure-p0: Pressure-sensitive button, reads cal_right when released, cal_center when pressed.
For mouse axes, cal_left is top/left edge of draw area, cal_center is top/left edge of game area, and cal_right is bottom/right edge of draw area.

input.keyhook

Syntax: none input.keyhook(string key, boolean enabled)
If enabled=true, requests on_keyhook callback to happen when key key changes state.
If enabled=false, requests that state changes on key key do not cause callbacks to on_keyhook.

input.geta

Syntax: Tuple input.geta(Number controller)
Get all input indices of physical controller controller at once. The returned tuple is in control index order.

input.seta

Syntax: none input.seta(Number controller, Number values...)
Set all input indices of physical controller controller at once. The values are in control index order.

input.joyget

Syntax: table input.joyget(Number controller)
Returns a table, indexes by control name containing state of logical controller controller.

input.joyset

Syntax: none input.joyset(Number controller, table state)
Set state of logical controller controller to state. The state is indexed by control name.
For buttons, nil/false is released, anything else is pressed (normal lua boolean rules).

Memory functions

(Generic)

These functions read/write console memory space.
The byte order used depends on the target address. Normally it is little-endian, but DSP memory is host-endian.
The data types are:

memory.read / memory.readbyte / memory.readword / memory.readdword / memory.readqword

Syntax: Number memory.read(Number address)
Syntax: Number memory.readbyte(Number address)
Syntax: Number memory.readword(Number address)
Syntax: Number memory.readdword(Number address)
Syntax: Number memory.readqword(Number address)
Returns the unsigned value read from address address (out of bounds bytes read as zeroes).

memory.readsbyte / memory.readsword / memory.readsdword / memory.readsqword

Syntax: Number memory.readsbyte(Number address)
Syntax: Number memory.readsword(Number address)
Syntax: Number memory.readsdword(Number address)
Syntax: Number memory.readsqword(Number address)
Returns the signed (two's complement) value read from address address (out of bounds bytes read as zeroes).

memory.write / memory.writebyte / memory.writeword / memory.writedword / memory.writeqword

Syntax: None memory.write(Number address, Number value)
Syntax: None memory.writebyte(Number address, Number value)
Syntax: None memory.writeword(Number address, Number value)
Syntax: None memory.writedword(Number address, Number value)
Syntax: None memory.writeqword(Number address, Number value)
Writes the value value (two's complement if negative) to address address (writes out of bounds are ignored).

memory.mapbyte / memory.mapsbyte / memory.mapword / memory.mapsword / memory.mapdword / memory.mapsdword / memory.mapqword / memory.mapsqword

Syntax: Table memory.map<type>()
Syntax: Table memory.map<type>(Number base, Number aperturesize)
Map area of size aperturesize starting from base (the entire map space if not specified) with specified type.
The returned table can be read/written to read/write console memory space.
The index values to this table are measured in bytes.

memory.map_structure()

Syntax: MAP_STRUCTURE memory.map_structure()
Syntax: none MAP_STRUCTURE(String field, Number address, String type)
Syntax: MAP_STRUCTURE:<field>
Returns an object that works like a structure that maps console memory variables as fields.
On call to object, the field field is mapped to memory address address (with type type, which can be "byte", "sbyte", "word", "sword", "dword", "sdword", "qword" or "sqword").

memory.vma_count

Syntax: number memory.vma_count()
Returns the number of VMAs active.

memory.read_vma

Syntax: Table/Nil memory.read_vma(Number vma)
Returns a table (Nil if index is out of range) about vmath VMA (zero-based).
The returned table has the following fields:
Invalid VMA index causes nil to be returned.

memory.find_vma

Syntax: Table/Nil memory.find_vma(Number address)
Return the information (the same table as returned by memory.read_vma) about the VMA where address address belongs to.
If the address address is not covered by any VMA, returns nil.

memory.hash_state

Syntax: String memory.hash_state()
Return hash (hexadecimal) of state of the entire system. Mainly useful for debugging core savestate code.

memory.hash_region

Syntax: String memory.hash_region(Number base, Number size)
Returns the SHA-256 hash (hexadecimal) of the contents of memory in region of size size starting from base.

memory.readregion

Syntax: Table memory.readregion(Number base, Number size)
Returns a table (zero-based) containing the byte values of memory region of size size starting from base.
Note that behavior is undefined if the specified range crosses a VMA boundary.

memory.writeregion

Syntax: None memory.writeregion(Number base, Number size, Table data)
Writes contents of tabe data (zero-based) as byte values to memory region of size size starting from base.
Note that behavior is undefined if the specified range crosses a VMA boundary.

Movie functions

movie.currentframe

Syntax: Number movie.currentframe()
Returns the current frame number.

movie.framecount

Syntax: Number movie.framecount()
Returns the number of frames in movie.

movie.readonly

Syntax: Boolean movie.readonly()
Returns true in readonly mode, otherwise false.

movie.readwrite

Syntax: none movie.readwrite()
Set readwrite mode.
Note: Does not trigger callback to on_readwrite.

movie.frame_subframes

Syntax: Number movie.frame_subframes(Number frame)
Returns the number of subframes in frame frame.

movie.read_subframes

Syntax: Table movie.read_subframes(Number frame, Number subframe)
Reads subframe subframe (0-based) of frame frame.
Return value is a table with numeric indices:
The index i of controller c is at table index 12 * c + i + 4.
Buttons/flags read as 0 (released, not set) or 1 (pressed, set).

movie.read_rtc

Syntax: (Number seconds, Number sseconds) movie.read_rtc()
Returns the current RTC time. seconds is in whole seconds (since 19700101T000000Z) and sseconds is subsecond ticks (32040.5*768 per second for SNES, 32768*64 per second for second for GB(C)) in second.

movie.unsafe_rewind

Syntax: none movie.unsafe_rewind() Syntax: none movie.unsafe_rewind(UNSAFEREWIND r)
If called without parameters, triggers call to on_set_rewind with state.
If called with parameter r, rewinds to that state.
The state rewinded must be in past or the results are undefined.

movie.rerecords

Syntax: Number movie.rerecords()
Returns the current rerecord count.

Settings functions

(Generic)

On failure, the first return value is nil and the second is error message.

settings.set

Syntax: true settings.set(String name, String value)
Sets setting name to value value.

setting.get

Syntax: String/false settings.get(String name)
Reads setting name. Returns value or false if setting is not set.

setting.blank

Syntax: true setting.blank(String name)
Blanks setting name. Returns true on success.

setting.is_set

Syntax: boolean setting.is_set(String name)
Checks if setting name is set. Returns true if it is, false if it isn't.

Misc. functions

exec

Syntax: none exec(String cmd)
Invokes emulator command cmd.

print

Syntax: none print(...)
Print value(s)
Prints values of all arguments (note: Table, function, thread, light userdata and userdata values can't be printed). The arguments are printed separated by tabs.

utime

Syntax: (Number secs, Number usecs) utime()
Return the current time. secs is the number of seconds since 19700101T000000Z. usecs is the number of microseconds within second.

emulator_ready

Syntax: boolean emulator_ready()
Returns true if on_startup has already been called, false otherwise.

set_idle_timeout

Syntax: none set_idle_timeout(Number microsecs)
After microsecs microseconds have passed and the emulator is idle, call the on_idle callback.

set_timer_timeout

Syntax: none set_timer_timeout(Number microsecs)
After microsecs microseconds have passed, call the on_timer callback.

bus_address

Syntax: Number bus_address(Number address)
Returns the map address corresponding to address address on physical console bus.
Currently only supported for SNES & co.

loopwrapper(

Syntax: Function loopwrapper(Function fn, ...)
First calls function fn with function suspending the execution of the function when called and any remaining arguments.
When the function calls the suspend function, loopwrapper returns function that will resume fn when called.
The suspend function returns the values passed to resume function as parameters.
This is handy for using functions that have internal loops, that need to run over a long time, as callbacks.

Callbacks

(Generic)

These all are defined by Lua scripts.
Return fast from these hooks or the performance suffers. Not returning at all locks up the emulator.

on_paint

Called when screen is rerendered. Any draw primitives here affect the drawn screen.
Parameter: boolean non_synthetic
non_synthetic is true if on_paint is triggered by actual frame from console or by a subframe (if requested). It is false for calls triggered by gui.request_paint().

on_video

Called when video frame is rendered. Any draw primitives here affect dumped video frame.

on_input

Called when input for frame is decided. May change the input in readwrite mode.
Parameter: boolean subframe
subframe is true if this is in response to subframe. Otherwise false.

on_reset

Called when console resets.

on_frame

Called after frame has completed (after on_paint)

on_readwrite

Called when entering readwrite mode.

on_startup

Called when the emulator starts up.

on_pre_load

Called before loading a savestate or movie.
Parameter: String name
The name of savestate or movie to load is passed as name.

on_err_load

Called if loading savestate or movie failed.
Parameter: String name
The name of savestate or movie attempted to load is passed as name.

on_post_load

Called if loading savestate or movie succeeded.
The name of savestate/movie is name. is_state is true if savestate, false for movies.

on_pre_save

Called before saving savestate or movie (except if movie save was requested from Lua).
name is the name of savestate or movie. is_state is true if this is savestate, false if movie.

on_err_save

Called if saving savestate or movie failed (except if movie save was requested from Lua).
name is the name of savestate or movie that failed to save.

on_post_save

Called if saving savestate or movie succeeded (except if movie save was requested from Lua).
name is the name of savestate or movie. is_state is true if this is savestate, false if movie.

on_snoop

Called just before answering a poll from emulator core. Can't alter the result.
The poll is for port port, controller controller, control index index and the value to be returned is value.

on_quit

Called just before the emulator quits.

on_keyhook

Called if status of key has changed (and callbacks have been requested for that key).
The key state change is for is key. state is state table, in the same format as the inner tables of input.raw.

on_set_rewind

Called when unsafe rewind point has been set up.
The state object is passed as state.

on_pre_rewind

Called just before unsafe rewind occurs.

on_post_rewind

Called just after unsafe rewind has occured.

on_frame_emulated

Called just after frame emulation finishes, but before on_paint.

on_idle

Called when the specified idle timeout expires and the emulator is idle.

on_timer

Called when the specified timer timeout expires.

EmulatorResources/Lsnes/LuaFunctions last edited by MESHUGGAH on 1/5/2019 3:08 PM
Page History Latest diff List referrers View Source