### Install Prerequisites and Build PDFs Source: https://github.com/x-friese/flywithlua/blob/master/docs/README.md Installs necessary LaTeX packages on Ubuntu and then builds the PDF documentation, followed by a cleanup of intermediate files. ```bash # Install prerequisites (Ubuntu): $ sudo apt-get install texlive-latex-extra texlive-fonts-recommended texlive-latex-recommended make ``` ```bash $ makei && make clean # Build PDF files and then remove intermittient garbage LaTeX tends to produce. ``` -------------------------------- ### Install Required Software on Ubuntu Source: https://github.com/x-friese/flywithlua/blob/master/README.md Installs necessary build tools and libraries for compiling FlyWithLua on Ubuntu. ```bash sudo apt-get install -y --no-install-recommends build-essential cmake git freeglut3-dev libudev-dev libopenal-dev ``` -------------------------------- ### Install Required Software on Windows Source: https://github.com/x-friese/flywithlua/blob/master/README.md Installs Git, CMake, and MinGW using Chocolatey. Ensure you are using an admin command prompt. ```bash choco install git cmake choco install mingw --version 8.1.0 ``` -------------------------------- ### Example: Measure Elapsed Time Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/socket.html Demonstrates how to measure elapsed time using socket.gettime(). Capture the start time, perform operations, and then subtract the start time from the current time. ```lua t = socket.gettime() -- do stuff print(socket.gettime() - t .. " seconds elapsed") ``` -------------------------------- ### Install Windows Cross-Compiling Toolchain on Ubuntu Source: https://github.com/x-friese/flywithlua/blob/master/README.md Installs the MinGW-w64 cross-compiling toolchain on Ubuntu for building Windows executables. This is generally not recommended over native builds. ```bash # Install Windows cross-compiling toolchain (MinGW). sudo apt-get install -y --no-install-recommends mingw-w64 g++-mingw-w64 && apt-get clean ``` -------------------------------- ### Example: Base64 Encoding with Line Wrapping Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/mime.html Demonstrates chaining filters for Base64 encoding and line wrapping. ```APIDOC ## Example: Base64 Encoding with Line Wrapping ### Description This example shows how to create a filter chain for encoding binary data to Base64 and wrapping the output into lines of the correct size. ### Method `ltn12.filter.chain` combined with `mime.encode` and `mime.wrap` ### Endpoint N/A (Lua code example) ### Request Example ```lua local base64_encoder = ltn12.filter.chain( mime.encode("base64"), mime.wrap("base64") ) ``` ``` -------------------------------- ### Install OS X Cross-Compiling Toolchain Source: https://github.com/x-friese/flywithlua/blob/master/README.md Installs the necessary clang compiler and dependencies for cross-compiling on OS X. This script downloads and builds the osxcross toolchain. ```bash apt-get install -y --no-install-recommends clang curl && apt-get clean #Build arguments OSXCROSS_REPO="tpoechtrager/osxcross" OSXCROSS_REVISION="f4ba4facae996b3b14d89eb62c0384564f7368b5" DARWIN_SDK_VERSION="10.11" DARWIN_SDK_URL="https://github.com/apriorit/osxcross-sdks/raw/master/MacOSX10.11.sdk.tar.xz" CROSSBUILD=1 mkdir -p "/tmp/osxcross" \ && cd "/tmp/osxcross" \ && curl -sSLo osxcross.tar.gz "https://codeload.github.com/${OSXCROSS_REPO}/tar.gz/${OSXCROSS_REVISION}" \ && tar --strip=1 -xzf osxcross.tar.gz \ && rm -f osxcross.tar.gz \ && curl -sLo tarballs/MacOSX${DARWIN_SDK_VERSION}.sdk.tar.xz \ "${DARWIN_SDK_URL}" \ && UNATTENDED=1 JOBS=4 SDK_VERSION=${DARWIN_SDK_VERSION} ./build.sh \ && mv target /usr/osxcross \ && mv tools /usr/osxcross/ \ && rm -rf "/usr/osxcross/SDK/MacOSX${DARWIN_SDK_VERSION}.sdk/usr/share/man" export PATH="$PATH:/usr/osxcross/bin" ``` -------------------------------- ### Initialize Arcaze Display Source: https://github.com/x-friese/flywithlua/blob/master/FlyWithLua/Documentation/Ein_Arcaze_USB_ansteuern.md Initializes the Arcaze display modules with specified brightness. This function should be called once during setup. ```lua arcaze.init_display( my_arcaze, "1b", INSTRUMENT_BRIGHTNESS*15 ) arcaze.init_display( my_arcaze, "3a", INSTRUMENT_BRIGHTNESS*15 ) ``` -------------------------------- ### Configure and Build FlyWithLua on OS X Source: https://github.com/x-friese/flywithlua/blob/master/README.md Clones the repository, configures the build using CMake, and builds the project. The plugin DLL is then copied to the appropriate directory. Ensure XCode, Git, and CMake are installed. ```bash git clone https://github.com/X-Friese/FlyWithLua.git cd FlyWithLua cmake -S ./src -B ./build -DCMAKE_BUILD_TYPE=RelWithDebInfo cmake --build ./build mkdir ./FlyWithLua/mac_x64 cp ./build/mac.xpl ./FlyWithLua/mac_x64/FlyWithLua.xpl ``` -------------------------------- ### Execute X-Plane Commands Source: https://context7.com/x-friese/flywithlua/llms.txt Use `command_once` for single actions, `command_begin` to start a continuous command, and `command_end` to release it. Useful for simulating button presses or holding controls. ```lua -- Execute a command once (button press simulation) command_once("sim/lights/beacon_lights_on") command_once("sim/flight_controls/flaps_down") -- Continuous command (hold button) -- command_begin starts the command, command_end releases it function hold_autopilot_adjust() command_begin("sim/autopilot/heading_up") end function release_autopilot_adjust() command_end("sim/autopilot/heading_up") end -- Toggle gear with command command_once("sim/flight_controls/landing_gear_toggle") -- Engage autopilot systems command_once("sim/autopilot/servos_on") command_once("sim/autopilot/heading") command_once("sim/autopilot/altitude_hold") ``` -------------------------------- ### Send a Multipart Email with Attachments Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/smtp.html Example demonstrating how to create and send a multipart email with plain text and a base64 encoded PNG image attachment. It requires loading smtp, mime, and ltn12 modules. ```lua -- load the smtp support and its friends local smtp = require("socket.smtp") local mime = require("mime") local ltn12 = require("ltn12") -- creates a source to send a message with two parts. The first part is -- plain text, the second part is a PNG image, encoded as base64. source = smtp.message{ headers = { -- Remember that headers are *ignored* by smtp.send. from = "Sicrano de Oliveira ", to = "Fulano da Silva ", subject = "Here is a message with attachments" }, body = { preamble = "If your client doesn't understand attachments, \r\n" .. "it will still display the preamble and the epilogue.\r\n" .. "Preamble will probably appear even in a MIME enabled client.", -- first part: no headers means plain text, us-ascii. -- The mime.eol low-level filter normalizes end-of-line markers. [1] = { body = mime.eol(0, [[ Lines in a message body should always end with CRLF. The smtp module will *NOT* perform translation. However, the send function *DOES* perform SMTP stuffing, whereas the message function does *NOT*. ]]) }, -- second part: headers describe content to be a png image, -- sent under the base64 transfer content encoding. -- notice that nothing happens until the message is actually sent. ``` -------------------------------- ### Create Command with Continuous Execution Source: https://github.com/x-friese/flywithlua/blob/master/FlyWithLua/Documentation/First_Steps_Programming_FlyWithLua.md This example shows how to make a command execute Lua code continuously while a button or key is held down. Note that this can lead to rapid, uncontrollable increments and loss of fine control. ```lua require("radio") create_command("FlyWithLua/testing/increase_OBS", "This command increases the OBS value by one degree.", "", "OBS1 = OBS1 + 1", "OBS1 = OBS1 % 360") ``` -------------------------------- ### Copy LuaJIT Library and Set Up Target Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luajit/CMakeLists.txt This snippet defines a CMake target for LuaJIT, copies the built static library to the install directory, and sets up the include directories. It ensures the LuaJIT library is available as a static import library. ```cmake ExternalProject_Get_Property(project_luajit install_dir source_dir) add_custom_command( TARGET project_luajit POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${luajit_prefix}/src/project_luajit/src/libluajit.a ${install_dir}/lib/libluajit-5.1.a) add_library(LuaJIT STATIC IMPORTED GLOBAL) add_library(luajit::LuaJIT ALIAS LuaJIT) add_dependencies(LuaJIT project_luajit) set_property(TARGET LuaJIT PROPERTY IMPORTED_LOCATION "${install_dir}/lib/libluajit-5.1.a") target_include_directories(LuaJIT INTERFACE "${source_dir}/src") file(MAKE_DIRECTORY "${source_dir}/src") # CMake doesn't like if include dir doesn't exist at configure time. ``` -------------------------------- ### Create Command with Delayed Increment Source: https://github.com/x-friese/flywithlua/blob/master/FlyWithLua/Documentation/First_Steps_Programming_FlyWithLua.md This example demonstrates a command that delays the initial increment and then applies a single degree increase. It uses `os.clock()` to manage timing and ensures the increment happens only after a specified delay, providing a more deliberate user experience. ```lua require("radio") local obs_up_time = 1 local ops_up_value = 1 create_command("FlyWithLua/testing/increase_OBS", "This command increases the OBS value by one degree.", "obs_up_time = os.clock() + 2\n obs_up_value = OBS1\n OBS1 = obs_up_value + 1", "if os.clock() > obs_up_time then\n ``` -------------------------------- ### Create a Table Source with ltn12.source.table Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/ltn12.html Creates a source that iterates over the numerically-indexed values of a table, starting from index 1. The source terminates when it encounters a nil value. ```lua ltn12.source.table(table) ``` -------------------------------- ### Require and Use socket.http Module Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/installation.html Load the socket.http module to make HTTP requests. This module automatically loads its dependencies. The example shows how to fetch content from a URL. ```lua http = require("socket.http") print(http.request("http://www.impa.br/~diego/software/luasocket")) ``` -------------------------------- ### Require LuaSocket Module Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/installation.html Use the require function to load the LuaSocket module and access its version. This is the basic way to start using LuaSocket. ```lua socket = require("socket") print(socket._VERSION) ``` -------------------------------- ### Build Binaries for All Platforms Source: https://github.com/x-friese/flywithlua/blob/master/docker/README.md Builds Xbtn2cmd binaries for all supported platforms and lists the resulting files. ```bash $ (cd docker; make) $ ls src/build-*/*.xpl src/build-lin/lin.xpl src/build-mac/mac.xpl src/build-win/win.xpl ``` -------------------------------- ### Navigate to Repository Source: https://github.com/x-friese/flywithlua/blob/master/docker/README.md Change the current directory to the root of the Xbtn2cmd repository. ```bash $ cd $Xbtn2cmd_REPO ``` -------------------------------- ### Configure and Build FlyWithLua on Ubuntu Source: https://github.com/x-friese/flywithlua/blob/master/README.md Clones the repository, configures the build using CMake, and builds the project. The plugin DLL is then copied to the appropriate directory. ```bash git clone https://github.com/X-Friese/FlyWithLua.git cd FlyWithLua cmake -S ./src -B ./build -DCMAKE_BUILD_TYPE=RelWithDebInfo cmake --build ./build mkdir ./FlyWithLua/lin_x64 cp ./build/lin.xpl ./FlyWithLua/lin_x64/FlyWithLua.xpl ``` -------------------------------- ### Configure and Build FlyWithLua on Windows Source: https://github.com/x-friese/flywithlua/blob/master/README.md Clones the repository, configures the build using CMake with MinGW Makefiles, and builds the project. The plugin DLL is then copied to the appropriate directory. ```bash git clone https://github.com/X-Friese/FlyWithLua.git cd FlyWithLua cmake -G "MinGW Makefiles" -S .\src -B .\build -DCMAKE_BUILD_TYPE=RelWithDebInfo cmake --build .\build mkdir .\FlyWithLua\win_x64 copy .\build\win.xpl .\FlyWithLua\win_x64\FlyWithLua.xpl ``` -------------------------------- ### Simplified HTTP GET Function Using Table Sink in Lua Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/ltn12.html A simplified implementation of an HTTP GET function that uses LTN12's table sink to collect the response body. It returns the concatenated response body, headers, and status code. Ensure the 'socket.http' and 'ltn12' modules are loaded. ```lua -- load needed modules local http = require("socket.http") local ltn12 = require("ltn12") -- a simplified http.get function function http.get(u) local t = {} local respt = request{ url = u, sink = ltn12.sink.table(t) } return table.concat(t), respt.headers, respt.code end ``` -------------------------------- ### GET /socket/getsockname Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/tcp.html Retrieves the local address information associated with the socket object. ```APIDOC ## GET /socket/getsockname ### Description Returns the local address information associated to the object. ### Method GET ### Response #### Success Response (200) - **ip** (string) - Local IP address - **port** (number) - Local port - **family** (string) - Address family ("inet" or "inet6") ``` -------------------------------- ### Download files using FTP Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/ftp.html Demonstrates both simple URL-based retrieval and generic table-based retrieval for custom operations like directory listings. ```lua -- load the ftp support local ftp = require("socket.ftp") -- Log as user "anonymous" on server "ftp.tecgraf.puc-rio.br", -- and get file "lua.tar.gz" from directory "pub/lua" as binary. f, e = ftp.get("ftp://ftp.tecgraf.puc-rio.br/pub/lua/lua.tar.gz;type=i") ``` ```lua -- load needed modules local ftp = require("socket.ftp") local ltn12 = require("ltn12") local url = require("socket.url") -- a function that returns a directory listing function nlst(u) local t = {} local p = url.parse(u) p.command = "nlst" p.sink = ltn12.sink.table(t) local r, e = ftp.get(p) return r and table.concat(t), e end ``` -------------------------------- ### Create Borland Import Library Source: https://github.com/x-friese/flywithlua/blob/master/src/GLUT_for_Windows/GL/README-win32.txt Commands to generate a Borland-compatible import library from the provided DLL or definition file. ```shell IMPLIB glut32.lib glut32.dll ``` ```shell IMPLIB glut32.lib glut32.def ``` -------------------------------- ### Example: Text Normalization and Quoted-Printable Encoding Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/mime.html Demonstrates creating a filter for Quoted-Printable encoding of text data. ```APIDOC ## Example: Text Normalization and Quoted-Printable Encoding ### Description This example demonstrates creating a filter chain for encoding text data using Quoted-Printable, including normalization of line endings and line wrapping. ### Method `ltn12.filter.chain` combined with `mime.normalize`, `mime.encode`, and `mime.wrap` ### Endpoint N/A (Lua code example) ### Request Example ```lua local qp_encoder = ltn12.filter.chain( mime.normalize(), mime.encode("quoted-printable"), mime.wrap("quoted-printable") ) ``` ``` -------------------------------- ### Open Project in QT Creator Source: https://github.com/x-friese/flywithlua/blob/master/README.md Instructions for opening the FlyWithLua project in QT Creator. This involves cloning the repository and using QT Creator's 'Open File or Project' feature. ```bash mkdir QTCreatorProjects cd D:\QTCreatorProjects git clone https://github.com/X-Friese/FlyWithLua.git # Using QT Creator use "File" > "Open File or Project" and browse to "FlyWithLua/src/CMakeLists.txt" then click on the "Open" button. ``` -------------------------------- ### Build for Specific Platform Source: https://github.com/x-friese/flywithlua/blob/master/docker/README.md Builds the binary for a single specified platform (lin, mac, or win). ```bash $ (cd docker; make lin) ``` -------------------------------- ### Direct DataRef Access - get / set Source: https://context7.com/x-friese/flywithlua/llms.txt Provides direct read/write access to DataRefs without creating persistent bindings. ```APIDOC ## get / set - Direct DataRef Access ### Description Provides direct read/write access to DataRefs without creating persistent bindings. Useful for one-time operations or accessing DataRefs dynamically. ### Method `get(dataref_path, [index])` `set(dataref_path, value, [index])` ### Parameters #### get Parameters - **dataref_path** (string) - Required - The path to the X-Plane DataRef. - **index** (number) - Optional - The index for array DataRefs. Defaults to 0. #### set Parameters - **dataref_path** (string) - Required - The path to the X-Plane DataRef. - **value** (any) - Required - The value to set for the DataRef. - **index** (number) - Optional - The index for array DataRefs. Defaults to 0. ### Request Example ```lua -- Read a DataRef value directly local current_altitude = get("sim/flightmodel/position/elevation") logMsg("Current altitude: " .. current_altitude .. " meters") -- Write to a DataRef directly set("sim/cockpit/electrical/landing_lights_on", 1) -- Read array element with index local engine_rpm = get("sim/flightmodel/engine/ENGN_N1_", 0) -- First engine -- Read string DataRef local aircraft_path = get("sim/aircraft/view/acf_relative_path") logMsg("Aircraft: " .. aircraft_path) ``` ``` -------------------------------- ### Create CodeBlocks Project Source: https://github.com/x-friese/flywithlua/blob/master/README.md Sets up a CodeBlocks project for FlyWithLua. This involves cloning the repository, creating build directories, and configuring CMake for CodeBlocks. ```bash mkdir CodeBlocksProjects cd D:\CodeBlocksProjects git clone https://github.com/X-Friese/FlyWithLua.git cd FlyWithLua/src mkdir build cd build cmake -G "CodeBlocks - MinGW Makefiles" .. # Open CodeBlocks and use "Open an existing project" browsing to "FlyWithLua/src/build/FlyWithLua.cbp" and click on the Open button. ``` -------------------------------- ### Load the HTTP module Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/http.html Initialize the HTTP module to access its functionality. ```lua -- loads the HTTP module and any libraries it requires local http = require("socket.http") ``` -------------------------------- ### UDP Option Management Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/udp.html Methods for getting and setting options on UDP objects. Options control various aspects of socket behavior. ```APIDOC ## UDP getoption() and setoption() ### Description `getoption()` retrieves an option value from the UDP object. `setoption()` sets an option value. See the documentation for a list of supported option names and their values. ### Method `getoption(option_name)` `setoption(option_name, value)` ### Endpoint N/A (Methods on UDP object) ### Parameters #### getoption() - **option_name** (string) - The name of the option to retrieve. #### setoption() - **option_name** (string) - The name of the option to set. - **value** (any) - The value to set for the option. ### Supported Options - 'dontroute' - 'broadcast' - 'reuseaddr' - 'reuseport' - 'ip-multicast-loop' - 'ipv6-v6only' - 'ip-multicast-if' - 'ip-multicast-ttl' - 'ip-add-membership' - 'ip-drop-membership' ### Request Example (getoption) ```lua local broadcast_status = udp_socket:getoption('broadcast') ``` ### Request Example (setoption) ```lua udp_socket:setoption('broadcast', true) ``` ### Response (getoption) - **option_value** (any) - The value of the option if successful, otherwise nil followed by an error message. ### Response (setoption) - Success: Typically returns nothing or a success indicator. - Error: nil followed by an error message. ``` -------------------------------- ### Get Current Time Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/socket.html Returns the current UNIX time in seconds. Subtract the values returned by this function to calculate elapsed time. ```lua socket.gettime() ``` -------------------------------- ### MIME Module Initialization Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/mime.html How to load and access the MIME module in Lua. ```APIDOC ## MIME Module Initialization ### Description Loads the MIME module and makes its functionality available. ### Method `require` ### Endpoint N/A (Lua module) ### Request Example ```lua local mime = require("mime") ``` ### Response Returns the mime namespace table. ``` -------------------------------- ### Build FlyWithLua for OS X Source: https://github.com/x-friese/flywithlua/blob/master/README.md Builds FlyWithLua for OS X using the previously set up osxcross toolchain. Requires the OS X cross-compiling toolchain to be installed. ```bash git clone https://github.com/X-Friese/FlyWithLua.git cd FlyWithLua # For OS X: cmake -S ./src -B ./build-mac -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_TOOLCHAIN_FILE=src/Toolchain-ubuntu-osxcross-10.11.cmake -DCMAKE_FIND_ROOT_PATH=/usr/osxcross/SDK/MacOSX10.11.sdk/ cmake --build ./build-mac ``` -------------------------------- ### URL Module Initialization Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/url.html How to load and access the URL module. ```APIDOC ## Loading the URL Module To use the URL module, you need to require it: ```lua local url = require("socket.url") ``` ``` -------------------------------- ### Example: Resource Cleanup with newtry Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/socket.html Illustrates using socket.newtry to ensure a network connection is closed even if errors occur during communication. A finalizer function is provided to close the connection. ```lua foo = socket.protect(function() -- connect somewhere local c = socket.try(socket.connect("somewhere", 42)) -- create a try function that closes 'c' on error local try = socket.newtry(function() c:close() end) -- do everything reassured c will be closed try(c:send("hello there?\r\n")) local answer = try(c:receive()) ... try(c:send("good bye\r\n")) c:close() end) ``` -------------------------------- ### Define and Set a Writable DataRef Source: https://github.com/x-friese/flywithlua/blob/master/FlyWithLua/Documentation/First_Steps_Programming_FlyWithLua.md Declare a DataRef for reading and writing, then assign a value. Ensure the DataRef is marked as 'writable' in the X-Plane DataRefs documentation. This example sets beacon lights on. ```Lua dataref("Beacons", "sim/cockpit/electrical/beacon_lights_on", "writable") Beacons = 1 ``` -------------------------------- ### Build ImGui Widgets in Lua Source: https://context7.com/x-friese/flywithlua/llms.txt Demonstrates creating a floating window and populating it with various ImGui widgets like checkboxes, sliders, radio buttons, and text inputs. Requires a defined builder function passed to float_wnd_set_imgui_builder. ```lua -- Complete ImGui widget demonstration settings_wnd = float_wnd_create(500, 400, 1, true) float_wnd_set_title(settings_wnd, "Aircraft Settings") float_wnd_set_imgui_builder(settings_wnd, "build_settings") -- Widget state variables autopilot_on = false heading_value = 180 altitude_value = 10000 selected_mode = 0 notes_text = "" function build_settings(wnd, x, y) -- Collapsible tree sections if imgui.TreeNode("Autopilot Settings") then -- Checkbox local changed, val = imgui.Checkbox("Autopilot Enabled", autopilot_on) if changed then autopilot_on = val if val then command_once("sim/autopilot/servos_on") else command_once("sim/autopilot/servos_off") end end -- Integer slider local changed, val = imgui.SliderInt("Heading", heading_value, 0, 359) if changed then heading_value = val set("sim/cockpit/autopilot/heading", val) end -- Float slider with format local changed, val = imgui.SliderFloat("Altitude (ft)", altitude_value, 0, 45000, "%.0f") if changed then altitude_value = val end imgui.TreePop() end -- Radio buttons if imgui.TreeNode("Flight Mode") then if imgui.RadioButton("Normal", selected_mode == 0) then selected_mode = 0 end if imgui.RadioButton("Approach", selected_mode == 1) then selected_mode = 1 end if imgui.RadioButton("Landing", selected_mode == 2) then selected_mode = 2 end imgui.TreePop() end -- Text input if imgui.TreeNode("Notes") then local changed, val = imgui.InputText("Flight Notes", notes_text, 256) if changed then notes_text = val end -- Multiline text local changed, val = imgui.InputTextMultiline("Details", notes_text, 256, 200, 100) if changed then notes_text = val end imgui.TreePop() end -- Styled button imgui.PushStyleColor(imgui.constant.Col.Button, 0xFF0000FF) -- Red if imgui.Button("Emergency Stop", 150, 40) then command_once("sim/operation/pause_toggle") end imgui.PopStyleColor() end ``` -------------------------------- ### Verbose Imgui Binding Generation Source: https://github.com/x-friese/flywithlua/blob/master/src/imgui/HowTo_Generate_iterator_file.txt To make the Perl script verbose during binding generation, install Devel::Trace and use the -d:Trace option. This helps in debugging the script's execution. ```perl sudo perl -MCPAN -e 'install Devel::Trace' ``` ```perl perl -d:Trace generate_imgui_bindings.pl imgui_iterator.inl ``` -------------------------------- ### Create and Bind TCP Server Socket Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/introduction.html Creates a TCP socket, binds it to a local address and port, and listens for incoming connections. Use this to set up a server that accepts client connections. ```lua local socket = require("socket") local server = assert(socket.bind("*", 0)) local ip, port = server:getsockname() print("Please telnet to localhost on port " .. port) print("After connecting, you have 10s to enter a line to be echoed") while 1 do local client = server:accept() client:settimeout(10) local line, err = client:receive() if not err then client:send(line .. "\n") end client:close() end ``` -------------------------------- ### Direct DataRef Access Source: https://context7.com/x-friese/flywithlua/llms.txt Use `get` to read and `set` to write X-Plane DataRefs directly without persistent bindings. Useful for one-time operations or dynamic access. Array elements require an index. ```lua -- Read a DataRef value directly local current_altitude = get("sim/flightmodel/position/elevation") logMsg("Current altitude: " .. current_altitude .. " meters") -- Write to a DataRef directly set("sim/cockpit/electrical/landing_lights_on", 1) -- Read array element with index local engine_rpm = get("sim/flightmodel/engine/ENGN_N1_", 0) -- First engine -- Read string DataRef local aircraft_path = get("sim/aircraft/view/acf_relative_path") logMsg("Aircraft: " .. aircraft_path) ``` -------------------------------- ### Load the FTP module Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/ftp.html Initializes the FTP namespace for use in Lua scripts. ```lua -- loads the FTP module and any libraries it requires local ftp = require("socket.ftp") ``` -------------------------------- ### Accessing Global Variables in FlyWithLua Source: https://context7.com/x-friese/flywithlua/llms.txt This snippet demonstrates how to access and log various global variables provided by FlyWithLua to get information about the simulator, script, and aircraft. It also shows a conditional check for feature support. ```lua -- Screen dimensions logMsg("Screen: " .. SCREEN_WIDTH .. "x" .. SCREEN_HEIGHT) -- Script and plugin paths logMsg("Script directory: " .. SCRIPT_DIRECTORY) logMsg("System directory: " .. SYSTEM_DIRECTORY) -- X-Plane root -- Plugin version info logMsg("FlyWithLua version: " .. PLUGIN_VERSION) logMsg("Version number: " .. PLUGIN_VERSION_NO) logMsg("Build date: " .. PLUGIN_VERSION_BUILD) -- Aircraft information logMsg("Aircraft: " .. AIRCRAFT_FILENAME) logMsg("Aircraft path: " .. AIRCRAFT_PATH) logMsg("Author: " .. PLANE_AUTHOR) logMsg("Description: " .. PLANE_DESCRIP) logMsg("Tail number: " .. PLANE_TAILNUMBER) logMsg("ICAO type: " .. PLANE_ICAO) -- Feature detection if SUPPORTS_FLOATING_WINDOWS then logMsg("ImGui floating windows supported") end -- Mouse state (in event handlers) -- MOUSE_X, MOUSE_Y: coordinates -- MOUSE_STATUS: 0=up, 1=down -- MOUSE_WHEEL_CLICKS: scroll amount -- Keyboard state (in event handlers) -- KEY_ACTION: 0=up, 1=down -- VKEY: virtual key code -- CKEY: character ``` -------------------------------- ### Control Elevator Trim with Mouse Wheel Source: https://github.com/x-friese/flywithlua/blob/master/FlyWithLua/Documentation/First_Steps_Programming_FlyWithLua.md This example reads mouse wheel movements (MOUSE_WHEEL_CLICKS) to adjust the elevator trim DataRef. It includes bounds checking to keep the trim within the valid range of -1.0 to 1.0. ```Lua dataref("xp_elv_trim", "sim/flightmodel/controls/elv_trim", "writable") function set_trim_by_mouse_wheel() xp_elv_trim = xp_elv_trim - MOUSE_WHEEL_CLICKS * 0.0025 if xp_elv_trim > 1.0 then xp_elv_trim = 1.0 end if xp_elv_trim < -1.0 then xp_elv_trim = -1.0 end RESUME_MOUSE_WHEEL = true end do_on_mouse_wheel("set_trim_by_mouse_wheel()") ``` -------------------------------- ### Initialize Arcaze Radio Script Source: https://github.com/x-friese/flywithlua/blob/master/FlyWithLua/Documentation/Ein_Arcaze_USB_ansteuern.md Sets up the required Arcaze module, validates the X-Plane version, and defines the necessary DataRefs for COM1 radio control. ```lua -- We need the Arcaze module require "arcaze" -- The DataRefs we want to use are first implemented into X-Plane 10.30, so we have to check it if XPLANE_VERSION < 10300 then logMsg('FlyWithLua error: The script "little arcaze radio.lua" needs X-Plane 10.30 or newer!') else -- These are the DataRefs we need: COM1, COM1_STDBY, INSTRUMENT_BRIGHTNESS dataref("NEW_COM1", "sim/cockpit2/radios/actuators/com1_frequency_hz_833", "writable") dataref("NEW_COM1_STDBY", "sim/cockpit2/radios/actuators/com1_standby_frequency_hz_833", "writable") dataref("INSTRUMENT_BRIGHTNESS", "sim/cockpit/electrical/instrument_brightness", "readonly") end -- First we have to find the Arcaze USB device local my_arcaze = arcaze.open_first_device() -- we will check, if an Arcaze was found, to avoid crashing the sim if the Arcaze isn't plugged in -- when no Arcaze was found, the function arcaze.open_first_device() will return a nil value if not ((my_arcaze == nil) or (XPLANE_VERSION < 10300)) then -- As both rotary encoders will result in a relative value, we will have to remember the last value -- to decide if the change is made up or down and how many steps it was turned. We need two local variables. local last_big_radio_wheel = 0 local last_small_radio_wheel = 0 -- As we connected the rotary to the first encoder pins, we can easily get the relative values: last_big_radio_wheel, last_small_radio_wheel = arcaze.read_encoders( my_arcaze ) -- The same with the push button, but we simply guess it is not pushed at the moment local last_radio_push_button = 0 -- Now we initialize the Display Driver 32 connectors (the brightness DataRef has a range 0.0 to 1.0, but we need 0 to 15). ``` -------------------------------- ### Audio Playback and Callout System Source: https://context7.com/x-friese/flywithlua/llms.txt Load and control WAV files for audio feedback, or implement a frame-based callout system using datarefs. ```lua -- Load sound files (do this once at script start) local gear_warning = load_WAV_file(SYSTEM_DIRECTORY .. "Resources/sounds/alert/gear_warn.wav") local altitude_10 = load_WAV_file(SYSTEM_DIRECTORY .. "Resources/sounds/alert/10ft.wav") local custom_click = load_WAV_file(SCRIPT_DIRECTORY .. "click.wav") -- Play sound once play_sound(gear_warning) -- Sound control functions stop_sound(gear_warning) pause_sound(gear_warning) rewind_sound(gear_warning) -- Adjust sound properties set_sound_gain(gear_warning, 0.8) -- Volume (0.0 to 1.0) set_sound_pitch(gear_warning, 1.2) -- Pitch multiplier -- Looping sound let_sound_loop(gear_warning, true) -- Enable looping play_sound(gear_warning) -- Later: let_sound_loop(gear_warning, false) to stop loop -- Complete callout system example dataref("radio_alt", "sim/flightmodel/position/y_agl", "readonly") local callout_played = {} function altitude_callouts() local alt_feet = radio_alt * 3.28084 local callouts = { {50, altitude_50}, {40, altitude_40}, {30, altitude_30}, {20, altitude_20}, {10, altitude_10} } for _, callout in ipairs(callouts) do local alt, sound = callout[1], callout[2] if alt_feet <= alt and not callout_played[alt] then play_sound(sound) callout_played[alt] = true elseif alt_feet > alt + 5 then callout_played[alt] = nil -- Reset when climbing end end end do_every_frame("altitude_callouts()") ``` -------------------------------- ### Constructing an Email with Attachments Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/smtp.html This snippet demonstrates how to construct an email with attachments, including setting content type, disposition, and encoding for image files. It uses ltn12.source.chain and mime.encode for base64 encoding. ```lua -- small chunks are loaded into memory right before transmission and -- translation happens on the fly. \[2\] = { headers = { \["content-type"\] = 'image/png; name="image.png"', \["content-disposition"] = 'attachment; filename="image.png"', \["content-description"] = 'a beautiful image', \["content-transfer-encoding"] = "BASE64" }, body = ltn12.source.chain( ltn12.source.file(io.open("image.png", "rb")), ltn12.filter.chain( mime.encode("base64"), mime.wrap() ) ) }, epilogue = "This might also show up, but after the attachments" } } -- finally send it r, e = smtp.send{ from = "", rcpt = "", source = source, } ``` -------------------------------- ### Cycle Through a Low-Level Filter in Lua Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/ltn12.html Creates a high-level filter that repeatedly applies a low-level filter, managing context between calls. This is useful for stateful filtering operations. The 'encodet["base64"]' example shows how to use it with a base64 mime filter. ```lua local ltn12 = require("ltn12") -- the base64 mime filter factory encodet['base64'] = function() return ltn12.filter.cycle(b64, "") end ``` -------------------------------- ### Create Basic Custom Command Source: https://github.com/x-friese/flywithlua/blob/master/FlyWithLua/Documentation/First_Steps_Programming_FlyWithLua.md Use this to create a simple command that executes a single line of Lua code when triggered. Ensure the 'radio' module is required if using DataRefs like OBS1. ```lua require("radio") create_command("FlyWithLua/testing/increase_OBS", "This command increases the OBS value by one degree.", "OBS1 = OBS1 + 1", "", "") ``` -------------------------------- ### Initialize Radio Module Source: https://github.com/x-friese/flywithlua/blob/master/FlyWithLua/Scripts (disabled)/Checklists/global_checklist.txt Loads the radio module required for transponder and communication data. ```lua >require("radio") ``` -------------------------------- ### Load MIME Module Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/mime.html Initializes the MIME namespace for use in the Lua environment. ```lua -- loads the MIME module and everything it requires local mime = require("mime") ``` -------------------------------- ### Windows Build Configuration Source: https://github.com/x-friese/flywithlua/blob/master/src/CMakeLists.txt Configures static linking for Windows builds, including standard libraries and the entire plugin. This is necessary because X-Plane does not provide standard libraries on Windows. ```cmake if (WIN32) # Unlike OS X and Linux we build standard libraries statically since X-Plane does not provide them. target_link_libraries(FlyWithLua -static-libgcc -static-libstdc++) # MSYS2 for some reason always links against winpthread, so we have to work around it by statically linking the # entire plugin. This allows building the plugin nativaly on Windows. target_link_libraries(FlyWithLua -static) endif () ``` -------------------------------- ### Send Email with LuaSocket Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/smtp.html Demonstrates how to configure and send an email message using the smtp.send function. Ensure the socket.smtp module is loaded before use. ```lua -- load the smtp support local smtp = require("socket.smtp") -- Connects to server "localhost" and sends a message to users -- "fulano@example.com", "beltrano@example.com", -- and "sicrano@example.com". -- Note that "fulano" is the primary recipient, "beltrano" receives a -- carbon copy and neither of them knows that "sicrano" received a blind -- carbon copy of the message. from = "" rcpt = { "", "", "" } mesgt = { headers = { to = "Fulano da Silva ", cc = '"Beltrano F. Nunes" ', subject = "My first message" }, body = "I hope this works. If it does, I can send you another 1000 copies." } r, e = smtp.send{ from = from, rcpt = rcpt, source = smtp.message(mesgt) } ``` -------------------------------- ### server:accept() Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/tcp.html Waits for a remote connection on the server object and returns a client object representing that connection. ```APIDOC ## server:accept() ### Description Waits for a remote connection on the server object and returns a client object representing that connection. ### Response - **client object** (object) - Returned if connection is successful. - **nil, error** (string) - Returned if a timeout or error occurs. ``` -------------------------------- ### Build FlyWithLua for Windows Source: https://github.com/x-friese/flywithlua/blob/master/README.md Builds FlyWithLua for Windows using MinGW-w64 toolchain. Ensure CMake and the specified toolchain file are available. ```bash git clone https://github.com/X-Friese/FlyWithLua.git cd FlyWithLua # For Windows: cmake -S ./src -B ./build-win -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_TOOLCHAIN_FILE=src/Toolchain-mingw-w64-x86-64.cmake cmake --build ./build-win ``` -------------------------------- ### Studio::EventDescription and Studio::EventInstance API Source: https://github.com/x-friese/flywithlua/blob/master/src/Fmod_api/revision.txt Updated methods for managing event cues and parameter values in the FMOD Studio API. ```APIDOC ## Studio::EventDescription::hasCue ### Description Checks if an event description has a specific cue. ## Studio::EventInstance::triggerCue ### Description Triggers a cue on an event instance. ## Studio::EventInstance::getParameterValue ### Description Retrieves the value of a parameter by name. ## Studio::EventInstance::setParameterValue ### Description Sets the value of a parameter by name. ``` -------------------------------- ### master:connect(address, port) Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/tcp.html Attempts to connect a master object to a remote host, transforming it into a client object. ```APIDOC ## master:connect(address, port) ### Description Attempts to connect a master object to a remote host, transforming it into a client object. ### Parameters - **address** (string) - Required - IP address or host name. - **port** (number) - Required - Integer in range [1..64K). ### Response - **1** (number) - Returned on success. - **nil, error** (string) - Returned on error. ``` -------------------------------- ### Perform simple HTTP requests with LuaSocket Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luasocket/upstream/doc/http.html Demonstrates basic usage of the socket.http module for retrieving web content and handling common request outcomes. ```lua -- load the http module local io = require("io") local http = require("socket.http") local ltn12 = require("ltn12") -- connect to server "www.cs.princeton.edu" and retrieves this manual -- file from "~diego/professional/luasocket/http.html" and print it to stdout http.request{ url = "http://www.cs.princeton.edu/~diego/professional/luasocket/http.html", sink = ltn12.sink.file(io.stdout) } -- connect to server "www.example.com" and tries to retrieve -- "/private/index.html". Fails because authentication is needed. b, c, h = http.request("http://www.example.com/private/index.html") -- b returns some useless page telling about the denied access, -- h returns authentication information -- and c returns with value 401 (Authentication Required) -- tries to connect to server "wrong.host" to retrieve "/" -- and fails because the host does not exist. r, e = http.request("http://wrong.host/") -- r is nil, and e returns with value "host not found" ``` -------------------------------- ### Download and Build LuaJIT with CMake Source: https://github.com/x-friese/flywithlua/blob/master/src/third_party/luajit/CMakeLists.txt This snippet uses ExternalProject_Add to download, patch, and build LuaJIT. It configures build options for cross-compilation and specifies build byproducts. The CONFIGURE_COMMAND is intentionally left empty as patching and building are handled separately. ```cmake cmake_minimum_required(VERSION 3.9) project(luajit DESCRIPTION "LuaJIT is a Just-In-Time (JIT) compiler for the Lua programming language.") include(ExternalProject) set (luajit_version $ENV{LUAJIT_VERSION}) if ("${lua_version}" STREQUAL "") set(luajit_version 2.0.5) endif() set(build_options "") if (NOT CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME) # We are cross-compiling: set appropriate toolchain options for LuaJIT. if (WIN32) set(build_options "CC=gcc" "CROSS=${TOOLCHAIN_PREFIX}-" "TARGET_SYS=Windows") elseif (APPLE) set(build_options "CC=clang" "CROSS=${TOOLCHAIN_PREFIX}-" "TARGET_SYS=Darwin") endif () endif() set(luajit_prefix ${CMAKE_CURRENT_BINARY_DIR}/luajit-${luajit_version}) find_package(Patch REQUIRED) find_program(Make_EXECUTABLE NAMES make mingw32-make REQUIRED) ExternalProject_Add(project_luajit URL http://luajit.org/download/LuaJIT-${luajit_version}.tar.gz PREFIX ${luajit_prefix} CONFIGURE_COMMAND "" PATCH_COMMAND ${Patch_EXECUTABLE} -p1 -t -N < ${CMAKE_CURRENT_SOURCE_DIR}/x-plane-luajit.patch BUILD_COMMAND ${CMAKE_COMMAND} -E env MACOSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET} ${Make_EXECUTABLE} -j ${build_options} BUILD_IN_SOURCE 1 INSTALL_COMMAND "" BUILD_BYPRODUCTS ${luajit_prefix}/lib/libluajit-5.1.a ) ``` -------------------------------- ### Command Execution - command_once / command_begin / command_end Source: https://context7.com/x-friese/flywithlua/llms.txt Executes X-Plane commands to trigger cockpit actions, system toggles, and simulator functions programmatically. ```APIDOC ## command_once / command_begin / command_end - Execute X-Plane Commands ### Description Executes X-Plane commands to trigger cockpit actions, system toggles, and simulator functions programmatically. ### Method `command_once(command_name)` `command_begin(command_name)` `command_end(command_name)` ### Parameters #### Path Parameters - **command_name** (string) - Required - The name of the X-Plane command to execute. ### Request Example ```lua -- Execute a command once (button press simulation) command_once("sim/lights/beacon_lights_on") command_once("sim/flight_controls/flaps_down") -- Continuous command (hold button) -- command_begin starts the command, command_end releases it function hold_autopilot_adjust() command_begin("sim/autopilot/heading_up") end function release_autopilot_adjust() command_end("sim/autopilot/heading_up") end -- Toggle gear with command command_once("sim/flight_controls/landing_gear_toggle") -- Engage autopilot systems command_once("sim/autopilot/servos_on") command_once("sim/autopilot/heading") command_once("sim/autopilot/altitude_hold") ``` ```