Exit and Return in Proc TCL - return

I want to know the difference between Exit and Return inside a proc.
I have a script that contains a lot of proc, one of them uses exit and some value ex:
proc someProc {code} {
exit $code
}
and another one is like:
proc multiply {value} {
set number [expr {$value * 5}]
return $number
}
Does the exit stop the running script or what is the difference?

The exit command makes the current process stop. The running program will be gone afterwards (though the file containing the code will still be there). Its optional argument is the error code to hand to the OS; the default is zero, for no-error-at-all.
The return command makes the current procedure call stop. The optional argument provides a way to say what the result of the call to the procedure is; the default is the empty string (given that Tcl doesn't have NULL/null/nil/etc. at all).
Internally, exit does a system call to the “stop running this program” OS API, and return throws an exception that the general procedure management code transforms into the result of the call.

Related

Script returns a value in the stadout but not able to get value in return parameter

I am using the callexec function to call a python script. The python script returns a value in the stadout but I am not able to get the value in the return parameter. Is there a way to pass the value to the results variable?
The is the CANape script that I am using:
double err;
char result[];
err = CallExecutable("C:\\Program Files (x86)\\Python38-32\\python.exe", "C:\\Users\\XXXX\\Desktop\\Read_Current.py 1", 1, result);
print("%s", result);
Thanks in advance
The result buffer provided to CallExecutable will return the result of the exit code from the python program. The following python code if called will return 123 and that is what the value of result will be in your code above.
import sys
sys.exit(123)
If you are looking to pass data back from the python script I've done this using the function DLL mechanism (there is some demo code included with CANape for this). It involves a little C++ wrapper to interface with python or other languages.

how can i stop a lua function block/call mid execution

is there a way to stop a lua pcall to a lua function block from mid execution? Im using multiple threads and would be good to cancel a function mid-flight.
The simplest way is to call error('my message') as this will abort the execution and will return nil, 'my message' as the result of pcall(). If you want to abort a running coroutine (or a "main" chunk) from "outside", the only way to do it I know about without modifying Lua VM is to attach a debug hook to coroutine or the main chunk and call error() from that debug hook:
print(1)
local count = 0
debug.sethook(function(event, line)
if count > 1 then error('done', 2) end
count = count + 1
end, "l")
print(2)
print(3)
print("not getting here")
You should see something like this:
1
2
3
script.lua:4: done
In the case of pcall, you will see the parameter of the error() call to be passed as the error message by pcall.
The conditions to check can get quite elaborate; for example, you can check for the hook to be called from a particular function with a certain number of commands executed before aborting.

Optimizing Lua for cyclic execution

I'm exeucting my Lua script once per program cycle of 10 ms. using the same Lua_state (luaL_newstate called once in my app)
Calling luaL_loadbuffer complies the script very fast for sure, still it seems unneccessary to do this every time the script is executed since the script does not change.
Tried to save binary using lua_dump() and then execute it, but lua_pcall() didn't accept the binary for some reason.
Any ideas on how to optimize? (LuaJIT is not an unfortenately an option here)
Jan
You're correct, if the code is not changing, there is no reason to reprocess the code. Perhaps you could do something like the following:
luaL_loadbuffer(state, buff, len, name); // TODO: check return value
while (true) {
// sleep 10ms
lua_pushvalue(state, -1); // make another reference to the loaded chunk
lua_call(state, 0, 0);
}
You'll note that we simply duplicate the function reference on the top of the stack, since lua_call removes the function that it calls from the stack. This way, you do not lose a reference to the loaded chunk.
Executing the loadbuffer compiles the script into a chunk of lua code, which you can treat as an anonymous function. The function is put at the top of the stack. You can "save" it the way you would any other value in Lua: push a name for the function onto the stack, then call lua_setglobal(L, name). After that, every time you want to call your function (the chunk), you push it onto the Lua stack, push the parameters onto the stack, and call lua_pcall(L, nargs, nresults). Lua will pop the function and put nresults results onto the stack (regardless of how many results are returned by your function -- if more are returned they are discarded, if fewer then the extras are nil). Example:
int stat = luaL_loadbuffer(L, scriptBuffer, scriptLen, scriptName);
// check status, if ok save it, else handle error
if (stat == 0)
lua_setglobal(L, scriptName);
...
// re-use later:
lua_getglobal(L, scriptName);
lua_pushinteger(L, 123);
stat = lua_pcall(L, 1, 1, 0);
// check status, if ok get the result off the stack

How to exit a Lua script's execution?

I want to exit execution of Lua script on some condition .
Example :
content = get_content()
if not content then
-- ( Here i want some kind of exit function )
next_content = get_content()
--example there can lot of further checks
Here I want that if I am not getting content my script suppose to terminate is should not go to check to next.
Use os.exit() or just return from some "main" function if your script is embedded.
os.exit()
kill process by sending a signal
do return end
stop execution
The two methods are not equal if you want to write and execute some luacode in the interpreter after stopping the execution by launching your program using the -i flag.
th -i main.lua
extract from the lua api doc :
For syntactic reasons, a break or return can appear only as the last statement of a block (in other words, as the last statement in your chunk or just before an end, an else, or an until). For instance, in the next example, break is the last statement of the then block.
local i = 1
while a[i] do
if a[i] == v then break end
i = i + 1
end
Usually, these are the places where we use these statements, because any other statement following them is unreachable. Sometimes, however, it may be useful to write a return (or a break) in the middle of a block; for instance, if you are debugging a function and want to avoid its execution. In such cases, you can use an explicit do block around the statement:
function foo ()
return --<< SYNTAX ERROR
-- `return' is the last statement in the next block
do return end -- OK
... -- statements not reached
end
In lua 5.2.0-beta-rc1+, you can add a label at the end of your code called ::exit:: or something of the like, and then whenever you need to exit the program just call it like this:
goto exit

Why is 'name' nil for debug.getinfo(1)

I'm trying to put together a lua testing framework that lets you know the function that had the problem, but when I switched from loadstring to _G, (I switched so my test harness could see the results of the function call) my functions started using 'nil' for the function name
Why can _G not detect the name of the current function in the following code? Also, how can I get the return results from loadstring (ie the 'false' from the blah call) or set the function name when using _G (ie. Tell the lua interpreter what the function name should be)?
function run_test(one, two)
if one ~= two then
print(debug.getinfo(2).name..' Failed')
end
end
function blah()
run_test(false, true)
return false
end
local fname = 'blah'
local status, result = pcall(_G[fname]) -- Outputs 'nil'; result is 'false'
local status, result = pcall(loadstring(fname..'()')) -- Outputs 'blah', result is 'nil'
The main thing I need is a way to call a function using a string of the function name, be able to see the function name inside the call (for test failures to point to the function that failed, like fname = 'blah' in the code above) and be able to get the return value
local fname = 'blah'
status, result = pcall(??Call fname somehow??)
assert(status)
assert(not result)
--stdout should be "blah Failed"
This is a limitation of the heuristics used by Lua to provide names for functions.
In Lua, all functions are anonymous. A given function can be the value of several variables: global, local, and table fields. The Lua debug system tries to find a reasonable name for a value based on where it came from by looking into the bytecode being executed.
Consider the simpler example
blah()
pcall(blah)
In the first call, the debug system sees that the function being called comes from the global blah and debug.getinfo(1).name gives the expected result, blah.
In the second call, the debug system sees that the function being called comes from the first argument to pcall but it does not look further to see where that argument came from, and debug.getinfo(1).name gives nil.
The same thing happens when you call _G[name](). All the debug system sees is a field of a table and the name of the field is too far off.
Try adding print(debug.traceback()) as the first line of blah to see another take on this explanation.

Resources