Answer the question
In order to leave comments, you need to log in
How to put a set of commands into a separate function in lua?
There is this code in lua:
require('sem')
semaphore = sem.open('RS485-3')
timeout = 10 * 2
while not semaphore:trywait() and timeout > 0 do
sleep(0.5)
timeout = timeout - 1
end
semaphore:post()
sem_local:close()
function semaphore_manager:wait(name)
require('sem')
semaphore = sem.open(name)
timeout = 10 * 2
while not semaphore:trywait() and timeout > 0 do
sleep(0.5)
timeout = timeout - 1
end
return semaphore
end
function semaphore_manager:wait(sem_local)
sem_local:post()
sem_local:close()
end
function modbus(action, slave)
if (action == 'connect') then
require('luamodbus')
mb = luamodbus.rtu()
mb:open('/dev/RS485-3', 115200, 'N', 8, 1, 'H')
mb:connect()
mb:setslave(slave)
local amount, modbus_error = mb:readregisters(1)
return amount, modbus_error
elseif (action == 'disconnect') then
mb:close()
end
end
count_sensors, m_error = modbus('connect', slave_devices[i])
modbus('disconnect')
Answer the question
In order to leave comments, you need to log in
1) for starters, you should not call require
inside functions.
2) further, don't pollute the global space (and tell the author of the 'sem' module about the same if its module can only export to the global space, and not return a method table).
3) (variation of item 2) use local variables as often as possible, especially inside functions. Use globals only where absolutely necessary. Otherwise, you will run into sudden collisions.
4) I have, in general, a lot of complaints about your code in both inserts. From their number, I just want to take and rewrite, without explaining anything, and then answer all questions about why this is so :)
5)
Am I doing the right thing
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question