Passing session between two lua files - lua

I want to call another lua script from my main script say like
session:execute("lua","/path/somefile.lua "..somearg1.." "..somearg2..)
its working fine and somefile.lua is executing but suppose i also want to use session there i.e. i am accessing a database in somefile.lua and want to speak a query result in somefile.lua by using session. (session:speak(queryResult)).
i also tried sending session as one of argument
session:execute("lua","/path/somefile.lua "..session)
but it gives a error "attempt to concatenate global 'session' (a userdata value)"
any advise..??
code of first lua file
session:answer();
session:setAutoHangup(false);
session:set_tts_params("flite","kal");
callerId = session:getVariable("caller_id_number");
session:execute("lua ","/etc/freeswitch/scripts/checkbal.lua "..callerId.." "..session);
session:destroy();
code for 2nd lua file
callerId=argv[1];
session=argv[2];
luasql = require "luasql.postgres";
env=assert(luasql:postgres());
con=assert(env:connect("mydb","postgres","password","127.0.0.1","5432"));
cur=assert(con:execute("select balance from bal where number='"..callerId.."'"));
session:set_tts_params("flite","kal");
row=cur:fetch({},"a");
res=row.balance;
session:speak(res);

Rig your second file to be a module that returns a function or a table of functions. Here is an example that has second file return a "speak" function that you can then re-use as many times as desired:
Code of first Lua file:
session:answer()
session:setAutoHangup(false)
session:set_tts_params("flite","kal")
callerId = session:getVariable("caller_id_number")
speak = require 'checkbal'
speak(session, callerId)
-- session:execute("lua ","/etc/freeswitch/scripts/checkbal.lua "..callerId.." "..session)
session:destroy()
Code for 2nd Lua file:
luasql = require "luasql.postgres"
local env=assert(luasql:postgres())
local con=assert(env:connect("mydb","postgres","password","127.0.0.1","5432"))
local function speak(session, callerId)
local cur = assert(con:execute("select balance from bal where number='"..callerId.."'"))
session:set_tts_params("flite","kal")
row=cur:fetch({},"a")
res=row.balance
session:speak(res)
end
return speak
Note: this is Lua: no need for semicolons.
I would consider making "session" an object (table with methods) with a "speak" method, but this is going beyond scope of this question and is not necessary, may just lead to more maintainable code later.

Related

FiveM lua: spoof source

RegisterServerEvent('XD')
AddEventHandler('XD', function()
print(source)
end)
TriggerServerEvent("XD")
is there a way to spoof your source from the server when you trigger an event.
i though of doing this when you trigger
TriggerServerEvent("XD", source = '200' -- [[this is the source the server will think you are]])
Lua is a language of reference. If Lua cannot see something, it cannot use it.
Typically, as a rule of thumb: if you do not define the variable, you cannot use it. There are exceptions to this, which are the functions that the global variable provides to you, like print.
We also see another issue: you try to define source like a table, but you don't give it a table to rest in.
There are two ways to solve this problem.
#1. Give source it's own argument
Remove source and add source as a argument to function(...)
Server:
RegisterServerEvent('XD')
AddEventHandler('XD', function(source)
print(source)
end)
Client:
TriggerServerEvent("XD", '200')
#2. Create a table for source to hang out in
To start with, give the TriggerServerEvent a nice cozy table.
TriggerServerEvent("XD", {} )
Then put source into it.
TriggerServerEvent("XD", { source = '200' })
Now, on the server, we need an argument for the table:
RegisterServerEvent('XD')
AddEventHandler('XD', function(args)
print(args)
end)
However, since args is a table, and we want source, we have to index it.
RegisterServerEvent('XD')
AddEventHandler('XD', function(args)
print(args.source) -- or args["source"]
end)

How to get the value from SPOP safely and test for value or null

I am currently doing 2 steps in my code and I just realized I can combine both steps in a LUA script.
I am doing:
SPOP on my set
calling a lua script to do other things.
The value from step#1 is being passed and stored in the local variable ele.
My lua script looks like:
local ele = KEYS[1]
local p = KEYS[2]
local u = KEYS[3]
if redis.call("SISMEMBER", u, ele) == 0 then
..
..
return "OK"
else
return "EXISTS"
end
How can I call SPOP from inside my lua script and store it in a variable.
I need to do:
local popped = redis.call("SPOP", "my-set-here")
I'm not sure if that will work, but then I have to check if it is null or has a value I guess. Just want to make sure I am following best practise.
BTW, as a side note, what is the fastest way to create and test lua scripts?
You can check the value of popped for non-nillness with something like:
if popped then
-- do something
end
As for developing Redis Lua scripts, have a look at Zerobrane's integration:
http://notebook.kulchenko.com/zerobrane/redis-lua-debugging-with-zerobrane-studio
https://redislabs.com/blog/zerobrane-studio-plugin-for-redis-lua-scripts/
Disclosure: I was involved in the integration effort ;)

In Lua, using a boolean variable from another script in the same project ends up with nill value error

This code is for a modding engine, Unitale base on Unity Written in Lua
So I am trying to use a Boolean Variable in my script poseur.lua, so when certain conditions are met so I can pass it to the other script encounter.lua, where a engine Predefined functions is being uses to make actions happens base on the occurring moment.
I tried to read the engine documentation multiple times, follow the exact syntax of Lua's fonction like GetVar(), SetVar(), SetGobal(),GetGlobal().
Searching and google thing about the Language, post on the subreddit and Game Exchange and tried to solve it by myself for hours... I just can't do it and I can't understand why ?
I will show parts of my codes for each.
poseur:
-- A basic monster script skeleton you can copy and modify for your own creations.
comments = {"Smells like the work\rof an enemy stand.",
"Nidhogg_Warrior is posing like his\rlife depends on it.",
"Nidhogg_Warrior's limbs shouldn't\rbe moving in this way."}
commands = {"GREET", "JUMP", "FLIRT", "CRINGE"}
EndDialougue = {" ! ! !","ouiii"}
sprite = "poseur" --Always PNG. Extension is added automatically.
name = "Nidhogg_Warrior"
hp = 99
atk = 1
def = 1
check = "The Nidhogg_Warrior is\rsearching for the Nidhogg"
dialogbubble = "rightlarge" -- See documentation for what bubbles you have available.
canspare = false
cancheck = true
GreetCounter = 5
Berserk = false
encounter:
-- A basic encounter script skeleton you can copy and modify for your own creations.
encountertext = "Nidhogg_Warrior is\rrunning frantically"
nextwaves = {"bullettest_chaserorb"}
wavetimer = 5.0
arenasize = {155, 130}
music = "musAncientGuardian"
enemies = {"poseur"}
require("Monsters.poseur")
enemypositions = {{0, 0}}
-- A custom list with attacks to choose from.
-- Actual selection happens in EnemyDialogueEnding().
-- Put here in case you want to use it.
possible_attacks = {"bullettest_bouncy", "bullettest_chaserorb", "bullettest_touhou"}
function EncounterStarting()
-- If you want to change the game state immediately, this is the place.
Player.lv = 20
Player.hp = 99
Player.name = "Teemies"
poseur.GetVar("Berserk")
end
Thank you for reading.
The answer to my problem was to use SetGobal(), GetGobal().
For some reasons my previous attempt to simply use SetGobal()Resulted in nil value despite writing it like that SetGobal("Berserk",true) gave me a nill value error, as soon as I launch the game.
But I still used them wrong. First I needed to put it SetGobal() at the end of the condition instead of at the start of the the poseur.lua script because the change of value... for some reasons was being overwritten by it first installment.
And to test the variable in the function in my encounter.lua, I needed to write it like that
function EnemyDialogueStarting()
-- Good location for setting monster dialogue depending on how the battle is going.
if GetGlobal("Jimmies") == true then
TEEEST()
end
end
Also any tips an suggestions are still welcome !
Well firstly, in lua simple values like bool and number are copied on assignment:
global={}
a=2
global.a=a--this is a copy
a=4--this change won't affect value in table
print(global.a)--2
print(a)--4
Secondly,
SetGobal and the other mentioned functions are not part of lua language, they must be related to your engine. Probably, they use word 'Global' not as lua 'global' but in a sense defined by engine.
Depending on the engine specifics these functions might as well do a deep copy of any variable they're given (or might as well not work with complicated objects).

Modify Lua Chunk Environment: Lua 5.2

It is my understanding that in Lua 5.2 that environments are stored in upvalues named _ENV. This has made it really confusing for me to modify the environment of a chunk before running it, but after loading it.
I would like to load a file with some functions and use the chunk to inject those functions into various environments. Example:
chunk = loadfile( "file" )
-- Inject chunk's definitions
chunk._ENV = someTable -- imaginary syntax
chunk( )
chunk._ENV = someOtherTable
chunk( )
Is this possible from within Lua? The only examples I can find of modifying this upvalue are with the C api (another example from C api), but I am trying to do this from within Lua. Is this possible?
Edit: I'm unsure of accepting answers using the debug library. The docs state that the functions may be slow. I'm doing this for efficiency so that entire chunks don't have to be parsed from strings (or a file, even worse) just to inject variable definitions into various environments.
Edit: Looks like this is impossible: Recreating setfenv() in Lua 5.2
Edit: I suppose the best way for me to do this is to bind a C function that can modify the environment. Though this is a much more annoying way of going about it.
Edit: I believe a more natural way to do this would be to load all chunks into separate environments. These can be "inherited" by any other environment by setting a metatable that refers to a global copy of a chunk. This does not require any upvalue modification post-load, but still allows for multiple environments with those function definitions.
The simplest way to allow a chunk to be run in different environments is to make this explicit and have it receive an environment. Adding this line at the top of the chunk achieves this:
_ENV=...
Now you can call chunk(env1) and later chunk(env2) at your pleasure.
There, no debug magic with upvalues.
Although it will be clear if your chunk contains that line, you can add it at load time, by writing a suitable reader function that first sends that line and then the contents of the file.
I do not understand why you want to avoid using the debug library, while you are happy to use a C function (neither is possible in a sandbox.)
It can be done using debug.upvaluejoin:
function newEnvForChunk(chunk, index)
local newEnv = {}
local function source() return newEnv end
debug.upvaluejoin(chunk, 1, source, 1)
if index then setmetatable(newEnv, {__index=index}) end
return newEnv
end
Now load any chunk like this:
local myChunk = load "print(x)"
It will initially inherit the enclosing _ENV. Now give it a new one:
local newEnv = newEnvForChunk(myChunk, _ENV)
and insert a value for 'x':
newEnv.x = 99
Now when you run the chunk, it should see the value for x:
myChunk()
=> 99
If you don't want to modify your chunk (per LHF's great answer) here are two alternatives:
Set up a blank environment, then dynamically change its environment to yours
function compile(code)
local meta = {}
local env = setmetatable({},meta)
return {meta=meta, f=load('return '..code, nil, nil, env)}
end
function eval(block, scope)
block.meta.__index=scope
return block.f()
end
local block = compile('a + b * c')
print(eval(block, {a=1, b=2, c=3})) --> 7
print(eval(block, {a=2, b=3, c=4})) --> 14
Set up a blank environment, and re-set its values with your own each time
function compile(code)
local env = {}
return {env=env, f=load('return '..code, nil, nil, env)}
end
function eval(block, scope)
for k,_ in pairs(block.env) do block.env[k]=nil end
for k,v in pairs(scope) do block.env[k]=v end
return block.f()
end
local block = compile('a + b * c')
print(eval(block, {a=1, b=2, c=3})) --> 7
print(eval(block, {a=2, b=3, c=4})) --> 14
Note that if micro-optimizations matter, the first option is about 2✕ as slow as the _ENV=... answer, while the second options is about 8–9✕ as slow.

Lua create multiple closure instances

I have some lua code in a file. I want to create multiple closure instances of this code, each with a different _ENV upvalue. I can use luaL_loadfile to load the file and set the first upvalue, N times with different tables, to create N instances. But wouldn't this load and compile the file N times?
The lua equivalent of what i want to do is the following, except without the loadfile
func_list = {}
for i = 1, 10 do
local new_env = {hello=i, print=print}
func_list[i] = loadfile("Code.lua", "t", new_env)
end
for i = 1, 10 do
func_list[i]()
end
------ Code.lua ------
print(hello*hello)
is there a better way to do this?
Whenever you load a string/file in Lua, what you get in return is a function to call to actually run the file. What load does for you is just some additional processing to set the _ENV.
However, nothing prevents you from setting _ENV yourself. You could do it with something like this:
-- Code.lua --
_ENV = ...
print(hello * hello)
Then, you could load/compile the file just once, and use multiple instances as such:
local code = loadfile("Code.lua")
env_list = {}
for i = 1, 10 do
local new_env = {hello=i, print=print}
code(new_env)
env_list[i] = new_env
end
If you do not want the user to write _ENV = ... in every file, you could instead load the file into a string, prepend the line yourself and use load to compile the source. But this would not work on compiled files.
Use the IO libraries to load the file into a string, and then call loadstring on it.
Alternatively, just get one chunk and then change it's env prior to executing it

Resources