lua-logic/sim/utility.lua
2022-11-04 19:03:19 -06:00

155 lines
2.4 KiB
Lua

bool_to_int = {[false] = 0, [true] = 1}
local escapes = {
{"\\", "b"},
{"\t", "t"},
{"\n", "n"},
{"\r", "r"},
{"\'", "a"},
{"\"", "q"},
{";" , "s"},
{":" , "c"},
}
function expandescape(str)
local ostrt = {}
local len = #str
for i=1, len do
local ci = str:sub(i, i)
local co = ci
for escidx, esc in ipairs(escapes) do
if ci==esc[1] then co = "\\"..esc[2] end
end
table.insert(ostrt, co)
end
return table.concat(ostrt)
end
function collapseescape(str)
local ostrt = {}
local i = 1
local len = #str
while i<=len do
local ci = str:sub(i, i)
local co = ci
if ci=="\\" and i<len then
i = i+1
ci = str:sub(i, i)
for escidx, esc in ipairs(escapes) do
if ci==esc[2] then co = esc[1] end
end
end
table.insert(ostrt, co)
i = i+1
end
return table.concat(ostrt)
end
function tobitstring(num, len)
local maxval = bit.lshift(1, len)
if num>=maxval then error("bitstring value too big") end
num = num%maxval
local bitstring = ""
for i = len, 1, -1 do
bitstring = bitstring..bit.rshift(bit.band(num, bit.lshift(1, i-1)), i-1)
end
return bitstring
end
function array_remove(array, len, value, pass)
for i = 0, len-1 do
local v = array[i]
if v==value then
array[i] = array[len-1]
array[len-1] = nil
len = len - 1
return len
end
end
if not pass then error("element not in array") end
return len
end
function array_add(array, len, value)
for i = 0, len-1 do
local v = array[i]
if v==value then return len end
end
array[len] = value
len = len + 1
return len
end
function round(x)
return math.floor(x+0.5)
end
local units = {
"uHz",
"mHz",
"Hz",
"kHz",
"MHz",
"GHz",
}
function unitize(v)
local unit = 1
v = v*1000000
while v >= 1000 do
v = v/1000
unit = unit+1
end
local s
if v >= 100 then
s = "" .. round(v/10)*10
elseif v >= 10 then
s = "" .. round(v)
elseif v >= 1 then
s = "" .. round(v*10)/10
if #s == 1 then s = s .. ".0" end
else
s = 0
end
return s .. " " .. units[unit]
end
function vectotable(vec)
local tbl = {}
for comp in string.gmatch(vec, "([^%s]+)") do
tbl[#tbl+1] = tonumber(comp)
end
return tbl
end
function tabletostring(table)
local str = tostring(table[1])
for i = 2, #table do
str = str .. " " .. tostring(table[i])
end
return str
end
function toboolean(value)
local num = tonumber(value)
if num == 1 then
return true
else
return false
end
end