Beispiel #1
0
// Encodes a lua value, only bool, number, nil, table, and string can be
// encoded.  If an unencodable value is encountered an error will be
// returned.
func LuaEncodeValue(w io.Writer, L *lua.State, index int) error {
	var err1, err2, err3 error
	switch {
	case L.IsBoolean(index):
		err1 = binary.Write(w, binary.LittleEndian, luaEncBool)
		var v byte = 0
		if L.ToBoolean(index) {
			v = 1
		}
		err2 = binary.Write(w, binary.LittleEndian, v)
	case L.IsNumber(index):
		err1 = binary.Write(w, binary.LittleEndian, luaEncNumber)
		err2 = binary.Write(w, binary.LittleEndian, L.ToNumber(index))
	case L.IsNil(index):
		err1 = binary.Write(w, binary.LittleEndian, luaEncNil)
	case LuaIsEntity(L, index):
		err1 = binary.Write(w, binary.LittleEndian, luaEncEntity)
		L.PushString("id")
		L.GetTable(index - 1)
		err2 = binary.Write(w, binary.LittleEndian, uint64(L.ToInteger(-1)))
		L.Pop(1)
	case L.IsTable(index):
		err1 = binary.Write(w, binary.LittleEndian, luaEncTable)
		err2 = LuaEncodeTable(w, L, index)
	case L.IsString(index):
		err1 = binary.Write(w, binary.LittleEndian, luaEncString)
		str := L.ToString(index)
		err2 = binary.Write(w, binary.LittleEndian, uint32(len(str)))
		err3 = binary.Write(w, binary.LittleEndian, []byte(str))
	default:
		return errors.New(fmt.Sprintf("Cannot encode lua type id == %d.", L.Type(index)))
	}
	switch {
	case err1 != nil:
		return err1
	case err2 != nil:
		return err2
	case err3 != nil:
		return err3
	}
	return nil
}