org.luaj.vm2.LuaString Java Examples

The following examples show how to use org.luaj.vm2.LuaString. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseLib.java    From luaj with MIT License 6 votes vote down vote up
public int read() throws IOException {
	if ( remaining < 0 )
		return -1;
	if ( remaining == 0 ) {
		LuaValue s = func.call();
		if ( s.isnil() )
			return remaining = -1;
		LuaString ls = s.strvalue();
		bytes = ls.m_bytes;
		offset = ls.m_offset;
		remaining = ls.m_length;
		if (remaining <= 0)
			return -1;
	}
	--remaining;
	return 0xFF&bytes[offset++];
}
 
Example #2
Source File: LuaC.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Parse the input
   */
  private Prototype luaY_parser(InputStream z, String name, boolean standardSyntax) throws IOException {
      LexState lexstate = new LexState(this, z, standardSyntax);
      FuncState funcstate = new FuncState();
      // lexstate.buff = buff;
      lexstate.fs = funcstate;
      lexstate.setinput(this, z.read(), z, (LuaString) LuaValue.valueOf(name));
      /* main func. is always vararg */
      funcstate.f = new Prototype();
      funcstate.f.source = (LuaString) LuaValue.valueOf(name);
      lexstate.mainfunc(funcstate);
      LuaC._assert(funcstate.prev == null);
/* all scopes should be correctly finished */
      LuaC._assert(lexstate.dyd == null
              || (lexstate.dyd.n_actvar == 0 && lexstate.dyd.n_gt == 0 && lexstate.dyd.n_label == 0));
      return funcstate.f;
  }
 
Example #3
Source File: PackageLib.java    From XPrivacyLua with GNU General Public License v3.0 6 votes vote down vote up
public Varargs invoke(Varargs args) {
	LuaString name = args.checkstring(1);
	InputStream is = null;
			
	// get package path
	LuaValue path = package_.get(_PATH);
	if ( ! path.isstring() ) 
		return valueOf("package.path is not a string");

	// get the searchpath function.
	Varargs v = package_.get(_SEARCHPATH).invoke(varargsOf(name, path));
	
	// Did we get a result?
	if (!v.isstring(1))
		return v.arg(2).tostring();
	LuaString filename = v.arg1().strvalue();

	// Try to load the file.
	v = globals.loadfile(filename.tojstring()); 
	if ( v.arg1().isfunction() )
		return LuaValue.varargsOf(v.arg1(), filename);
	
	// report error
	return varargsOf(NIL, valueOf("'"+filename+"': "+v.arg(2).tojstring()));
}
 
Example #4
Source File: StringLib.java    From XPrivacyLua with GNU General Public License v3.0 6 votes vote down vote up
public Varargs invoke(Varargs args) {
	LuaString s = args.checkstring(1);
	int l = s.m_length;
	int posi = posrelat( args.optint(2,1), l );
	int pose = posrelat( args.optint(3,posi), l );
	int n,i;
	if (posi <= 0) posi = 1;
	if (pose > l) pose = l;
	if (posi > pose) return NONE;  /* empty interval; return no values */
	n = (int)(pose -  posi + 1);
	if (posi + n <= pose)  /* overflow? */
	    error("string slice too long");
	LuaValue[] v = new LuaValue[n];
	for (i=0; i<n; i++)
		v[i] = valueOf(s.luaByte(posi+i-1));
	return varargsOf(v);
}
 
Example #5
Source File: StringLib.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
/**
 * string.sub (s, i [, j])
 * <p>
 * Returns the substring of s that starts at i and continues until j;
 * i and j may be negative. If j is absent, then it is assumed to be equal to -1
 * (which is the same as the string length). In particular, the call
 * string.sub(s,1,j)
 * returns a prefix of s with length j, and
 * string.sub(s, -i)
 * returns a suffix of s with length i.
 */
static Varargs sub(Varargs args) {
     LuaString s = args.checkstring(1);
     int l = s.length();

    int start = posrelat(args.checkint(2), l);
    int end = posrelat(args.optint(3, -1), l);

    if (start < 1)
        start = 1;
    if (end > l)
        end = l;

    if (start <= end) {
        return s.substring(start - 1, end);
    } else {
        return EMPTYSTRING;
    }
}
 
Example #6
Source File: LuaC.java    From XPrivacyLua with GNU General Public License v3.0 6 votes vote down vote up
/** Parse the input */
private Prototype luaY_parser(InputStream z, String name) throws IOException{
	LexState lexstate = new LexState(this, z);
	FuncState funcstate = new FuncState();
	// lexstate.buff = buff;
	lexstate.fs = funcstate;
	lexstate.setinput(this, z.read(), z, (LuaString) LuaValue.valueOf(name) );
	/* main func. is always vararg */
	funcstate.f = new Prototype();
	funcstate.f.source = (LuaString) LuaValue.valueOf(name);
	lexstate.mainfunc(funcstate);
	LuaC._assert (funcstate.prev == null);
	/* all scopes should be correctly finished */
	LuaC._assert (lexstate.dyd == null 
			|| (lexstate.dyd.n_actvar == 0 && lexstate.dyd.n_gt == 0 && lexstate.dyd.n_label == 0));
	return funcstate.f;
}
 
Example #7
Source File: LuaInterpreter.java    From claudb with MIT License 6 votes vote down vote up
private RedisToken convert(Object result) {
  return Pattern1.<Object, RedisToken>build()
      .when(instanceOf(LuaTable.class))
        .then(table -> convertLuaTable((LuaTable) table))
      .when(instanceOf(LuaNumber.class))
        .then(number -> convertLuaNumber((LuaNumber) number))
      .when(instanceOf(LuaBoolean.class))
        .then(boolean_ -> convertLuaBoolean((LuaBoolean) boolean_))
      .when(instanceOf(LuaString.class))
        .then(string -> convertLuaString((LuaString) string))
      .when(instanceOf(Number.class))
        .then(number -> convertNumber((Number) number))
      .when(instanceOf(String.class))
        .then(string -> convertString((String) string))
      .when(instanceOf(Boolean.class))
        .then(boolean_ -> convertBoolean((Boolean) boolean_))
      .otherwise()
        .then(this::convertUnknown)
      .apply(result);
}
 
Example #8
Source File: LexState.java    From VideoOS-Android-SDK with GNU General Public License v3.0 6 votes vote down vote up
void forlist(LuaString indexname) {
/* forlist -> NAME {,NAME} IN explist1 forbody */
      FuncState fs = this.fs;
      expdesc e = new expdesc();
      int nvars = 4;   /* gen, state, control, plus at least one declared var */
      int line;
      int base = fs.freereg;
/* create control variables */
      this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_GENERATOR);
      this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_STATE);
      this.new_localvarliteral(RESERVED_LOCAL_VAR_FOR_CONTROL);
/* create declared variables */
      this.new_localvar(indexname);
      while (this.testnext(',')) {
          this.new_localvar(this.str_checkname());
          ++nvars;
      }
      this.checknext(TK_IN);
      line = this.linenumber;
      this.adjust_assign(3, this.explist(e), e);
      fs.checkstack(3); /* extra space to call generator */
      this.forbody(base, line, nvars - 3, false);
  }
 
Example #9
Source File: FuncState.java    From XPrivacyLua with GNU General Public License v3.0 6 votes vote down vote up
static int singlevaraux(FuncState fs, LuaString n, expdesc var, int base) {
	if (fs == null)   /* no more levels? */
		return LexState.VVOID;  /* default is global */
	int v = fs.searchvar(n); /* look up at current level */
	if (v >= 0) {
		var.init(LexState.VLOCAL, v);
		if (base == 0)
			fs.markupval(v); /* local will be used as an upval */
		return LexState.VLOCAL;
	} else { /* not found at current level; try upvalues */
	    int idx = fs.searchupvalue(n);  /* try existing upvalues */
	    if (idx < 0) {  /* not found? */
	        if (singlevaraux(fs.prev, n, var, 0) == LexState.VVOID) /* try upper levels */
	          return LexState.VVOID;  /* not found; is a global */
	        /* else was LOCAL or UPVAL */
	        idx  = fs.newupvalue(n, var);  /* will be a new upvalue */
	    }
	    var.init(LexState.VUPVAL, idx);
	    return LexState.VUPVAL;
	}
}
 
Example #10
Source File: IoLib.java    From XPrivacyLua with GNU General Public License v3.0 6 votes vote down vote up
public static LuaValue freaduntil(File f,boolean lineonly) throws IOException {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	int c;
	try {
		if ( lineonly ) {
			loop: while ( (c = f.read()) > 0 ) { 
				switch ( c ) {
				case '\r': break;
				case '\n': break loop;
				default: baos.write(c); break;
				}
			}
		} else {
			while ( (c = f.read()) > 0 ) 
				baos.write(c);
		}
	} catch ( EOFException e ) {
		c = -1;
	}
	return ( c < 0 && baos.size() == 0 )? 
		(LuaValue) NIL:
		(LuaValue) LuaString.valueUsing(baos.toByteArray());
}
 
Example #11
Source File: FuncState.java    From HtmlNative with Apache License 2.0 6 votes vote down vote up
static int singlevaraux(FuncState fs, LuaString n, expdesc var, int base) {
	if (fs == null)   /* no more levels? */
		return LexState.VVOID;  /* default is global */
	int v = fs.searchvar(n); /* look up at current level */
	if (v >= 0) {
		var.init(LexState.VLOCAL, v);
		if (base == 0)
			fs.markupval(v); /* local will be used as an upval */
		return LexState.VLOCAL;
	} else { /* not found at current level; try upvalues */
	    int idx = fs.searchupvalue(n);  /* try existing upvalues */
	    if (idx < 0) {  /* not found? */
	        if (singlevaraux(fs.prev, n, var, 0) == LexState.VVOID) /* try upper levels */
	          return LexState.VVOID;  /* not found; is a global */
	        /* else was LOCAL or UPVAL */
	        idx  = fs.newupvalue(n, var);  /* will be a new upvalue */
	    }
	    var.init(LexState.VUPVAL, idx);
	    return LexState.VUPVAL;
	}
}
 
Example #12
Source File: StringLib.java    From HtmlNative with Apache License 2.0 6 votes vote down vote up
/** Perform one-time initialization on the library by creating a table
 * containing the library functions, adding that table to the supplied environment,
 * adding the table to package.loaded, and returning table as the return value.
 * Creates a metatable that uses __INDEX to fall back on itself to support string
 * method operations.
 * If the shared strings metatable instance is null, will set the metatable as
 * the global shared metatable for strings.
 * <P>
 * All tables and metatables are read-write by default so if this will be used in 
 * a server environment, sandboxing should be used.  In particular, the 
 * {@link LuaString#s_metatable} table should probably be made read-only.
 * @param modname the module name supplied if this is loaded via 'require'.
 * @param env the environment to load into, typically a Globals instance.
 */
public LuaValue call(LuaValue modname, LuaValue env) {
	LuaTable string = new LuaTable();
	string.set("byte", new byte_());
	string.set("char", new char_());
	string.set("dump", new dump());
	string.set("find", new find());
	string.set("format", new format());
	string.set("gmatch", new gmatch());
	string.set("gsub", new gsub());
	string.set("len", new len());
	string.set("lower", new lower());
	string.set("match", new match());
	string.set("rep", new rep());
	string.set("reverse", new reverse());
	string.set("sub", new sub());
	string.set("upper", new upper());
	LuaTable mt = LuaValue.tableOf(
			new LuaValue[] { INDEX, string });
	env.set("string", string);
	env.get("package").get("loaded").set("string", string);
	if (LuaString.s_metatable == null)
		LuaString.s_metatable = mt;
	return string;
}
 
Example #13
Source File: LexState.java    From luaj with MIT License 6 votes vote down vote up
void forstat(int line) {
	/* forstat -> FOR (fornum | forlist) END */
	FuncState fs = this.fs;
	LuaString varname;
	BlockCnt bl = new BlockCnt();
	fs.enterblock(bl, true); /* scope for loop and control variables */
	this.next(); /* skip `for' */
	varname = this.str_checkname(); /* first variable name */
	switch (this.t.token) {
	case '=':
		this.fornum(varname, line);
		break;
	case ',':
	case TK_IN:
		this.forlist(varname);
		break;
	default:
		this.syntaxerror(LUA_QL("=") + " or " + LUA_QL("in") + " expected");
	}
	this.check_match(TK_END, TK_FOR, line);
	fs.leaveblock(); /* loop scope (`break' jumps to this point) */
}
 
Example #14
Source File: StringLib.java    From XPrivacyLua with GNU General Public License v3.0 6 votes vote down vote up
/** Perform one-time initialization on the library by creating a table
 * containing the library functions, adding that table to the supplied environment,
 * adding the table to package.loaded, and returning table as the return value.
 * Creates a metatable that uses __INDEX to fall back on itself to support string
 * method operations.
 * If the shared strings metatable instance is null, will set the metatable as
 * the global shared metatable for strings.
 * <P>
 * All tables and metatables are read-write by default so if this will be used in 
 * a server environment, sandboxing should be used.  In particular, the 
 * {@link LuaString#s_metatable} table should probably be made read-only.
 * @param modname the module name supplied if this is loaded via 'require'.
 * @param env the environment to load into, typically a Globals instance.
 */
public LuaValue call(LuaValue modname, LuaValue env) {
	LuaTable string = new LuaTable();
	string.set("byte", new byte_());
	string.set("char", new char_());
	string.set("dump", new dump());
	string.set("find", new find());
	string.set("format", new format());
	string.set("gmatch", new gmatch());
	string.set("gsub", new gsub());
	string.set("len", new len());
	string.set("lower", new lower());
	string.set("match", new match());
	string.set("rep", new rep());
	string.set("reverse", new reverse());
	string.set("sub", new sub());
	string.set("upper", new upper());
	LuaTable mt = LuaValue.tableOf(
			new LuaValue[] { INDEX, string });
	env.set("string", string);
	env.get("package").get("loaded").set("string", string);
	if (LuaString.s_metatable == null)
		LuaString.s_metatable = mt;
	return string;
}
 
Example #15
Source File: StringLib.java    From luaj with MIT License 5 votes vote down vote up
public Varargs invoke(Varargs args) {
	int n = args.narg();
	byte[] bytes = new byte[n];
	for ( int i=0, a=1; i<n; i++, a++ ) {
		int c = args.checkint(a);
		if (c<0 || c>=256) argerror(a, "invalid value for string.char [0; 255]: " + c);
		bytes[i] = (byte) c;
	}
	return LuaString.valueUsing( bytes );
}
 
Example #16
Source File: DebugLib.java    From VideoOS-Android-SDK with GNU General Public License v3.0 5 votes vote down vote up
public Varargs invoke(Varargs args) {
    LuaValue func = args.checkfunction(1);
    int up = args.checkint(2);
    LuaValue value = args.arg(3);
    if (func instanceof LuaClosure) {
        LuaClosure c = (LuaClosure) func;
        LuaString name = findupvalue(c, up);
        if (name != null) {
            c.upValues[up - 1].setValue(value);
            return name;
        }
    }
    return NIL;
}
 
Example #17
Source File: LuaTest.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
@Test
public void testLuaReturnString() {
    final Globals theGlobals = new Globals();
    LuaC.install(theGlobals);
    final LuaValue chunk = theGlobals.load("return 'hello, world'");
    final LuaString theResult = chunk.call().strvalue();
    Assert.assertEquals("hello, world", theResult.tojstring());
}
 
Example #18
Source File: CoerceLuaToJava.java    From luaj with MIT License 5 votes vote down vote up
public Object coerce(LuaValue value) {
	if ( value.isnil() )
		return null;
	if ( targetType == TARGET_TYPE_STRING )
		return value.tojstring();
	LuaString s = value.checkstring();
	byte[] b = new byte[s.m_length];
	s.copyInto(0, b, 0, b.length);
	return b;
}
 
Example #19
Source File: BaseLib.java    From XPrivacyLua with GNU General Public License v3.0 5 votes vote down vote up
public Varargs invoke(Varargs args) {
	LuaValue tostring = globals.get("tostring"); 
	for ( int i=1, n=args.narg(); i<=n; i++ ) {
		if ( i>1 ) globals.STDOUT.print( '\t' );
		LuaString s = tostring.call( args.arg(i) ).strvalue();
		globals.STDOUT.print(s.tojstring());
	}
	globals.STDOUT.println();
	return NONE;
}
 
Example #20
Source File: LuaC.java    From luaj with MIT License 5 votes vote down vote up
public LuaString cachedLuaString(LuaString s) {
	LuaString c = (LuaString) strings.get(s);
	if (c != null) 
		return c;
	strings.put(s, s);
	return s;
}
 
Example #21
Source File: StringLib.java    From VideoOS-Android-SDK with GNU General Public License v3.0 5 votes vote down vote up
/**
 * string.rep (s, n)
 * <p>
 * Returns a string that is the concatenation of n copies of the string s.
 */
static Varargs rep(Varargs args) {
    LuaString s = args.checkstring(1);
    int n = args.checkint(2);
     byte[] bytes = new byte[s.length() * n];
    int len = s.length();
    for (int offset = 0; offset < bytes.length; offset += len) {
        s.copyInto(0, bytes, offset, len);
    }
    return LuaString.valueOf(bytes);
}
 
Example #22
Source File: LexState.java    From VideoOS-Android-SDK with GNU General Public License v3.0 5 votes vote down vote up
int registerlocalvar(LuaString varname) {
    FuncState fs = this.fs;
    Prototype f = fs.f;
    if (f.locvars == null || fs.nlocvars + 1 > f.locvars.length)
        f.locvars = LuaC.realloc(f.locvars, fs.nlocvars * 2 + 1);
    f.locvars[fs.nlocvars] = new LocVars(varname, 0, 0);
    return fs.nlocvars++;
}
 
Example #23
Source File: RedisBinding.java    From claudb with MIT License 5 votes vote down vote up
private LuaValue toLuaString(UnknownRedisToken value) {
  SafeString string = value.getValue();
  if (string == null) {
    return LuaValue.NIL;
  }
  return LuaString.valueOf(string.getBytes());
}
 
Example #24
Source File: LexState.java    From luaj with MIT License 5 votes vote down vote up
void gotostat(int pc) {
	int line = linenumber;
	LuaString label;
	int g;
	if (testnext(TK_GOTO))
		label = str_checkname();
	else {
		next();  /* skip break */
		label = LuaString.valueOf("break");
	}
	g = newlabelentry(dyd.gt =grow(dyd.gt, dyd.n_gt+1), dyd.n_gt++, label, line, pc);
	findlabel(g);  /* close it if label already defined */
}
 
Example #25
Source File: StringLib.java    From XPrivacyLua with GNU General Public License v3.0 5 votes vote down vote up
int match_capture( int soff, int l ) {
	l = check_capture( l );
	int len = clen[ l ];
	if ( ( s.length() - soff ) >= len &&
		 LuaString.equals( s, cinit[l], s, soff, len ) )
		return soff + len;
	else
		return -1;
}
 
Example #26
Source File: IoLib.java    From XPrivacyLua with GNU General Public License v3.0 5 votes vote down vote up
private Varargs ioread(File f, Varargs args) throws IOException {
	int i,n=args.narg();
	LuaValue[] v = new LuaValue[n];
	LuaValue ai,vi;
	LuaString fmt;
	for ( i=0; i<n; ) {
		item: switch ( (ai = args.arg(i+1)).type() ) {
			case LuaValue.TNUMBER:
				vi = freadbytes(f,ai.toint());
				break item;
			case LuaValue.TSTRING:
				fmt = ai.checkstring();
				if ( fmt.m_length == 2 && fmt.m_bytes[fmt.m_offset] == '*' ) {
					switch ( fmt.m_bytes[fmt.m_offset+1] ) {
					case 'n': vi = freadnumber(f); break item;
					case 'l': vi = freadline(f); break item;
					case 'a': vi = freadall(f); break item;
					}
				}
			default: 
				return argerror( i+1, "(invalid format)" ); 
		}
		if ( (v[i++] = vi).isnil() )
			break;
	}
	return i==0? NIL: varargsOf(v, 0, i);
}
 
Example #27
Source File: JseIoLib.java    From luaj with MIT License 5 votes vote down vote up
public void write(LuaString s) throws IOException {
	if ( os != null )
		os.write( s.m_bytes, s.m_offset, s.m_length );
	else if ( file != null )
		file.write( s.m_bytes, s.m_offset, s.m_length );
	else
		notimplemented();
	if ( nobuffer )
		flush();
}
 
Example #28
Source File: FuncState.java    From luaj with MIT License 5 votes vote down vote up
void checkrepeated (LexState.Labeldesc[] ll, int ll_n, LuaString label) {
	int i;
	for (i = bl.firstlabel; i < ll_n; i++) {
		if (label.eq_b(ll[i].name)) {
			String msg = ls.L.pushfstring(
                         "label '" + label + " already defined on line " + ll[i].line);
			ls.semerror(msg);
		}
	}
}
 
Example #29
Source File: DebugLib.java    From luaj with MIT License 5 votes vote down vote up
Varargs getLocal(int i) {
	LuaString name = getlocalname(i);
	if ( i >= 1 && i <= stack.length && stack[i-1] != null )
		return varargsOf( name == null ? NIL : name, stack[i-1] );
	else
		return NIL;
}
 
Example #30
Source File: StringLib.java    From HtmlNative with Apache License 2.0 5 votes vote down vote up
private static void addquoted(Buffer buf, LuaString s) {
	int c;
	buf.append( (byte) '"' );
	for ( int i = 0, n = s.length(); i < n; i++ ) {
		switch ( c = s.luaByte( i ) ) {
		case '"': case '\\':  case '\n':
			buf.append( (byte)'\\' );
			buf.append( (byte)c );
			break;
		default:
			if (c <= 0x1F || c == 0x7F) {
				buf.append( (byte) '\\' );
				if (i+1 == n || s.luaByte(i+1) < '0' || s.luaByte(i+1) > '9') {
					buf.append(Integer.toString(c));
				} else {
					buf.append( (byte) '0' );
					buf.append( (byte) (char) ('0' + c / 10) );
					buf.append( (byte) (char) ('0' + c % 10) );
				}
			} else {
				buf.append((byte) c);
			}
			break;
		}
	}
	buf.append( (byte) '"' );
}