88 lines
2.3 KiB
Lua
88 lines
2.3 KiB
Lua
CropController = {}
|
|
|
|
function CropController:new(t)
|
|
t = t or {}
|
|
setmetatable(t, self)
|
|
self.__index = self
|
|
return t
|
|
end
|
|
|
|
|
|
function CropController:toMatrix(str)
|
|
local matrix = {}
|
|
assert(type(str) == "string")
|
|
assert(str:sub(1,1) == "{", "the string must begin with a \"{\"")
|
|
local len = str:len()
|
|
assert(str:sub(len,len) == "}", "the string must end with a \"}\"")
|
|
local s1, ob = str:gsub("{", "{")
|
|
local s2, cb = str:gsub("}", "}")
|
|
assert(ob == cb, "the string must have the same amount of opening brackets as closing brackets")
|
|
|
|
str = str:sub(2, len - 1)
|
|
len = len - 2
|
|
if ob == 1 then
|
|
return self:toArray(str)
|
|
else
|
|
local level = 0
|
|
local lastC = 0
|
|
for i = 1, len do
|
|
local c = str:sub(i,i)
|
|
if c == "{" then
|
|
level = level + 1
|
|
elseif c == "}" then
|
|
level = level - 1
|
|
elseif c == "," then
|
|
if level == 0 then
|
|
matrix[#matrix+1] = self:toMatrix(str:sub(lastC + 1, i - 1))
|
|
lastC = i
|
|
end
|
|
end
|
|
end
|
|
matrix[#matrix+1] = self:toMatrix(str:sub(lastC + 1, len))
|
|
return matrix
|
|
end
|
|
|
|
end
|
|
|
|
function CropController:toArray(str)
|
|
local len = str:len()
|
|
local comma = str:find(",")
|
|
local arr = {}
|
|
while(type(comma)=="number") do
|
|
arr[#arr+1] = str:sub(1, comma-1)
|
|
local latest = tonumber(arr[#arr])
|
|
if(latest ~= nil) then
|
|
arr[#arr] = latest
|
|
end
|
|
str = str:sub(comma + 1, len)
|
|
len = str:len()
|
|
comma = str:find(",")
|
|
end
|
|
if(str ~= "") then
|
|
arr[#arr+1] = str
|
|
local latest = tonumber(arr[#arr])
|
|
if(latest ~= nil) then
|
|
arr[#arr] = latest
|
|
end
|
|
end
|
|
return arr
|
|
end
|
|
|
|
function CropController:sendMessage(id, message, protocol)
|
|
rednet.send(id, message, protocol)
|
|
local id2, message2 = rednet.receive("received", 1)
|
|
return message == message2
|
|
end
|
|
|
|
function CropController:doAction(id, message, protocol)
|
|
self:sendMessage(id, message, protocol)
|
|
local id2, message2, protocol2
|
|
repeat
|
|
id2, message2, protocol2 = rednet.receive()
|
|
until id2 == id
|
|
return protocol2 == "confirm", message2
|
|
end
|
|
|
|
function CropController:setSlaveID(id)
|
|
self.slaveID = id
|
|
end |