From ef3016eff014678e97bfe85bf0374eea5d7c2c55 Mon Sep 17 00:00:00 2001 From: Andrew Tridgell Date: Sat, 26 Nov 2022 11:37:01 +1100 Subject: [PATCH] AP_Scripting: added a simple example of the load() function --- libraries/AP_Scripting/examples/test_load.lua | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 libraries/AP_Scripting/examples/test_load.lua diff --git a/libraries/AP_Scripting/examples/test_load.lua b/libraries/AP_Scripting/examples/test_load.lua new file mode 100644 index 0000000000..2b4fd627b4 --- /dev/null +++ b/libraries/AP_Scripting/examples/test_load.lua @@ -0,0 +1,34 @@ +--[[ + test the load function for loading new code from strings +--]] + +gcs:send_text(0,"Testing load() method") + +-- a function written as a string. This could come from a file +-- or any other source (eg. mavlink) +-- Note that the [[ xxx ]] syntax is just a multi-line string +local func_str = [[ +function TestFunc(x,y) + return math.sin(x) + math.cos(y) +end +]] + +function test_load() + -- load the code into the global environment + local f,errloc,err = load(func_str,"TestFunc", "t", _ENV) + if not f then + gcs:send_text(0,string.format("Error %s: %s", errloc, err)) + return + end + -- run the code within a protected call to catch any errors + local success, err = pcall(f) + if not success then + gcs:send_text(0, string.format("Failed to load TestFunc: %s", err)) + return + end + + -- we now have the new function + gcs:send_text(0, string.format("TestFunc(3,4) -> %f", TestFunc(3,4))) +end + +test_load()