# LibFunction (Luaj API)
Date: 2015-04-29

## org.luaj.vm2.lib
Class LibFunction

    java.lang.Object
      org.luaj.vm2.Varargs
          org.luaj.vm2.LuaValue
              org.luaj.vm2.LuaFunction
                  org.luaj.vm2.lib.LibFunction

Direct Known Subclasses:
  OneArgFunction, ThreeArgFunction, TwoArgFunction, VarArgFunction, ZeroArgFunction

    public abstract class LibFunction

extends LuaFunction

Subclass of `LuaFunction` common to Java functions exposed to lua.

To provide for common implementations in JME and JSE, library functions are typically grouped on one or more library classes and an opcode per library function is defined and used to key the switch to the correct function within the library.

Since lua functions can be called with too few or too many arguments, and there are overloaded `LuaValue.call()` functions with varying number of arguments, a Java function exposed in lua needs to handle the argument fixup when a function is called with a number of arguments differs from that expected.

To simplify the creation of library functions, there are 5 direct subclasses to handle common cases based on number of argument values and number of return return values.

- `ZeroArgFunction`
- `OneArgFunction`
- `TwoArgFunction`
- `ThreeArgFunction`
- `VarArgFunction`

To be a Java library that can be loaded via `require`, it should have a public constructor that returns a `LuaValue` that, when executed, initializes the library.

For example, the following code will implement a library called "hyperbolic" with two functions, "sinh", and "cosh":

     import org.luaj.vm2.LuaValue;
     import org.luaj.vm2.lib.*;

     public class hyperbolic extends TwoArgFunction {

    	public hyperbolic() {}

    	public LuaValue call(LuaValue modname, LuaValue env) {
    		LuaValue library = tableOf();
    		library.set( "sinh", new sinh() );
    		library.set( "cosh", new cosh() );
    		env.set( "hyperbolic", library );
    		return library;
    	}

    	static class sinh extends OneArgFunction {
    		public LuaValue call(LuaValue x) {
    			return LuaValue.valueOf(Math.sinh(x.checkdouble()));
    		}
    	}

    	static class cosh extends OneArgFunction {
    		public LuaValue call(LuaValue x) {
    			return LuaValue.valueOf(Math.cosh(x.checkdouble()));
    		}
    	}
    }

The default constructor is used to instantiate the library in response to `require 'hyperbolic'` statement, provided it is on Java"s class path. This instance is then invoked with 2 arguments: the name supplied to require(), and the environment for this function. The library may ignore these, or use them to leave side effects in the global environment, for example. In the previous example, two functions are created, 'sinh', and 'cosh', and placed into a global table called 'hyperbolic' using the supplied 'env' argument.

To test it, a script such as this can be used:

     local t = require('hyperbolic')
     print( 't', t )
     print( 'hyperbolic', hyperbolic )
     for k,v in pairs(t) do
     	print( 'k,v', k,v )
     end
     print( 'sinh(.5)', hyperbolic.sinh(.5) )
     print( 'cosh(.5)', hyperbolic.cosh(.5) )

It should produce something like:

     t	table: 3dbbd23f
     hyperbolic	table: 3dbbd23f
     k,v	cosh	function: 3dbbd128
     k,v	sinh	function: 3dbbd242
     sinh(.5)	0.5210953
     cosh(.5)	1.127626

See the source code in any of the library functions such as `BaseLib` or `TableLib` for other examples.

Field Summary
`protected java.lang.String` `name` The common name for this function, useful for debugging.
`protected int` `opcode` User-defined opcode to differentiate between instances of the library function class.

Fields inherited from class org.luaj.vm2.LuaFunction
`s_metatable`

Fields inherited from class org.luaj.vm2.LuaValue
`ADD, CALL, CONCAT, DIV, EMPTYSTRING, ENV, EQ, FALSE, INDEX, LE, LEN, LT, METATABLE, MINUSONE, MOD, MODE, MUL, NEWINDEX, NIL, NILS, NONE, NOVALS, ONE, POW, SUB, TBOOLEAN, TFUNCTION, TINT, TLIGHTUSERDATA, TNIL, TNONE, TNUMBER, TOSTRING, TRUE, TSTRING, TTABLE, TTHREAD, TUSERDATA, TVALUE, TYPE_NAMES, UNM, ZERO`

Constructor Summary
`protected` `LibFunction()` Default constructor for use by subclasses

Method Summary
`protected void` `bind(LuaValue env, java.lang.Class factory, java.lang.String[] names)` Bind a set of library functions.
`protected void` `bind(LuaValue env, java.lang.Class factory, java.lang.String[] names, int firstopcode)` Bind a set of library functions, with an offset
`LuaValue` `call()` Call `this` with 0 arguments, including metatag processing, and return only the first return value.
`LuaValue` `call(LuaValue a)` Call `this` with 1 argument, including metatag processing, and return only the first return value.
`LuaValue` `call(LuaValue a, LuaValue b)` Call `this` with 2 arguments, including metatag processing, and return only the first return value.
`LuaValue` `call(LuaValue a, LuaValue b, LuaValue c)` Call `this` with 3 arguments, including metatag processing, and return only the first return value.
`LuaValue` `call(LuaValue a, LuaValue b, LuaValue c, LuaValue d)`
`Varargs` `invoke(Varargs args)` Call `this` with variable arguments, including metatag processing, and retain all return values in a `Varargs`.
`protected static LuaValue[]` `newupe()` Java code generation utility to allocate storage for upvalue, leave it empty
`protected static LuaValue[]` `newupl(LuaValue v)` Java code generation utility to allocate storage for upvalue, initialize with value
`protected static LuaValue[]` `newupn()` Java code generation utility to allocate storage for upvalue, initialize with nil
`java.lang.String` `tojstring()` Convert to human readable String for any type.

Methods inherited from class org.luaj.vm2.LuaFunction
`checkfunction, classnamestub, getmetatable, isfunction, name, optfunction, strvalue, type, typename`

Methods inherited from class org.luaj.vm2.LuaValue

`add, add, add, and, arg, arg1, argerror, argerror, aritherror, aritherror, arithmt, arithmtwith, assert_, buffer, call, callmt, checkboolean, checkclosure, checkdouble, checkglobals, checkint, checkinteger, checkjstring, checklong, checkmetatag, checknotnil, checknumber, checknumber, checkstring, checktable, checkthread, checkuserdata, checkuserdata, compareerror, compareerror, comparemt, concat, concat, concatmt, concatTo, concatTo, concatTo, div, div, div, divInto, eq_b, eq, eqmtcall, equals, error, get, get, get, gettable, gt_b, gt_b, gt_b, gt, gt, gt, gteq_b, gteq_b, gteq_b, gteq, gteq, gteq, illegal, inext, initupvalue1, invoke, invoke, invoke, invoke, invoke, invokemethod, invokemethod, invokemethod, invokemethod, invokemethod, invokemethod, isboolean, isclosure, isint, isinttype, islong, isnil, isnumber, isstring, istable, isthread, isuserdata, isuserdata, isvalidkey, len, lenerror, length, listOf, listOf, load, lt_b, lt_b, lt_b, lt, lt, lt, lteq_b, lteq_b, lteq_b, lteq, lteq, lteq, metatableOf, metatag, method, method, method, method, method, method, mod, mod, mod, modFrom, mul, mul, mul, narg, neg, neq_b, neq, next, not, onInvoke, optboolean, optclosure, optdouble, optint, optinteger, optjstring, optlong, optnumber, optstring, opttable, optthread, optuserdata, optuserdata, optvalue, or, pow, pow, pow, powWith, powWith, presize, raweq, raweq, raweq, raweq, raweq, rawget, rawget, rawget, rawlen, rawset, rawset, rawset, rawset, rawset, rawset, rawset, rawsetlist, set, set, set, set, set, set, set, setmetatable, settable, strcmp, strcmp, strongvalue, sub, sub, sub, subargs, subFrom, subFrom, tableOf, tableOf, tableOf, tableOf, tableOf, tableOf, tailcallOf, testfor_b, toboolean, tobyte, tochar, todouble, tofloat, toint, tolong, tonumber, toshort, tostring, toString, touserdata, touserdata, typerror, unimplemented, userdataOf, userdataOf, valueOf, valueOf, valueOf, valueOf, valueOf, valueOf, varargsOf, varargsOf, varargsOf, varargsOf, varargsOf, varargsOf`

Methods inherited from class org.luaj.vm2.Varargs

`argcheck, checkboolean, checkclosure, checkdouble, checkfunction, checkint, checkinteger, checkjstring, checklong, checknotnil, checknumber, checkstring, checktable, checkthread, checkuserdata, checkuserdata, checkvalue, eval, isfunction, isnil, isnoneornil, isnumber, isstring, istable, isTailcall, isthread, isuserdata, isvalue, optboolean, optclosure, optdouble, optfunction, optint, optinteger, optjstring, optlong, optnumber, optstring, opttable, optthread, optuserdata, optuserdata, optvalue, toboolean, tobyte, tochar, todouble, tofloat, toint, tojstring, tolong, toshort, touserdata, touserdata, type`

Methods inherited from class java.lang.Object
`clone, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait`

Field Detail

### opcode

    protected int opcode

  User-defined opcode to differentiate between instances of the library function class.

  Subclass will typicall switch on this value to provide the specific behavior for each function.

### name

    protected java.lang.String name

  The common name for this function, useful for debugging.

  Binding functions initialize this to the name to which it is bound.

Constructor Detail

### LibFunction

    protected LibFunction()

  Default constructor for use by subclasses

Method Detail

### tojstring

    public java.lang.String tojstring()

  Description copied from class: `LuaValue`
  Convert to human readable String for any type.

  Overrides:
    `tojstring` in class `LuaFunction`
  Returns:
    String for use by human readers based on type.
  See Also:
    `LuaValue.tostring()`, `LuaValue.optjstring(String)`, `LuaValue.checkjstring()`, `LuaValue.isstring()`, `LuaValue.TSTRING`

### bind

    protected void bind(LuaValue env,
                        java.lang.Class factory,
                        java.lang.String[] names)

  Bind a set of library functions.

  An array of names is provided, and the first name is bound with opcode = 0, second with 1, etc.

  Parameters:
    `env` - The environment to apply to each bound function
    `factory` - the Class to instantiate for each bound function
    `names` - array of String names, one for each function.
  See Also:
    `bind(LuaValue, Class, String[], int)`

### bind

    protected void bind(LuaValue env,
                        java.lang.Class factory,
                        java.lang.String[] names,
                        int firstopcode)

  Bind a set of library functions, with an offset

  An array of names is provided, and the first name is bound with opcode = `firstopcode`, second with `firstopcode+1`, etc.

  Parameters:
    `env` - The environment to apply to each bound function
    `factory` - the Class to instantiate for each bound function
    `names` - array of String names, one for each function.
    `firstopcode` - the first opcode to use
  See Also:
    `bind(LuaValue, Class, String[])`

### newupe

    protected static LuaValue[] newupe()

  Java code generation utility to allocate storage for upvalue, leave it empty

### newupn

    protected static LuaValue[] newupn()

  Java code generation utility to allocate storage for upvalue, initialize with nil

### newupl

    protected static LuaValue[] newupl(LuaValue v)

  Java code generation utility to allocate storage for upvalue, initialize with value

### call

    public LuaValue call()

  Description copied from class: `LuaValue`
  Call `this` with 0 arguments, including metatag processing, and return only the first return value.

  If `this` is a `LuaFunction`, call it, and return only its first return value, dropping any others. Otherwise, look for the `LuaValue.CALL` metatag and call that.

  If the return value is a `Varargs`, only the 1st value will be returned. To get multiple values, use `LuaValue.invoke()` instead.

  To call `this` as a method call, use `LuaValue.method(LuaValue)` instead.

  Overrides:
    `call` in class `LuaValue`
  Returns:
    First return value `(this())`, or `LuaValue.NIL` if there were none.
  See Also:
    `LuaValue.call(LuaValue)`, `LuaValue.call(LuaValue,LuaValue)`, `LuaValue.call(LuaValue, LuaValue, LuaValue)`, `LuaValue.invoke()`, `LuaValue.method(String)`, `LuaValue.method(LuaValue)`

### call

    public LuaValue call(LuaValue a)

  Description copied from class: `LuaValue`
  Call `this` with 1 argument, including metatag processing, and return only the first return value.

  If `this` is a `LuaFunction`, call it, and return only its first return value, dropping any others. Otherwise, look for the `LuaValue.CALL` metatag and call that.

  If the return value is a `Varargs`, only the 1st value will be returned. To get multiple values, use `LuaValue.invoke()` instead.

  To call `this` as a method call, use `LuaValue.method(LuaValue)` instead.

  Overrides:
    `call` in class `LuaValue`
  Parameters:
    `a` - First argument to supply to the called function
  Returns:
    First return value `(this(arg))`, or `LuaValue.NIL` if there were none.
  See Also:
    `LuaValue.call()`, `LuaValue.call(LuaValue,LuaValue)`, `LuaValue.call(LuaValue, LuaValue, LuaValue)`, `LuaValue.invoke(Varargs)`, `LuaValue.method(String,LuaValue)`, `LuaValue.method(LuaValue,LuaValue)`

### call

    public LuaValue call(LuaValue a,
                         LuaValue b)

  Description copied from class: `LuaValue`
  Call `this` with 2 arguments, including metatag processing, and return only the first return value.

  If `this` is a `LuaFunction`, call it, and return only its first return value, dropping any others. Otherwise, look for the `LuaValue.CALL` metatag and call that.

  If the return value is a `Varargs`, only the 1st value will be returned. To get multiple values, use `LuaValue.invoke()` instead.

  To call `this` as a method call, use `LuaValue.method(LuaValue)` instead.

  Overrides:
    `call` in class `LuaValue`
  Parameters:
    `a` - First argument to supply to the called function
    `b` - Second argument to supply to the called function
  Returns:
    First return value `(this(arg1,arg2))`, or `LuaValue.NIL` if there were none.
  See Also:
    `LuaValue.call()`, `LuaValue.call(LuaValue)`, `LuaValue.call(LuaValue, LuaValue, LuaValue)`, `LuaValue.invoke(LuaValue, Varargs)`, `LuaValue.method(String,LuaValue,LuaValue)`, `LuaValue.method(LuaValue,LuaValue,LuaValue)`

### call

    public LuaValue call(LuaValue a,
                         LuaValue b,
                         LuaValue c)

  Description copied from class: `LuaValue`
  Call `this` with 3 arguments, including metatag processing, and return only the first return value.

  If `this` is a `LuaFunction`, call it, and return only its first return value, dropping any others. Otherwise, look for the `LuaValue.CALL` metatag and call that.

  If the return value is a `Varargs`, only the 1st value will be returned. To get multiple values, use `LuaValue.invoke()` instead.

  To call `this` as a method call, use `LuaValue.method(LuaValue)` instead.

  Overrides:
    `call` in class `LuaValue`
  Parameters:
    `a` - First argument to supply to the called function
    `b` - Second argument to supply to the called function
    `c` - Second argument to supply to the called function
  Returns:
    First return value `(this(arg1,arg2,arg3))`, or `LuaValue.NIL` if there were none.
  See Also:
    `LuaValue.call()`, `LuaValue.call(LuaValue)`, `LuaValue.call(LuaValue, LuaValue)`, `LuaValue.invoke(LuaValue, LuaValue, Varargs)`, `LuaValue.invokemethod(String,Varargs)`, `LuaValue.invokemethod(LuaValue,Varargs)`

### call

    public LuaValue call(LuaValue a,
                         LuaValue b,
                         LuaValue c,
                         LuaValue d)

### invoke

    public Varargs invoke(Varargs args)

  Description copied from class: `LuaValue`
  Call `this` with variable arguments, including metatag processing, and retain all return values in a `Varargs`.

  If `this` is a `LuaFunction`, call it, and return all values. Otherwise, look for the `LuaValue.CALL` metatag and call that.

  To get a particular return value, us `Varargs.arg(int)`

  To call `this` as a method call, use `LuaValue.invokemethod(LuaValue)` instead.

  Overrides:
    `invoke` in class `LuaValue`
  Parameters:
    `args` - Varargs containing the arguments to supply to the called function
  Returns:
    All return values as a `Varargs` instance.
  See Also:
    `LuaValue.varargsOf(LuaValue[])`, `LuaValue.call(LuaValue)`, `LuaValue.invoke()`, `LuaValue.invoke(LuaValue,Varargs)`, `LuaValue.invokemethod(String,Varargs)`, `LuaValue.invokemethod(LuaValue,Varargs)`

Copyright © 2007-2015 Luaj.org. All Rights Reserved.