I am trying to assign the output of a function to a variable, but I can’t do it. :(
I use Lua 5.3.4 and luarocks 3.2.1 (+luasql-postgres)
My script:
luasql = require "luasql.postgres"
value=arg[1]
current_time=os.date("%Y-%m-%d %H:%M:%S")
env = luasql.postgres()
con = assert (env:connect('postgres', 'postgres', 'postgres', '192.168.241.93','5432'))
function printvalues(res)
row = res:fetch ({}, "a")
while row do
print(string.format("%-12s", row.client_addr))
row = res:fetch (row, "a")
end
print()
end
res = assert (con:execute('select client_addr from pg_stat_replication order by replay_lag asc limit 1'))
--txn = res
a = {myfunc = printvalues(res)}
if a == '192.168.242.41' then
print("backend1")
elseif a == '192.168.241.76' then
print("backend2")
end
print(string.format("%-12s",a))
print(a)
Script result:
root@haproxy:/etc/haproxy# lua scripts/test.lua
192.168.1.76
table: 0x559fadf97080
table: 0x559fadf97080
Please tell me:
How can I assign the result of a function to a variable?
How to remove the empty line in the output of the function printvalues(res)
return
statement in the function body to return a valueprint()
statement in the functionprintvalues
I see you are making a query using
limit 1
, since you will only get one value, thewhile
loop statement is useless.I hope this works for you
but if you want an example with function:
try to use
local
keyword before variables, this will make them scope variables