I'm used to using C but I'm new to Lua. Is there a way to create a Lua program that can read example.exe and give me the program's code in hexadecimal?
Until Lua 5.1, this sample program xd.lua was included in the distribution:
-- hex dump
-- usage: lua xd.lua < file
local offset=0
while true do
local s=io.read(16)
if s==nil then return end
io.write(string.format("%08X ",offset))
string.gsub(s,"(.)",
function (c) io.write(string.format("%02X ",string.byte(c))) end)
io.write(string.rep(" ",3*(16-string.len(s))))
io.write(" ",string.gsub(s,"%c","."),"\n")
offset=offset+16
end
Another possibility:
local filename = arg[1]
if filename == nil then
print [=[
Usage: dump <filename> [bytes_per_line(16)]]=]
return
end
local f = assert(io.open(filename, 'rb'))
local block = tonumber(arg[2]) or 16
while true do
local bytes = f:read(block)
if not bytes then return end
for b in bytes:gmatch('.') do
io.write(('%02X '):format(b:byte()))
end
io.write((' '):rep(block - bytes:len() + 1))
io.write(bytes:gsub('%c', '.'), '\n')
end
Related
in ZeroBrane Studio if I use "Project - complile (F7)" - what exactly does happen?
Will there be a standalone .exe created from my Lua code ?
And if so - in which directory ?
I use Windows 10.
(Couldn't find any information in the documention)
From what I see by a quick look into the source code it simply checks whether the code has any errors by loading it using loadstring which compiles the file.
There is no output file, just some text output about any errors.
But that's just an assumption. Feel free to check if this is actually the function called when you click that button.
https://github.com/pkulchenko/ZeroBraneStudio/blob/5daf55d79449431ca9794f6b8a65476dc203b780/src/editor
function CompileProgram(editor, params)
local params = {
jumponerror = (params or {}).jumponerror ~= false,
reportstats = (params or {}).reportstats ~= false,
keepoutput = (params or {}).keepoutput,
}
local doc = ide:GetDocument(editor)
local filePath = doc:GetFilePath() or doc:GetFileName()
local loadstring = loadstring or load
local func, err = loadstring(StripShebang(editor:GetTextDyn()), '#'..filePath)
local line = not func and tonumber(err:match(":(%d+)%s*:")) or nil
if not params.keepoutput then ClearOutput() end
compileTotal = compileTotal + 1
if func then
compileOk = compileOk + 1
if params.reportstats then
ide:Print(TR("Compilation successful; %.0f%% success rate (%d/%d).")
:format(compileOk/compileTotal*100, compileOk, compileTotal))
end
else
ide:GetOutput():Activate()
ide:Print(TR("Compilation error").." "..TR("on line %d"):format(line)..":")
ide:Print((err:gsub("\n$", "")))
-- check for escapes invalid in LuaJIT/Lua 5.2 that are allowed in Lua 5.1
if err:find('invalid escape sequence') then
local s = editor:GetLineDyn(line-1)
local cleaned = s
:gsub('\\[abfnrtv\\"\']', ' ')
:gsub('(\\x[0-9a-fA-F][0-9a-fA-F])', function(s) return string.rep(' ', #s) end)
:gsub('(\\%d%d?%d?)', function(s) return string.rep(' ', #s) end)
:gsub('(\\z%s*)', function(s) return string.rep(' ', #s) end)
local invalid = cleaned:find("\\")
if invalid then
ide:Print(TR("Consider removing backslash from escape sequence '%s'.")
:format(s:sub(invalid,invalid+1)))
end
end
if line and params.jumponerror and line-1 ~= editor:GetCurrentLine() then
editor:GotoLine(line-1)
end
end
return func ~= nil -- return true if it compiled ok
end
I want to print my parsing value at Luci.
Here is my code.
local val = {}
mm = Map("test", translate("For TEST"))
test=mm:section(TypedSection, "test", translate("TEST"))
test.anonymous = true
test.addremove = false
rssis = test:option(DummyValue, "rssi", translate("RSSI"))
t = test:option(DummyValue, "tx", translate("TX"))
r = test:option(DummyValue, "rx", translate("RX"))
local f = io.popen("iwpriv wlan0 stat")
for line in f:lines() do
for s in line:gmatch("(%S+)%s") do
table.insert(val, s)
end
for i, v in ipairs(val) do
end
end
f:close()
rssis:value(val[35])
if val[41] == "6M" then
t:value(val[41], translate("Disconnect"))
else
t:value(33, translate("Good"))
end
if val[49] == "6M" then
r:value(val[49], translate("DIsconnect"))
else
r:value(33, translate("GOOD"))
end
return mm
I saw the DummyValue which Creates a readonly field in the form.
So I used it instead of print function.
However it has errors "attempt to index global 'rssis' (a nil value)"
Only in lua file(not used for Luci) If i used the print function, it has no error. Does Luci has print function?
There is a luci.util.perror("blah blah") function that prints to the syslog.
you can then use the shell command "logread" to display in a console.
I guess this is what you need to debug your code.
I'm trying to get the name of all the file saved in two folders, the name are saved as :
1.lua 2.lua 3.lua 4.lua and so on
the folders name are :
first folder : "/const/"
second folder: "/virt/"
what I'm trying to do is only get the number of the files and this works but not in the right order, when I get the 17 file for example I get the 17th delivered from the function before the 15 and this causes for me a problem here the code of the function that I'm using :
local virt_path = "/virt/"
local const_path = "/const"
local fs = require "lfs"
local const = {}
for num = 1, (numberoffile)do -- numberoffile is predfined and can't be change
const[num] = assert(
dofile (const_path .. mkfilename(num)),
"Failed to load constant ".. num ..".")
end
local function file_number() --this is the function that causes me a headach
local ci, co, num = ipairs(const)
local vi, vo, _ = fs.dir(virt_path)
local function vix(o)
local file = vi(o)
if file == nil then return nil end
local number = file:match("^(%d+).lua$")
if number == nil then return vix(o) end
return tonumber(number)
end
local function iter(o, num)
return ci(o.co, num) or vix(o.vo, num)
end
return iter, {co=co, vo=vo}, num
end
As I said the function delive the need return values but not the right Arithmetic order.
any idea what I'm doing wrong here ?
I use my path[1] library.
1 We fill table with filenames
local t = {}
for f in path.each("./*.lua", "n") do
t[#t + 1] = tonumber((path.splitext(f)))
end
table.sort(t)
for _, i in ipairs(t) do
-- do work
end
2 We check if files exists
for i = 1, math.huge do
local p = "./" .. i .. ".lua"
if not path.exists(p) then break end
-- do work
end
[1] https://github.com/moteus/lua-path
I am trying to run a redis lua mock project to test my redis lua code. but obviously, there are bugs in the redis-mock project.
When I call redis.call('hget', 'foo', 'bar') in my test code, the redis mock throw an assert error at hash.lua#22 which is call from RedisLua.lua#20
-- RedisLua.lua
local call = function(self)
return (function(cmd, ...)
cmd = string.lower(cmd)
local arg = {...}
local ret = self.db[cmd](self.db, unpack(arg)) -- line 20
if self.RedisLua_VERBOSE then
print(cmd .. "( " .. table.concat(arg, " ") .. " ) === ".. tostring(ret))
end
return ret
end)
end
-- hash.lua
function RedisDb:hget(self,k,k2)
assert((type(k2) == "string")) -- # line 22
local x = RedisDb.xgetr(self,k,"hash")
return x[k2]
end
After trace, I found, the self is 'foo', the k is 'bar' and the k2 is actually nil, How can I fix this bug, the k should be foo, and the k2 should be 'bar'
I think you need to call redis:call('hget', 'foo', 'bar') or equivalently redis.call(redis,'hget','foo','bar'), rather than redis.call('hget', 'foo', 'bar').
Answer my own question.
When define as :, no self need.
-- hash.lua
function RedisDb:hget(self,k,k2)
assert((type(k2) == "string")) -- # line 22
local x = RedisDb.xgetr(self,k,"hash")
return x[k2]
end
change to
-- hash.lua
function RedisDb:hget(k,k2)
assert((type(k2) == "string")) -- # line 22
local x = RedisDb:xgetr(k,"hash")
return x[k2]
end
I was wondering if there was a way to read data from a file or maybe just to see if it exists and return a true or false
function fileRead(Path,LineNumber)
--..Code...
return Data
end
Try this:
-- http://lua-users.org/wiki/FileInputOutput
-- see if the file exists
function file_exists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function lines_from(file)
if not file_exists(file) then return {} end
local lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- tests the functions above
local file = 'test.lua'
local lines = lines_from(file)
-- print all line numbers and their contents
for k,v in pairs(lines) do
print('line[' .. k .. ']', v)
end
You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.
local open = io.open
local function read_file(path)
local file = open(path, "rb") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content
end
local fileContent = read_file("foo.html");
print (fileContent);
Just a little addition if one wants to parse a space separated text file line by line.
read_file = function (path)
local file = io.open(path, "rb")
if not file then return nil end
local lines = {}
for line in io.lines(path) do
local words = {}
for word in line:gmatch("%w+") do
table.insert(words, word)
end
table.insert(lines, words)
end
file:close()
return lines;
end
There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.