LSLua 0.5
by doy (jluehrs2 at uiuc dot edu)
http://dev.litestep.com/projects/LSLua/


Introduction
----------------------

As you know, LiteStep has modules.

LSLua is a module.
Lua supports modules as well.
This document will refer to module

LSLua is a scripting interface to LiteStep using the Lua scripting language.
Lua is a cross platform, open source, embeddable scripting language. This
module provides an interface to the LSAPI through Lua scripts.

To load LSLua, put a line resembling
*NetLoadModule lslua-0.5 load lslua.dll threaded
in your theme.rc. The 'load lslua.dll' part is important, since, due to
restrictions in NetLoadModule, all of the modules that come with LSLua must
have a .dll extension for NetLoadModule to unpack them to the correct place.
The threaded part is important, since otherwise things that require
concurrent operation of things in Lua (such as the timer module) won't work.

Step.rc Settings and Bang Commands
----------------------
*LuaFile <filename>
Executes the given file. This registers any functions that are declared, and
executes any statements not declared in a function. Any function whose name
begins with "bang_" is also registered as a !bang command, named with the rest
of the function name. For example, the function bang_test would be registered
as !test. Bang functions take one optional string argument consisting of the
entire argument string passed to them.

*LuaBinaryModuleDir <directory>
Declares a directory to be added to the search path for binary modules
(package.cpath). Uses an extension of .dll.

*LuaScriptModuleDir <directory>
Declares a directory to be added to the search path for Lua script modules
(package.path). Uses an extension of .lua or .lua.dll.

*LuaModuleDir <directory>
Equivalent to both of *LuaBinaryModuleDir and *LuaScriptModuleDir.

*LuaPackageDir <directory> (deprecated)
Same as *LuaModuleDir.

!LuaExec <lua chunk>
Executes the argument as a Lua chunk. Note that new bangs are not registered
using this method (this may change in the future).

Modules (for LsLua, not LiteStep)
----------------------
LSLua comes with six modules designed to make certain tasks easier. To use
them, include the line 'require "<modulename>";' at the top of your Lua
script. All functions provided by the modules are provided in a global table
with the same name as the module, so for example, you would access the pause()
function through timer.pause(). Here are some descriptions:

args:
The args module defines some useful argument parsing functions.

Variables defined:
    strjoin(): strjoin takes two arguments: a table of strings, and a string to
    use as the separator. It returns a string containing all of the elements of
    the table concatenated together, with elements separated by the separator
    string passed as the second argument.
    For example,
        strjoin( { "this", "is", "a", "test" }, " " ) == "this is a test"

    strsplit(): strsplit takes two arguments: a string, and a delimiter. It
    splits the string up into a table of substrings based on the delimiter, and
    returns that table.
    For example,
        strsplit( "this is a test", " " ) == { "this", "is", "a", "test" }

    qsplit(): qsplit takes between 4 arguments, some of them optional. The
    first argument is a string, the second is a table of strings to use as
    delimiters, and the third and fourth are tables of strings to use as left
    and right quotes, respectively. If the fourth argument is omitted, it
    defaults to the same as the third, and if they are both omitted, they
    default to { "\"", "'" }. If the second argument is omitted, it defaults
    to { " " }. If any of the second, third, or fourth arguments are strings,
    they are automatically converted to tables holding those strings. This
    function splits the string into substrings based on the delimiter like
    strsplit does, but it takes into account quote characters as well.
    For example,
        qsplit( "this is a 'string with quotes'" ) == { "this", "is", "a",
        "string with quotes" }
        qsplit( "%{hello},%{world}", ",", "%{", "}" ) == { "hello", "world" }
        qsplit( "[this is][a test]", "", "[", "]" ) == { "this is", "a test" }

    mstrsplit(): mstrsplit is the same as strsplit, except it returns the
    results as multiple return values rather than as a table.

    mqsplit(): mqsplit is the same as qsplit, except it returns the results
    as multiple return values rather than as a table.

evar:
The evar module allows access to and (re)assignment of LiteStep evars.

Saving evars to file (like mzscript varfiles) is not yet supported,
although they may be in a future release.

Variables defined:
    toboolean(): toboolean takes one argument, a string for an evar's name.
    It returns a boolean evaluating the given evar as a boolean like how
    LiteStep core would in RC 'scripting' or preprocessing:
    It returns false for an evar whose value is "0", "false", "off", or "no".
    Otherwise it returns true.

  If for some reason you need to access the evar named "toboolean",
  access it with a different casing, like "ToBoolean".

 evar Access:
The evar table itself can be indexed to access the values of evars. For example,
evar.LiteStepDir == evar[ "LiteStepDir" ] == "C:\LiteStep\" (on my system).

The result is nil for both undefined evars and those evars previously
set to nil through the evar table (magic value is replaced with nil).

 evar Assignment:
Keys of the evar table can be assigned to; doing so will
set an evar's value.  tostring() is applied to this value.
For example, evar.nameOfEvar = 13

Setting an evar to nil this way will actually set the evar to a magic value.

 Notes on evar access and assignment and why a magic value for nil:

There is no way (aside from !reload or !recycle or restarting ls)
to undefine an evar, so the evar module has its own notion of 'undefined';
It does so using its own magic value.

So it makes no sense to set an evar to nil, because evars
are just key-value pairs where both key and value are strings
--omitting one or the other or both makes no sense.

The choice to handle nil specially is because of the addition of
toboolean(); nil should be recognized as false; why not handle nil
in assignment as well?

textedit:
This is designed to emulate the textedit.dll/xTextedit.dll modules in Lua. It
can search through files, replace lines, insert lines, delete lines, etc. The
main difference is that this module uses Lua pattern matching instead of
standard regexes like textedit.dll does.
Variables defined:
    append( filename, str ): append adds str at the end of the file filename on
    a new line.

    insert( filename, pattern, str, mode ): insert searches through the file
    filename for lines matching pattern, and inserts str there. 'There' is
    determined by part of the string mode. The mode string can be any
    combination of the letters g, i, b, and G. g means 'global', and means that
    the function will be applied to every matching line in the file. i means
    case insensitive, which should be self-explanitory. b means before, and
    only applies to insert. If b is given, str will be inserted before the
    matching line, otherwise it will be inserted after. G means line global,
    and only applies for replace(). It means that replace() should replace each
    match on a given line, instead of the first. insert() returns the number
    of insertions made.

    delete( filename, pattern, mode ): delete deletes lines that match pattern,
    following the mode rules from insert(). delete() returns the number of
    deletions made.

    replace( filename, pattern, replace_pattern, mode ):replace searches the
    file filename for lines that match pattern and replaces pattern with
    replace_pattern on those lines. Captures and stuff like that from
    string.gsub() are all valid here. It returns the number of times it
    replaced pattern.

    find( filename, pattern, mode ): find searches filename for pattern, and
    returns either the number of the first line that matches, or a table
    containing all lines that match if the mode string contains g.

    delete_line( filename, line_num ): delete_line deletes line number line_num
    from the file filename. It returns true if the line was successfully
    deleted and false otherwise.

    insert_line( filename, str, line_num, before ): insert_line inserts str
    into the file filename either before line_num if before is true, or after
    line_num if before is false. It returns true if the insertion was
    successful and false otherwise.

    get_line( filename, line_num ): get_line returns a string containing the
    contents of line line_num in file filename.

thread:
The thread module doesn't provide anything useful to users of LSLua, but it
provides an important interface for module writers. It allows scripters to
access the global coroutines defined by LSLua each time a user defined bang is
called, allowing scripts to be started and resumed by name.
Variables defined:
    yield(): yield yields the current bang execution, with a value of a string
    that is passed to it as an argument. If you declare your own
    coroutines in your code, you should always pass arguments back through
    coroutine.yield(), so that you can check to be sure that what is yielding
    is in fact your code, and not a thread trying to yield. See the animation
    module for an example of this.

    resume(): resume resumes the execution of the function that yielded with
    the name that is passed to resume.

timer:
The timer module is an interface to the timer LiteStep module, and allows for
pauses to work without freezing anything or stopping LSLua from functioning.
Variables defined:
    pause(): pause takes a single argument, defining how long to pause for,
    using the timer.dll syntax for time. For example, pause( 500 ) pauses for
    500 milliseconds, pause( "3s" ) pauses for 3 seconds, etc.

    resume(): resume is the function that timer.dll calls when the pause() is
    over. It shouldn't ever be called manually, unless you want to end a
    pause() early.

Other information
----------------------
LSLua defines the global table lslua which contains some important functions
and variables.
    message_box( text, title )
      Creates a message box with text of text and optional title of title.
      Quotes do work correctly, unlike !alert.

    exec( str )
      Executes str using LSAPI function LSExecute() (like lsxcommand).

    res():
      Returns a table such that res().x is the x resolution, res().y is
      the y resolution, and res().bpp is the bits per pixel.

    mouse()
      Returns a table such that mouse().x is the x coordinate of the
      mouse and mouse().y is the y coordinate of the mouse.

    milli()
      Returns the current number of milliseconds since the last second
      (use os.date to get the rest of the time information).

    version
      a string containing the lslua version.

    init()
      A user defined function that runs at the very end of module load, so
      that bangs are registered. It is also executed in a coroutine, so timers
      should work.

    quit()
      Same as init, but it is executed as the first thing on module unload.

    get_evar( name )
      Get an evar's value in memory, not file.
      Returns a string, or nil if evar is not defined.
      Similar to what you expect $name$ would give.
      Uses LSAPI function GetRCString().

      Note: the preferred way to use this function
            is through the evar module.
    
    get_line( evar_name ) --what should this be renamed to?
      Get an evar's raw value in memory, not file.
      Returns a string, or nil if evar is not defined.    
      Similar to get_evar but does not return first token.
      Uses LSAPI function GetRCLine().
    
    set_evar( name, value )
      Set an evar's value in memory, not file.
      Uses LSAPI function LSSetVariable().

      Note: the preferred way to use this function
            is through the evar module.
    
    rc_lines( prefix, file )
      Get lines with given prefix from rc file.
      Use empty string to return all lines.
      If file not specified, defaults to settings already loaded in memory.
      Returns a table of strings.
      Uses LSAPI function LCReadNextCommand().


During bang execution, !LuaExec execution, and init() and quit(), it also
declares the global variable CURRENT_THREAD, which is the coroutine that
contains the bang execution. See the thread module for how this can be used.

Information about Lua
----------------------
The Lua website is at http://lua.org. For information on Lua syntax, the Lua 5.0
manual is located at http://lua.org/manual/5.0/, and for information about
using the language, the site also hosts the book "Programming in Lua" at
http://lua.org/pil/. Documentation for Lua 5.1 isn't available on the web yet,
but can be found in the source tarball at http://lua.org/download.html. Code
snippets and general information can be found at the wiki, located at
http://lua-users.org/wiki/. Finally, for more specific questions not covered by
those resources, feel free to ask for help in #lua on irc.freenode.net. LSLua
now uses the beta version of Lua 5.1, so many of these resources may be slightly
inaccurate. Ask in #lua if there is anything that doesn't work that
you believe should.

Future
----------------------
- mzscript style varfile support. This will likely be added onto the evar
  module
- Better file manipulation functions (directory listings, etc)
- popen patch?
- better timer interface
- !LuaAddBang/!LuaDeleteBang
- clipboard access
- luathread library for os level threading

Known Bugs
----------------------
- message_box()s left open over a recycle will cause ls to crash, since when
  the function returns, the lua_State* that it was called from has already been
  deleted.
- crashes ls if you define an already defined bang
- tostring required for number args to exec()
- is this a !luaexec problem or a evar problem?
(15:16:39) cerbie: !setevar zzz "[meminuse] [cpu]"
(15:17:14) cerbie: !parseevars !alert "%#zzz%#" shows it. !luaexec message_box(evar.zzz) shows blank, and using it in a function, clearly returns ""
(15:20:12) cerbie: using \" seems to fix it, but then others don't work quite right. I can go through and figure them all out again later. Oh, I made a mistake on the above: !luaexec  exec() should be around the !parseevars
(15:21:46) cerbie: oftentimes, the evar setting works, and returning can work in special circumstances, like message_box(), but then return it from a function, and it wants to call it
(15:22:32) doy: are you getting the error about calling it when you use the string, or when you define it?
(15:23:22) cerbie: using. Like qwe = function that returns it
- register bangs after processing each file, and add a way to register bangs
  later
- animation module doesn't work with timers... after the second call to
  thread.resume(), the coroutine to resume is dead, although it definitely does
  not finish executing, and i dont see an error anywhere


Changelog
----------------------
0.5:
changes by doy:
- now using Lua 5.1
- bug fixes in the textedit module (thanks to c00i90wn)
- fixed not unloading !LuaExec on module unload
- fixed not unloading any other bang on unload, for a different reason
- removed animation module since it has been nonfunctional for quite a while
- removed xevar module
- added *LuaModuleDir, *LuaBinaryModuleDir, *LuaScriptModuleDir
changes by tnl:
- replaced in the docs, occurrences of "package" to "module"
  (leaving older portions of the changelog intact)
- added functions get_evar, get_line, set_evar, rc_lines
- removed _evar (replaced with get_evar)
- updated evar module to use get_evar, get_line, set_evar.
  get_evar and get_line does not show an error message when
  accessing an undefined evar.

0.4.3.1:
- fixed res().bpp

0.4.3:
- now actually testing for the existence of init() and quit() before blindly
  calling them

0.4.2:
- fixed metatable bug in evar package (overwriting mt.__index=_G is bad)
  for anyone out there who has already written packages that set metatables for
  themselves (such as the xlabel wrapper), you will need to change the way you
  access globals, since calling setmetatable makes the globals in the package
  go away. Declaring them as locals like in evar and xevar should do the trick.
- no one likes semicolons
- lslua.init() and lslua.quit() work now
- added xevar module (thanks to tnl)

0.4.1:
- recompile to fix the debug library dependency
- email address update

0.4:
- textedit package added
- bug with quotes in *LuaPackageDir fixed
- reorganized code - lslua.dll is the module, luainterface.dll is the Lua class
  which the module uses to interface with the lua engine, and lua51.dll is the
  lua engine itself. this was to allow loadlib to work, since lua needs to be
  its own dll for loadlib to work properly
- upgraded to lua 5.1
- loadlib should work, although i have done no testing of this at all
- added mouse(), res(), and milli()
- all global functions defined by lslua by default are now in the table lslua
  (lslua.message_box(), lslua.mouse(), etc). feel free to open the table
  yourself if you feel like it (for k,v in pairs( lslua ) do _G[ k ] = v end)
- LSLUA_VERSION becomes lslua.version
- lslua.init() and lslua.quit() added to make *script start functionality
  actually work (both in that bangs will have been registered before this is
  called and in that the timer package will work properly on init now)
- !luaexec works with the timer package now
- animation package is broken at the moment... i don't think anyone really used
  it anyway, but i'll fix it when i have the chance

0.3.1:
- the ls table in the evar package has been removed. Also, the toString(), etc
  functions are also removed, since they were only there for toBoolean(),
  which never worked correctly to begin with. Access evars with evar.EvarName.
- memory leak relating to coroutine creation fixed
- fixed random global in timer package, and changed how the names of the timers
  are generated
- reordered some arguments, changed some function names, and added mqsplit in
  the args package
- finally finished the documentation

0.3:
- lots of new require() stuff. All require()ed global variables are now
  namespaced, so use evar.LitestepDir or timer.pause().
  - require( "vars" ) is now require( "evar" ). Everything else is the same.
  - require( "args" ) has argument parsing functions
  - require( "timer" ) has helper functions for timer-0.5 (including pause())
  - require( "animation" ) is a method for easy concurrent animations
  - require( "thread" ) is a way to interact with the global coroutines
    created with each function call. It is used to implement timer.
- access the current lslua version from the global variable LSLUA_VERSION
- new step.rc setting: *LuaPackageDir for adding your own directories to the
  require() search path
- rewrote Lua.trigger() to use coroutines: manipulate them with the thread
  package
- runtime errors no longer disable lua
- !LuaExec to execute arbitrary lua code

0.2:
- First public release
- Bangs can now use arguments
- exec now has the option of passing several arguments in that will be passed
  as arguments to the command. For examples, see example.lua
- Removed pause(), since it really can't work correctly without better core
  support.
- Moved loading of evar code out to Lua as well... 'require( "vars" )' to get
  it.

Private alphas:
----------------------
0.1.1:
- Changed evar access to use the global 'ls' table. Access evars now like
  'ls.LiteStepDir:toString()'. Yes, the first is a period, and the second is a
  colon. In Lua, ls.var is equivalent to ls[ "var" ], and var:func is
  equivalent to var.func( self ) (self is lua's equivalent of 'this' in c++; it
  refers to the current object). Evar saving is coming shortly(:
- message_box now takes two arguments, first being the messagebox text, and the
  second being the title of the messagebox.
- The source zip now comes with just the precompiled Lua libraries. If you
  care, you can get the Lua source from http://lua.org/ftp/.

0.1:
- Initial release.
