Console Lua
Console Lua
function console:new( x, y)
--libs
utf8 = require 'utf8'
--tables
self.meta = {}
self.meta.x, self.meta.y, self.meta.w, self.meta.h, self.meta.r = x or 0, y or
0 , 512, 256, 20
self.meta.text = {}
self.meta.font = love.graphics.newFont( 16, 'mono')
self.meta.commands = { { name = "help";
func = function()
console:print( "command list:")
for i, command in ipairs(self.meta.commands) do
if command.description ~= nil then
console:print( command.name .. ": " .. command.description)
end
end
end
};
{ name = "echo";
description = "A simple text command.";
func = function(...)
local tkns = cpack({...})
function console:render()
local textY = self.meta.y + self.meta.h - 48 --the y text position
--button
console:drawButton( "open Console", { love.graphics.getWidth() - 96; 0; 96;
32}, { 100; 100; 100; 50})
--button
console:drawButton( "send", {self.meta.x + self.meta.w - 48;
self.meta.y + self.meta.h - 30; 32; 18}, { 100; 100; 100})
textY = textY - 16
end
love.graphics.setColor( 1, 1, 1)
end
end
function console:update()
--console
if #self.meta.text > 12 then
table.remove( self.meta.text, #self.meta.text)
end
if self.openConsole then
if isTouchOnButton({ self.meta.x + self.meta.w - 48; self.meta.y +
self.meta.h - 30; 48; 30}) then
if self.input ~= "" then
console:print(self.input)
console:run(self.input)
end
self.input = ""
elseif isTouchOnButton({ self.meta.x + 16 + self.meta.font:getWidth("C//:
"); self.meta.y + self.meta.h - 28; self.meta.w - 50, 24}) then
love.keyboard.setTextInput(true)
end
end
end
function console:keypressed(k)
if k == "backspace" then
local byteoffset = utf8.offset( self.input, -1)
if byteoffset then
self.input = string.sub( self.input, 1, byteoffset - 1)
end
end
end
function console:keyboard(t)
self.input = self.input .. t
end
function console:run(cmd)
local token = tokenize( cmd, " ")
msg = {}
msg.text = tostring(text) --text to print on console
msg.type = 'colored' --if is colored or no
msg.colors = { (colors[1] or 0) / 255; (colors[2] or 0) / 255; (colors[3] or 0)
/ 255} --text color
if self.consolePlay then
table.insert( self.meta.text, 1, msg)
end
end
--especial functions
function isTouchOnButton(object)
local touches = love.touch.getTouches()
if tx >= object[1] and tx <= object[1] + object[3] and ty >= object[2] and
ty <= object[2] + object[4] then
return true,
love.timer.sleep(1 / 12)
end
end
end
return t
end
function cunpack(s)
assert(type(s) == "string", "Can only TSerial.unpack strings.")
assert(loadstring("ctable="..s))()
local t = ctable
ctable = nil
return t
end
return console