https://wiki.mudlet.org/api.php?action=feedcontributions&user=Kebap&feedformat=atomMudlet - User contributions [en]2024-03-28T18:03:59ZUser contributionsMediaWiki 1.35.0https://wiki.mudlet.org/index.php?title=Compiling_Mudlet&diff=21489Compiling Mudlet2024-02-25T21:13:09Z<p>Kebap: </p>
<hr />
<div>{{TOC right}}<br />
<br />
If you just want to use Mudlet, you can skip these steps, and use one of the already ready (pre-compiled) installers [https://www.mudlet.org/download ready for download].<br />
<br />
Otherwise, hop in for new adventure! <br />
<br />
[[File:Easy Mudlet code understanding.png|400px|none]]<br />
<br />
= Key contributing information =<br />
<br />
Clang format is used to automatically format code submissions using the [https://github.com/Mudlet/Mudlet/blob/development/src/.clang-format src/.clang-format] style. [http://doc.qt.io/qtcreator/creator-beautifier.html See here] how to enable clang-format with Qt Creator - and make sure to specify the 'File' option for the configuration style.<br />
<br />
Branches:<br />
<br />
'''development''' is the development branch where new features can go.<br />
<br />
Workflow:<br />
<br />
Fork and submit a PR with your changes ([https://guides.github.com/activities/forking/ Github tutorial]).<br />
<br />
Here is a list of package versions delivered with different Linux distros. You may want to upgrade these: <br />
https://repology.org/project/mudlet/versions<br />
<br />
= Lua & Luarocks =<br />
<br />
Mudlet includes a [https://en.wikipedia.org/wiki/Lua_(programming_language) Lua] (version 5.1) scripting system for the end-user, which you, as a reader of this Wiki, may already be aware of! If not, you might wish to (after you have got your hands on a working Mudlet) take a look at [https://wiki.mudlet.org/w/Manual:Lua_Functions Mudlet Lua API] as that is the recommended place to find out the details of all the functions that Mudlet provides on top of the core Lua functionality.<br />
<br />
Some of that ability comes from extra code that is not built-in to Lua but is in the form of external modules either in the form of script (text) files written in the Lua language itself or binary (library) files compiled from (usually but not exclusively [https://en.wikipedia.org/wiki/C_(programming_language) 'C']) source code. In order to have that functionality Mudlet makes use of several of these modules which can most readily (if not already available as "packages" for a particular Operating System) be obtained as '''rocks''' from the public [https://en.wikipedia.org/wiki/LuaRocks Luarocks] collection. Such a rock actually consists of a ''rockspec'' file that gives instructions to the Luarocks tool how to obtains the (source) code, compile it on any supported OS into the form that a Lua interpreter (including the one included in '''''each''''' running Mudlet ''profile'') can use, and where and what it will be placed and called when it has been made. After that it should be available to Lua via the ''require'' command.<br />
<br />
Anyone compiling Mudlet for themselves will find it desirable to ensure they have a usable Luarocks installation and have the ''lua-yajl'' module installed before commencing to compile Mudlet itself; this is because a Lua (version 5.1) interpreter and that module are used within the build process of making the executable code that is the Mudlet application.<br />
<br />
= Compiling =<br />
<br />
== Compiling on Ubuntu ==<br />
<br />
These instructions will get you setup compiling on Ubuntu. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
===Ubuntu 22.04===<br />
Following instructions will work on Ubuntu 22.04 as well as all its flavours and derivatives (such as KDE Neon, for example)<br />
Important thing is to have ''Universe'' repository enabled in your package manager. (on Ubuntu you will have all the repositories that you need already enabled by default.)<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo apt install ubuntu-restricted-extras qtcreator build-essential git zlib1g-dev libhunspell-dev \<br />
libpcre3-dev libzip-dev libboost-dev libboost-all-dev libyajl-dev libpulse-dev libpugixml-dev \<br />
liblua5.1-0-dev lua-filesystem lua-zip lua-sql-sqlite3 luarocks ccache lua5.1 \<br />
libglu1-mesa-dev mesa-common-dev libglib2.0-dev libgstreamer1.0-dev libqt5opengl5-dev \<br />
qtmultimedia5-dev qttools5-dev qt5keychain-dev libsecret-1-dev \<br />
libqt5texttospeech5-dev qtspeech5-flite-plugin qtspeech5-speechd-plugin \<br />
qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo luarocks install lcf<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
sudo luarocks install lrexlib-pcre<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
4. '''installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
5. '''optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo apt install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.<br />
Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybidings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
===Other Ubuntu Versions===<br />
<br />
Most of the installation instructions for 22.04 should work for older versions as well. Of note is the required version of Qt, which is 5.14. If your used version of Ubuntu only supplies older<br />
Qt versions, have a look at [https://launchpad.net/~beineri Stephan Binners PPAs], which supplies a whole range of packages for different Ubuntu versions. Be sure to read the installation and<br />
usage instructions as Qt is installed to /opt and requires sourcing a script to set up.<br />
<br />
== Compiling on Chrome OS ==<br />
<br />
These instructions will get you setup compiling on Chrome OS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Install dependencies'''<br />
<br />
sudo apt install git build-essential qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools \<br />
qtmultimedia5-dev qttools5-dev \<br />
lua5.1 liblua5.1-0-dev libpcre3-dev libboost-dev zlib1g-dev cmake \<br />
libhunspell-dev lua-rex-pcre2 lua-sql-sqlite3 lua-filesystem lua-zip libyajl-dev \<br />
libzip-dev libglu1-mesa-dev ccache libpugixml-dev mesa-common-dev qtcreator \<br />
libpulse-dev libglib2.0-dev luarocks libboost-all-dev libsecret-1-dev \<br />
ninja-build libsecret-1-dev<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''3. Get Mudlet source'''<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''4. Create a build directory'''<br />
<br />
cd mudlet<br />
mkdir build && cd build<br />
<br />
'''5. Run the following command '''<br />
<br />
cmake .. -G Ninja<br />
<br />
'''then:'''<br />
<br />
ninja<br />
<br />
'''5. Start the application you have just compiled - enjoy'''<br />
<br />
src/mudlet<br />
{{Note}}Did <code>ninja</code> fail with <code>c++: fatal error: Killed signal terminated program cclplus</code>? Try again with <code>ninja -j 2</code><br />
<br />
== Compiling on macOS ==<br />
<br />
These instructions will get you setup compiling on macOS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums] otherwise.<br />
<br />
<br />
'''1. Install prerequisites'''<br />
<br />
Install [https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12 XCode], command line tools for XCode, and [http://brew.sh HomeBrew].<br />
<br />
Once everything is installed, do:<br />
<br />
brew doctor<br />
brew update<br />
brew install git<br />
<br />
'''2. Get Mudlet source'''<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git <br />
<br />
'''3. Go to the parent of the mudlet "src" folder and create (if necessary) a build subdirectory (this is so that we can build out of source which keeps the source code clean)'''<br />
cd Mudlet && mkdir build<br />
<br />
'''3. Setup your environment'''<br />
./CI/travis.osx.before_install.sh<br />
./CI/travis.osx.install.sh<br />
<br />
luarocks config lua_version 5.1<br />
eval `luarocks path --lua-version=5.1`<br />
For the following, one may have to add <code>''_DIR="/opt/homebrew/"''</code> such as <code>PCRE_DIR="/opt/homebrew/"</code> or <code>ZIP_DIR="/opt/homebrew/"</code> if the installation could not find header files.<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lrexlib-pcre PCRE_DIR=`brew --prefix pcre`<br />
brew install sqlite<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luasql-sqlite3 SQLITE_DIR=`brew --prefix sqlite` <br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luautf8<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luafilesystem<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-zip ZIP_DIR=`brew --prefix libzip`<br />
<br />
brew install boost<br />
OK to answer yes to delete files if prompted for the <code>rm</code> command above.<br />
<br />
'''4. Run the following commands'''<br />
<br />
cd ../../build<br />
cmake ../../Mudlet -DCMAKE_PREFIX_PATH=`brew --prefix qt5`<br />
make -j `sysctl -n hw.ncpu`<br />
<br />
<br />
'''5. Enjoy'''<br />
<br />
The mudlet.app is now available in <code>src/</code> for launching:<br />
<br />
open src/Mudlet.app<br />
<br />
'''6. Qt Creator setup'''<br />
<br />
No Lua installation is found, despite it existing on your system? Launch Qt Creator by doing <code>open /Applications/Qt Creator.app</code> (location depends on how you installed it).<br />
<br />
Receiving a <code>No rule to make target ... libQt5UiTools_debug.a</code> error? A workaround is to [https://bugreports.qt.io/browse/QTBUG-81251?focusedCommentId=538705&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-538705 symlink a file].<br />
<br />
Mudlet in Qt Creator is not launching due to <code>dyld: Symbol not found: __cg_jpeg_resync_to_restart</code>? See [https://stackoverflow.com/a/44851430/72944 here] for a workaround.<br />
<br />
====== 7. Troubleshooting ======<br />
If you exhaust all efforts to get YAJL to compile on your local system with homebrew, [https://github.com/lloyd/yajl/ clone from the YAJL repository] then <code>./configure && sudo make install</code>.<br />
<br />
== Compiling on Debian 'Sid' ==<br />
<br />
'''1. Install required packages from main repo.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev<br />
<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Grab latest Mudlet source.'''<br />
<br />
mkdir ~/projects && cd ~/projects && git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
cd ~/projects/mudlet/src<br />
<br />
qmake<br />
<br />
make<br />
<br />
sudo make install<br />
<br />
== Compiling on Debian 11 'Bullseye' ==<br />
<br />
'''1. Install required packages.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev \<br />
qttools5-dev luarocks ccache libpugixml-dev libqt5texttospeech5-dev qtspeech5-flite-plugin \<br />
qtspeech5-speechd-plugin libqt5opengl5-dev ninja-build cmake libsecret-1-dev<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Get Mudlet source.'''<br />
<br />
mkdir ~/source && cd ~/source<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git<br />
<br />
Note: the line above will check out `development` branch source code, and this might not always be stable. You can check out the latest release source code using this command:<br />
<br />
git clone --recursive --branch main https://github.com/Mudlet/Mudlet.git<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
mkdir ~/source/Mudlet/build && cd ~/source/Mudlet/build<br />
<br />
qmake ../src/mudlet.pro<br />
<br />
make -j `nproc`<br />
<br />
sudo make install<br />
<br />
After these steps you can run Mudlet by typing:<br />
<br />
mudlet<br />
<br />
'''4. (Optional) Discord library'''<br />
<br />
If you get the following error;<br />
<br />
Could not find Discord library - searched in:<br />
<br />
you need to specify the discord library in your build. Run the following, changing the path where necessary;<br />
<br />
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/mudlet-dev/Mudlet/3rdparty/discord/rpc/lib/<br />
<br />
and recompile. You should see<br />
<br />
Discord integration loaded. Using functions from: "libdiscord-rpc.so"<br />
<br />
== Compiling on Raspberry Pi OS ==<br />
<br />
These instructions will get you compiling and running Mudlet on Raspberry Pi OS (Buster). Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
''' 1.a Install apt dependencies '''<br />
<br />
sudo apt-get update<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-graph-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev cmake<br />
<br />
<br />
[[File:Apt-get-install-y-n.png|center|thumb|installing apt dependencies]]<br />
<br />
''' 1.b Install luarocks dependencies '''<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl YAJL_LIBDIR=`find /usr -name "libyajl.so" -printf '%h\n'` YAJL_INCDIR=/usr/include<br />
<br />
<br />
[[File:After-luarocks-dependencies.png|center|thumb|after luarocks dependencies]]<br />
<br />
''' 2. Get Mudlet source '''<br />
<br />
mkdir ~/source && cd ~/source <br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
<br />
[[File:After-get-mudlet-source.png|center|thumb|After cloning]]<br />
<br />
''' 3. Create a build directory '''<br />
<br />
cd Mudlet && mkdir build && cd build<br />
<br />
''' 4. Run the following commands to build '''<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake ../src/mudlet.pro<br />
<br />
:If you get a response along the lines of:<br />
<br />
qmake: could not find a Qt installation of ''<br />
<br />
:then you likely have ''qtchooser'' present in your system that allows for both Qt4 and Qt5 (or more than one Qt5 version) and it modifiers qmake and some other Qt development programs to take an additional argument to specify which version to use. In that case you should use:<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake -qt=qt5 ../src/mudlet.pro<br />
<br />
[[File:After-qmake.png|center|thumb|After qmake]]<br />
<br />
''' THEN: '''<br />
:For the fastest compile time while still being able to use the system at all (~35min on a RPi4 with 4GB of ram)<br />
make -j $(expr `nproc` - 1)<br />
<br />
''' OR: '''<br />
<br />
:Use this if you have an older Raspberry Pi. Be prepared for it to take a while (over an hour) - ''it is not recommended to try to more than one compilation task at a time on the older systems with the '''-j''' option as they will only have a system memory with enough space for one of some of those tasks'':<br />
make<br />
<br />
[[File:Success.png|center|thumb|Success!]]<br />
<br />
''' 4. Install the application you have just compiled '''<br />
<br />
sudo make install<br />
<br />
[[File:Installed.png|center|thumb|Installed now]]<br />
<br />
''' 5. Enjoy! '''<br />
<br />
# mudlet is in the path, can just run it<br />
mudlet<br />
<br />
== Compiling on Arch Linux ==<br />
<br />
===AUR Install and Compile===<br />
Mudlet is available in the [https://aur.archlinux.org Arch User Repository].<br />
(If the AUR has become unmaintained/orphaned, then skip below to [https://wiki.mudlet.org/w/Compiling_Mudlet#Manual_Install_and_Compile Manual install].)<br />
<br />
To install it use your favourite AUR helper (helper tool will automatically resove dependancies); example using ''yay'' :<br />
yay -S mudlet<br />
<br />
For more info on this process, visit [https://wiki.archlinux.org/index.php/Arch_User_Repository Arch User Repository - ArchWiki].<br />
<br />
''Note: For the most recent development version of Mudlet, replace 'mudlet' with 'mudlet-git' in the above commands and proceed as described.''<br />
<br />
''Built in fonts have been disabled, but are available in packages listed as optional dependancies.''<br />
<br />
''Discord support in Mudlet depends on an external library provided by discord-rpc-api, which is also available in AUR, choose whichever variant suits you best.''<br />
<br />
===Manual Install and Compile===<br />
These instructions will get you setup compiling on Arch. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo pacman -S --needed cmake qt5-multimedia hunspell libzip lua51-filesystem qt5-gamepad lua51-luautf8 pugixml \<br />
ttf-font qtkeychain-qt5 boost qt5-tools ttf-bitstream-vera ttf-ubuntu-font-family noto-fonts-emoji glu luarocks<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo lua5.1 /usr/bin/luarocks install lcf<br />
sudo lua5.1 /usr/bin/luarocks install luautf8<br />
sudo lua5.1 /usr/bin/luarocks install lua-yajl<br />
sudo lua5.1 /usr/bin/luarocks install lrexlib-pcre<br />
sudo lua5.1 /usr/bin/luarocks install luasql-sqlite3<br />
sudo lua5.1 /usr/bin/luarocks install lua-zip<br />
<br />
There is an optional dependency for discord integration:<br />
git clone https://github.com/discord/discord-rpc<br />
cd discord-rpc<br />
mkdir build<br />
cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=/usr<br />
sudo cmake --build . --config Release --target install<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
'''4. installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''5. optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo pacman -S install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.↵Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybindings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
== Compiling on Fedora (aarch64) ==<br />
<br />
'''1. Install dependencies'''<br />
sudo dnf groupinstall "Development Tools" "Development Libraries"<br />
<br />
sudo dnf install compat-lua compat-lua-devel compat-lua-libs hunspell-devel lua5.1-filesystem luarocks pugixml-devel qtkeychain-qt5-devel bitstream-vera-fonts-all ccache qt-creator qt5-qtmultimedia-devel qt5-qtgamepad-devel yajl-devel qtchooser qt5-qttools-devel qt5-qttools-static zziplib-devel pcre-devel libzip-devel sqlite-devel<br />
<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luazip<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luasql-sqlite3<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lcf<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luautf8<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lua-yajl<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lrexlib-pcre<br />
In your user's home directory:<br />
<br />
If you use a bash shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .bashenv<br />
source .bashenv<br />
If you use a zsh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .zshenv<br />
source .zshenv<br />
If you use a csh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .cshenv<br />
source .cshenv<br />
This should cover paths, but you may want to reboot to be sure.<br />
<br />
'''2. Obtain the source code'''<br />
git clone --recursive --branch=development <nowiki>https://github.com/Mudlet/Mudlet.git</nowiki><br />
mkdir Mudlet/build<br />
cd Mudlet/src<br />
<br />
'''3. Make necessary compiling instruction adjustments'''<br />
<br />
Edit mudlet.pro - find these lines in mudlet.pro and make the following changes:<br />
linux {<br />
LIBS += \<br />
-llua5.1 \<br />
-lhunspell<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
We're adding a - between lua and 5.1 and adding -1.7 to hunspell under LIBS so that it becomes this:<br />
linux {<br />
LIBS += \<br />
-llua-5.1 \<br />
-lhunspell-1.7<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
Save and exit.<br />
<br />
'''4. Compile'''<br />
cd ../build<br />
Run this in the build directory:<br />
WITH_FONTS=NO WITH_OWN_QTKEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share qmake-qt5 PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1 LUA_SEARCH_OUT=lua-5.1 ../src/mudlet.pro<br />
An explanation of the qmake arguments -- we're passing these environment variables to mudlet.pro:<br />
WITH_FONTS=NO WITH_OWN_KEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share<br />
Adding build variables to mudlet.pro so that it finds the correct libraries:<br />
PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1<br />
And finally adding a build variable to translations/translated/updateqm.pri so that it uses the correct version of the Lua compiler (Fedora also comes with 5.4) to generate translation statistics.<br />
LUA_SEARCH_OUT=lua-5.1<br />
Once complete, run the following:<br />
<br />
If you have time to kill (About 10 minutes on an Apple M1 Max in Fedora):<br />
make<br />
If you want it done as fast as possible(Less than a minute on an Apple M1 Max in Fedora):<br />
make -j `nproc`<br />
Or if you want something in between, make -j `nproc` tells it to use all available processor cores. If you want to use a specific number instead (ie 2), you can use:<br />
make -j 2<br />
<br />
'''5. Install'''<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''6. Hang onto the cloned git repo '''<br />
If you need to uninstall, you can go back into the /build directory and 'sudo make uninstall'.<br />
<br />
== Compiling on Gentoo ==<br />
An [https://github.com/toaster/gentoo-overlay overlay containing Mudlet is available] for compiling Mudlet on Gentoo.<br />
<br />
== Compiling on Windows ==<br />
<br />
These instructions will get you setup compiling on Windows. <br />
<br />
Need a hand? Join us on the Mudlet [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Download Mudlet source code'''<br />
<br />
# Install [https://desktop.github.com/ Github Desktop].<br />
# Clone ([https://help.github.com/desktop/guides/contributing-to-projects/cloning-a-repository-from-github-to-github-desktop/#platform-windows instructions]) Mudlet's [https://github.com/mudlet/mudlet repository] to your local drive.<br />
{{note}} You must use a location on <code>C:\</code> without any spaces in folder names! <br />
<br />
'''2. Perform a one-time setup'''<br />
<br />
* Open powershell in the newly cloned folder by typing in <code>powershell</code> in the address bar:<br />
<br />
[[File:Open powershell in a folder.png|none|thumb|418x418px]]<br />
<br />
* Run <code>Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted</code> to enable the setup script to run and press <code>A</code>.<br />
* Run <code>./setup-windows-sdk.ps1</code><br />
<br />
This will automatically download all of the requires tools (including Python 2) and libraries, set them up for you, build Mudlet, and launch it! <br />
<br />
{{note}} If this script exits immediately, please [https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/install/installing-windows-powershell?view=powershell-7.1#upgrading-existing-windows-powershell upgrade your PowerShell version] first. You may also need to [https://learn.microsoft.com/de-de/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.4 allow to run scripts from the internet]<br />
<br />
{{note}} Depending on your Internet connection and computer speed, this one-time setup will take 30 minutes or more - so grab a cup of tea or coffee.<br />
<br />
'''3. Watch the magic happen'''<br />
<br />
Here is a video recording of the setup unfolding, compiling, etc. for your comparsion:<br />
<br />
[[File:Start-of-installation.gif|frame|none|Sometimes the output will get stuck and not progress - just press Enter to make it continue. This is a well-known [https://serverfault.com/questions/204150/sometimes-powershell-stops-sending-output-until-i-press-enter-why Powershell bug.]]]<br />
<br />
During the installation, you'll see the Qt installer window pop-up - this is normal:<br />
<br />
[[File:Qt-installer.gif|thumb|none]]<br />
<br />
The Qt installer might ask you about your data collection preferences - answer as you wish and the automated install will continue:<br />
<br />
[[File:Qt-installer-data-collection.png|thumb|none]]<br />
<br />
The installer's final step will be compiling all of the source code, which looks like this:<br />
<br />
[[File:Compiling-step.gif|thumb|none]]<br />
<br />
After it's all done, a Mudlet version ending in "-dev" will launch automatically:<br />
<br />
[[File:Mudlet-launching.gif|frame|none]]<br />
<br />
If something didn't work right, you can check out the verbose log that is available at <code>C:\src\verbose_output.log</code>.<br />
<br />
=== Coding on Mudlet ===<br />
<br />
Open <code>C:\<path to repository>\src\mudlet.pro</code> in Qt Creator, which resides here: <code>C:\Qt\Tools\QtCreator\bin\qtcreator.exe</code>. Then enable Debug and Release builds and hit ''Configure Project'':<br />
<br />
[[File:Selection_173.png|frame|none]]<br />
<br />
Press <code>Ctrl+5</code> and update project settings. Check how many logical processors are available in your system with the Task Manager:<br />
<br />
[[File:Task-manager.png|thumb|none|2 processors are available in this example]]<br />
<br />
And set this amount in Qt Creator:<br />
<br />
[[File:Change Qt Creator to use many cores.gif|frame|none]]<br />
<br />
Hit run:<br />
<br />
[[File:Selection 176.png|frame|none]]<br />
<br />
Click on '''Compile Output''' to see progress on compiling:<br />
<br />
[[File:Selection 177.png|frame|none]]<br />
<br />
When it's all ready, the new Mudlet with your changes will launch. '''You're all done'''!<br />
<br />
=== Contributing changes ===<br />
<br />
Once you're all done with your changes, contribute them to Mudlet using a [https://help.github.com/desktop/guides/contributing-to-projects/creating-a-pull-request/#platform-windows pull request]. Thanks for improving open-source!<br />
<br />
=== Uninstalling ===<br />
To get rid of everything, remove the following folders:<br />
<br />
C:\Libraries<br />
C:\LuaRocks<br />
C:\MinGW<br />
C:\Python27<br />
C:\Qt<br />
C:\src<br />
<br />
== Compiling on Github Codespaces ==<br />
<br />
[https://github.com/features/codespaces/ Github Codespaces] allow you to code and run Mudlet all from the browser - makes it a lot easier to get started. It also allows you to code Mudlet itself from any computer in the world! <br />
<br />
'''1. Create a new codespace'''<br />
<br />
Create a new Codespace by going to https://github.com/Mudlet/Mudlet using Google Chrome or Microsoft Edge (Firefox at the time of the writing doesn't have working copy/paste). There, click the green "Code" button, select the "Codespaces" tab and click "New codespace".<br />
<br />
[[File:New codespace.png|alt=New codespace screenshot|frameless]]<br />
<br />
'''2. Wait for it to load'''<br />
<br />
This will take a while (~5min) so grab a tea:<br />
<br />
[[File:Building Visual Studio Codespace.png|frameless]]<br />
<br />
'''3. Connect to the environment'''<br />
<br />
Go to the <code>Ports</code> section at the bottom and change the Port Privacy of the Open Mudlet port to Public:<br />
<br />
[[File:Port privacy in Github Codespaces.png|900x900px]]<br />
<br />
<br />
Then connect to your online Linux desktop with <code>mudlet</code> as the password by clicking on the web icon. <br />
<br />
[[File:Connect to remote machine.png|frameless]]<br />
<br />
<br />
In case it can't connect, make sure the port privacy is set to <code>Public</code>. If it still can't connect, try 4-5 more times - eventually it'll work.<br />
<br />
<br />
<br />
We chose a retro 90's look here to fit with the whole hacking theme, so if you see this you're good 😉<br />
<br />
[[File:Github_codespaces_desktop.png|alt=|frameless|400x400px]]<br />
<br />
'''4. Build Mudlet'''<br />
<br />
In Codespaces, hit <code>F7</code> and select <code>Let CMake guess...</code><br />
<br />
[[File:CMake configuration.png|none]]<br />
<br />
It will then start building Mudlet automatically. Using the [https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/about-billing-for-codespaces Basic instance] (only kind available in beta) the first-time build will take ~25min, so take a break here - you've made excellent progress. All follow-up compiles after this will be quicker, by the way.<br />
<br />
[[File:Building Mudlet in codespaces.png|none]]<br />
<br />
'''5. Run Mudlet'''<br />
<br />
[[File:Launch Mudlet.png|none]]<br />
<br />
Hit the little play button at the bottom of the screen, and Mudlet will now launch in the remote connection tab. Not working? [https://discord.gg/kuYvMQ9 We can help]. Otherwise, enjoy!<br />
<br />
[[File:Mudlet running remotely.png |500px]]<br />
<br />
Note: When the codespace is unused for a while, it will disconnect. It'll never disconnect while you're actively using it. See [https://github.com/microsoft/vscode-dev-containers/issues/588 Github issue] for details.<br />
<br />
== Developing with Docker ==<br />
<br />
Docker is a system designed for more reproducible and isolated builds. A docker setup exists and has been tested using Pop OS! 20.04 (which is derived from Ubuntu 20.04). First, follow the instructions to install both [https://docs.docker.com/get-docker/ docker] and [https://docs.docker.com/compose/install/ docker-compose].<br />
<br />
Clone the development branch<br />
<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
cd Mudlet/docker<br />
<br />
Make a local copy of the .env.template file:<br />
<br />
cp .env.template .env<br />
<br />
If you wish to customize things like the number of cores to use for building mudlet, feel free to change the corresponding values in the .env file.<br />
<br />
To run Qt-Creator and develop Mudlet, run <code>docker-compose up dev</code>.<br />
<br />
To run Mudlet, run <code>docker-compose up mudlet</code>. Note: At the moment, the mudlet build will not persist settings past container rebuilds.<br />
<br />
== Compiling on Windows 7+ (MSYS2 Alternative)==<br />
<br />
''INCOMPLETE, IN PROGRESS''<br />
<br />
Go to http://www.msys2.org/ to download the 64 bit MSYS2 installer (as of 2020/05/24 32 bit hosts - for '''compiling''' software, but ''not'' for using code built with it have been deprecated, the last installer for that 32-bit systems is held at: http://repo.msys2.org/distrib/i686/msys2-i686-20200517.exe) and follow the installation instructions (Steps 1 to 8 on that page), these instructions assume that "C:\msys64" or "C:\msys32" is used depending on the bitness of the system it is being installed on.<br />
<br />
Install the following packages (using "pacman -S ''packageName''"), the ones with a '''-i686-''' in the middle are the ones for 32-bit (i686) targets and '''-x86_64-''' are the ones for 64-bit targets - it is possible to install both for building Mudlet for target PCs of both bitnesses on a 64-bit host, it is not clear whether the reverse is true with a 32-bit host. These will pull in a number of other required packages as well (the ''--needed'' option prevents the re-installation of packages that have already been installed by MSYS2/Mingw-w64's own setup/installation process) - as some of the packages, e.g. ''base-devel'' are actually ''groups'' you will be requested to select which members of that group are actually required, it is easiest to just go with the default which is to install ALL of the packages in that group!<br />
<br />
: For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-i686-toolchain mingw-w64-i686-qt-creator mingw-w64-i686-qt5-multimedia mingw-w64-i686-libzip mingw-w64-i686-pugixml mingw-w64-i686-lua51 mingw-w64-i686-lua51-lpeg mingw-w64-i686-lua51-lsqlite3 mingw-w64-i686-hunspell mingw-w64-i686-boost mingw-w64-i686-yajl mingw-w64-i686-clang mingw-w64-i686-cmake mingw-w64-i686-SDL unzip<br />
</syntaxhighlight><br />
<br />
: For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-x86_64-toolchain mingw-w64-x86_64-qt-creator mingw-w64-x86_64-qt5-multimedia mingw-w64-x86_64-libzip mingw-w64-x86_64-pugixml mingw-w64-x86_64-lua51 mingw-w64-x86_64-lua51-lpeg mingw-w64-x86_64-lua51-lsqlite3 mingw-w64-x86_64-hunspell mingw-w64-x86_64-boost mingw-w64-x86_64-yajl mingw-w64-x86_64-clang mingw-w64-x86_64-cmake mingw-w64-x86_64-SDL unzip<br />
</syntaxhighlight><br />
<br />
::The ''*-zziplib'' libraries are used by the ''luazip'' luarock {from the Kepler project} but Mudlet will work perfectly well with the alternative ''lua-zip'' {from the brimworks GitHub repository - which also provides the ''lua-yajl'' rock} which does not require this library - although it is possible that it might still be pulled into the system as a dependency of another MSYS2 package.<br />
<br />
:Note that this will install the MSYS2 builds of the Qt Libraries and Creator IDE - ''THE ON/OFF-LINE INSTALLER OF THE QT LIBRARIES AND CREATOR VIA DOWNLOADS FROM QT ARE NOT USEFUL IN THIS SETUP!''<br />
<br />
:{| class="wikitable"<br />
|-<br />
|'''Attention - Luarocks packages problem'''<br />
|-<br />
| Recently the Luarocks project attempted to adopt the MSYS2/Mingw-w64 platform as one it would supported natively and the MSYS2/Mingw-w64 project went and upgraded its luarocks packages to make use of the changes and also on-board other improvements (and the version number increased from ''2.4.4-2'' to ''3.5.0-1'') unfortunately this completely broke them and although the issue has been reported ([https://github.com/msys2/MINGW-packages/issues/9037 MSYS2 Issue 9037]) a fix has not yet materialised. The only way to work around this in the meantime is to download the older package (with '''wget''') and install it manually (with '''pacman -U):<br />
|-<br />
|For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:19:09-- https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97905 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-i686-lua51-luarocks-2.4.4-2- 100%[===========================================================================>] 95.61K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:19:10 (1.43 MB/s) - ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97905/97905]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-i686-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-i686-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|-<br />
|For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:17:32-- https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97935 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-x86_64-lua51-luarocks-2.4.4- 100%[===========================================================================>] 95.64K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:17:32 (1.28 MB/s) - ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97935/97935]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-x86_64-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-x86_64-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|}<br />
<br />
::{| class="wikitable"<br />
|-<br />
|'''Warning for those planning to build ''both'' 32 and 64 bit versions'''<br />
|-<br />
|If one is planning to build ''both'' bitness binaries an additional step is necessary as, by default, the MSYS2/Mingw-w64 ''luarocks'' setup seems to place any ''.lua'' or ''.dll'' modules it builds/installs on a per user (the so-called ''local'' basis) into the same directories with the same names. This is no good for two reasons:<br />
* It is difficult to work out which bitness a particular module is for and whilst 32-bit modules ''might'' work in a 64-bit environment the reverse is definitely not the case<br />
* It confuses the Luarocks package management systems (as effectively there will be two different luarocks systems operated side-by-side)<br />
<br />
This can be worked around by:<br />
* Editing the '''.\etc\luarocks\config-5.1.lua''' for each bitness so that the ''rocks_trees'' table entry for the ''user'' key is changed from this in '''both''' files:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks]] },</syntaxhighlight><br />
to something different for each of them, say, for example, for the the 64-bit one:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks-x64]] },</syntaxhighlight><br />
* Then by specifying the ''rocktree'' name ('''user''') on the command line when '''installing''' or '''building''' a luarock with the ''--tree user'' argument - note that for some inexplicable reason the ''--local'' argument that '''''should''''' do the same thing does not seem to work for these two actions, it is not clear whether this is a MSYS2/Mingw-w64 specific issue or it goes further upstream to Luarocks in general. Thus, in the next step it will be necessary to change from using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --local rockname<br />
</syntaxhighlight><br />
to, for the example given:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --tree user rockname<br />
</syntaxhighlight><br />
where ''user'' is the literal string "user" to match the Lua table key in the rock_trees and not, in this case, a representation of the user-name/account of the person performing the action.<br />
|}<br />
<br />
From the Windows ''Start menu'' start a shell appropriate for the target with the bitness to be built for i.e. '''"MSYS2 Mingw 32-Bit"''' or '''"MSYS2 Mingw 64-Bit"'''. This will likely position the current directory to the root directory of the MSYS2 environment, the text about the prompt line (the one with the "$") will contain three different bits of colored text '''username@computername'''; one of '''MSYS2'''/'''MINGW32'''/'''MINGW''' depending on the type of shell you currently in use and '''/''' representing the root directory (which will actually be the directory MSYS2 was installed to, for example on the author's system this is "C:/msys64"). Change to the home directory in MYSY by entering "cd" on its own with no argument (it will show up as '''~''' and it would work out to be, for '''user''' to be '''c:/msys64/home/user''' or '''c:/msys32/home/user''' (if both bitnessess are to be built it will be necessary to repeat the following step twice, one for each and also observe the steps in the above warning) install the following luarocks:<br />
<br />
:{| class="wikitable sortable"<br />
|-<br />
! rockname<br />
|-<br />
| lrexlib-pcre<br />
|-<br />
| lua-yajl<br />
|-<br />
| luafilesystem<br />
|-<br />
| luasql-sqlite3<br />
|-<br />
| luautf8<br />
|-<br />
| luazip or lua-zip<br />
|}<br />
by using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install [--local] rockname<br />
</syntaxhighlight><br />
The ''--local'' argument is an optional one that causes the luarock and the lua module to be installed on a per-user basis rather than on a system wide one, this may be important if the PC is used by multiple users and more than one of them uses Lua in any form.<br />
<br />
Now create somewhere to work on the Mudlet source, assuming that other software coding with other pieces of software will be done, create a sub-directory in the home directory, and then make one just for Mudlet under that:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ mkdir ./src<br />
<br />
MINGW64 user@computer ~<br />
$ mkdir ./src/mudlet<br />
</syntaxhighlight><br />
<br />
Change to that directory and get the source code:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ cd ./src/mudlet<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git clone git://github.com/Mudlet/Mudlet.git .<br />
</syntaxhighlight><br />
<br />
If you are planning to contribute to the Mudlet code you will want to visit Github and create your own GitHub repository, you can then push commits (changes to the code) to there and raise a Pull Request for a Mudlet Maker to drag the changes over to the above repository. You will want to add your repository and perhaps those of some other contributors so you can track what they are doing and see/try/experiment with their PRs before they get merged. Therefore you will want to add some other repositories into the mix. The names you use to identify those other repositories will show up in any utility that works with the repository you have just created in the above "clone" operation and can be anything you like but it makes sense to have clear names. So to add "myName", and those of the leading active contributors to the Mudlet codebase you will use:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Mine https://github.com/myName/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Vadim https://github.com/vadi2/Mudlet.git <br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add SlySven https://github.com/SlySven/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Kebap https://github.com/Kebap/Mudlet.git<br />
</syntaxhighlight><br />
<br />
Now obtain ''all'' the versions of the code with:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git fetch --all<br />
</syntaxhighlight><br />
<br />
This will produce a lot of lines of output the first time and it might take a little while on a slow connection...<br />
<br />
{Section missing - it turns out that the default GUI git tools that the author of this section would normally use: "gitk" and "git gui" have some problems in the versions currently supplied from the MSYS2 system - and it was necessary to import them from the set that the Git4Win have patched - see https://github.com/git-for-windows/git/wiki/Install-inside-MSYS2-proper }<br />
<br />
Some modifications to the qmake/cmake project files are needed and these are now supported in the main ''development'' branch in the upstream {the Mudlet organisation's own GitHub repository} which requires that there is an environmental variable '''WITH_MAIN_BUILD_SYSTEM''' and it is set to the (case-insensitive) value '''NO''':<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export WITH_MAIN_BUILD_SYSTEM=NO<br />
</syntaxhighlight><br />
<br />
Also the '''MINGW_BASE_DIR''' environmental variable will need to be set to the root directory for the MINGW-W64 installation for the appropriate bitness of the target to be made. For building on a 64-Bit Host {the PC that is ''compiling'' the code} to make a 64-Bit application this will likely be '''C:/msys64/mingw64''' and for a 32-Bit application it will probably be '''C:/msys64/ming32'''.<br />
: E.g. <syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw64 # To build a 64-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
: Or: <syntaxhighlight lang="shell"><br />
MINGW32 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw32 # To build a 32-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
Now checkout a branch {ideally, if working on solving a new issue, or adding a feature or resolving a bug, one should create a new branch that is a copy of the current, upstream ''development'' branch} and then work on it with Qt Creator:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ qtcreator &<br />
</syntaxhighlight><br />
<br />
Load in the '''mudlet.pro''' ''qmake'' project file in the '''src''' subdirectory (e.g. for this example: '''c:/msys64/home/user/src/mudlet/src/mudlet.pro''') and get hacking...<br />
<br />
= Setting up IDEs =<br />
== CLion ==<br />
=== Qt not detected ===<br />
If you'd like to use CLion and it is giving the following error:<br />
<br />
<nowiki><br />
By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has<br />
asked CMake to find a package configuration file provided by "Qt5Core", but<br />
CMake did not find one.<br />
<br />
...<br />
</nowiki><br />
<br />
You can fix this by setting <code>-DCMAKE_PREFIX_PATH=<your Qt + version + compiler location></code>. For example: <code>-DCMAKE_PREFIX_PATH=/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code> [[File:CLion CMake settings - finidng Qt.png|700px|none]]<br />
<br />
=== CLion setup on Windows ===<br />
After running <code>setup-windows-sdk.ps1</code> make sure to set Cmake options to:<br />
-DCMAKE_PREFIX_PATH=C:\Qt\Tools\mingw730_32;C:\Qt\5.14.2\mingw73_32 -DBoost_INCLUDE_DIR=C:\Libraries\boost_1_77_0<br />
''Directories might vary slightly, when different Qt, Boost or MinGW version will be used.''<br />
<br />
[[File:Clion Settings - Cmake.png|frameless|700x700px]]<br />
<br />
<br />
<br />
You will need 32 bit version of MinGW. Set it in the <code>Toolset</code> field to:<br />
C:\Qt\Tools\mingw730_32<br />
<br />
''Directory may be slightly different if MinGW version used will change.''<br />
<br />
[[File:Toolchain.png|frameless|700x700px]]<br />
<br />
=== Clang Tidy ===<br />
Ensure that CLion is set to run the project's [https://www.jetbrains.com/help/clion/clang-tidy-checks-support.html#paticularcheck .clang-tidy checks] with the <code>Prefer .clang-tidy files over IDE settings</code> option:<br />
<br />
[[File:Clang Tidy CLIon.png|700px|none]]<br />
<br />
This helps us catch any issues just a bit earlier.<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in CLion, adjust the CMake settings:<br />
<br />
[[File:Clion_cmake_settings.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
=== Clang Format ===<br />
Ensure that [https://www.jetbrains.com/help/clion/clangformat-as-alternative-formatter.html#clion-support CLion is set to use] the <code>.clang-format</code> formatting style:<br />
<br />
[[File:Clang-format CLion.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
== Visual Studio Code ==<br />
<br />
To set the path in Visual Studio Code, open settings, search for <code>cmake environment</code> and set the <code>CMAKE_PREFIX_PATH</code> to your path, such as <code>/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code>:<br />
<br />
[[File:CMake path in Visual Studio Code.png|none]]<br />
<br />
===Clang Tidy===<br />
clang-tidy catches common programming issues, run it by selecting 'Analysis' from the command palette (Ctrl+Shift+P by default):<br />
<br />
[[File:Clang-tidy in vscode.png|none]]<br />
<br />
It is also possible [https://devblogs.microsoft.com/cppblog/visual-studio-code-c-december-2021-update-clang-tidy/ check status of analysis and cancel if needed].<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in VSCode, set the <code>cmake.configureSettings</code> variable:<br />
<br />
[[File:Cmake.configureSettings option in vscode.png|frameless|890x890px]]<br />
<br />
[[File:Choosing which sanitizers in vscode to use.png|frameless|891x891px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
== Qt Creator==<br />
===Clang Tidy and Clazy===<br />
<br />
Configure Mudlet-specific checks for [https://clang.llvm.org/extra/clang-tidy/ clang-tidy] and [https://github.com/KDE/clazy clazy] tools help catch any issues early on. See [https://doc.qt.io/qtcreator/creator-clang-tools.html Qt Creator's instructions] for setting this up - clang-tidy can use the <code>.clang-tidy</code> file that's available at the root of the repository, and for clazy enable <code>level0</code> and <code>level1</code> checks.<br />
<br />
[[File:Clang tidy configuration.png|frame|none]]<br />
[[File:Clazy configuration.png|frame|none]]<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in Qt creator, head to <code>Projects</code> - <code>Build</code>: <br />
<br />
[[File:Sanitisers in qt creator.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
==Clang Format==<br />
Ensure that Qt Creator is set to use the <code>.clang-format</code> formatting style in the C++ settings. Turn on <code>Format instead of indenting</code> for <code>Ctrl+I</code> to format code, and ensure <code>Override Clang Format configuration file</code> is disabled:<br />
<br />
[[File:Qt Creator clang format.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
<br />
=Building with multiple versions of Lua=<br />
Mudlet uses Lua 5.1 only, so if you are compiling on a system that also has later versions installed, you might get the following error: <code>‘LUA_GLOBALSINDEX’ was not declared in this scope</code>.<br />
<br />
To fix this, pass the path to Lua headers explicitly. For CMake: <code>-DLUA_INCLUDE_DIR=/usr/include/lua5.1</code> (adjust as needed).<br />
<br />
= Compile Time Flags =<br />
<br />
<nowiki><br />
DEBUG_UTF8_PROCESSING - for decoding the UTF-8 (1 byte with the MSB set or 2, 3 or 4 bytes) encoding<br />
DEBUG_GB_PROCESSING - for decoding the GBK (2 bytes) or GB18030 (2 or 4 bytes) encodiing<br />
DEBUG_BIG5_PROCESSING - for decoding the Big5-ETEN or Big5-HKSCS encodings<br />
DEBUG_EUC_KR_PROCESSING - for decoding the EUC_KR encoding<br />
DEBUG_SGR_PROCESSING - decoding the <ESC>[ codes (that pair of bytes being the CSI "Control Sequence Introducer" - including the one ending in m which is the "Set Graphics Rendition" that Mudlet (and other MUD clients and other things) use to control colours and other font effects.<br />
DEBUG_OSC_PROCESSING - decode the <ESC>] codes (that MUST end with a <ESC>\) - currently Mudlet only handles a couple of these OSC "Operating System Commands".<br />
DEBUG_MXP_PROCESSING - stuff to do with the MXP protocol - which uses a <ESC> ... z sequence of characters to do some things...<br />
</nowiki></div>Kebaphttps://wiki.mudlet.org/index.php?title=Compiling_Mudlet&diff=21488Compiling Mudlet2024-02-25T21:10:24Z<p>Kebap: </p>
<hr />
<div>{{TOC right}}<br />
<br />
If you just want to use Mudlet, you can skip these steps, and use one of the already ready (pre-compiled) installers [https://www.mudlet.org/download ready for download].<br />
<br />
Otherwise, hop in for new adventure! <br />
<br />
[[File:Easy Mudlet code understanding.png|frame|300px|none]]<br />
<br />
= Key contributing information =<br />
<br />
Clang format is used to automatically format code submissions using the [https://github.com/Mudlet/Mudlet/blob/development/src/.clang-format src/.clang-format] style. [http://doc.qt.io/qtcreator/creator-beautifier.html See here] how to enable clang-format with Qt Creator - and make sure to specify the 'File' option for the configuration style.<br />
<br />
Branches:<br />
<br />
'''development''' is the development branch where new features can go.<br />
<br />
Workflow:<br />
<br />
Fork and submit a PR with your changes ([https://guides.github.com/activities/forking/ Github tutorial]).<br />
<br />
Here is a list of package versions delivered with different Linux distros. You may want to upgrade these: <br />
https://repology.org/project/mudlet/versions<br />
<br />
= Lua & Luarocks =<br />
<br />
Mudlet includes a [https://en.wikipedia.org/wiki/Lua_(programming_language) Lua] (version 5.1) scripting system for the end-user, which you, as a reader of this Wiki, may already be aware of! If not, you might wish to (after you have got your hands on a working Mudlet) take a look at [https://wiki.mudlet.org/w/Manual:Lua_Functions Mudlet Lua API] as that is the recommended place to find out the details of all the functions that Mudlet provides on top of the core Lua functionality.<br />
<br />
Some of that ability comes from extra code that is not built-in to Lua but is in the form of external modules either in the form of script (text) files written in the Lua language itself or binary (library) files compiled from (usually but not exclusively [https://en.wikipedia.org/wiki/C_(programming_language) 'C']) source code. In order to have that functionality Mudlet makes use of several of these modules which can most readily (if not already available as "packages" for a particular Operating System) be obtained as '''rocks''' from the public [https://en.wikipedia.org/wiki/LuaRocks Luarocks] collection. Such a rock actually consists of a ''rockspec'' file that gives instructions to the Luarocks tool how to obtains the (source) code, compile it on any supported OS into the form that a Lua interpreter (including the one included in '''''each''''' running Mudlet ''profile'') can use, and where and what it will be placed and called when it has been made. After that it should be available to Lua via the ''require'' command.<br />
<br />
Anyone compiling Mudlet for themselves will find it desirable to ensure they have a usable Luarocks installation and have the ''lua-yajl'' module installed before commencing to compile Mudlet itself; this is because a Lua (version 5.1) interpreter and that module are used within the build process of making the executable code that is the Mudlet application.<br />
<br />
= Compiling =<br />
<br />
== Compiling on Ubuntu ==<br />
<br />
These instructions will get you setup compiling on Ubuntu. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
===Ubuntu 22.04===<br />
Following instructions will work on Ubuntu 22.04 as well as all its flavours and derivatives (such as KDE Neon, for example)<br />
Important thing is to have ''Universe'' repository enabled in your package manager. (on Ubuntu you will have all the repositories that you need already enabled by default.)<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo apt install ubuntu-restricted-extras qtcreator build-essential git zlib1g-dev libhunspell-dev \<br />
libpcre3-dev libzip-dev libboost-dev libboost-all-dev libyajl-dev libpulse-dev libpugixml-dev \<br />
liblua5.1-0-dev lua-filesystem lua-zip lua-sql-sqlite3 luarocks ccache lua5.1 \<br />
libglu1-mesa-dev mesa-common-dev libglib2.0-dev libgstreamer1.0-dev libqt5opengl5-dev \<br />
qtmultimedia5-dev qttools5-dev qt5keychain-dev libsecret-1-dev \<br />
libqt5texttospeech5-dev qtspeech5-flite-plugin qtspeech5-speechd-plugin \<br />
qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo luarocks install lcf<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
sudo luarocks install lrexlib-pcre<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
4. '''installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
5. '''optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo apt install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.<br />
Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybidings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
===Other Ubuntu Versions===<br />
<br />
Most of the installation instructions for 22.04 should work for older versions as well. Of note is the required version of Qt, which is 5.14. If your used version of Ubuntu only supplies older<br />
Qt versions, have a look at [https://launchpad.net/~beineri Stephan Binners PPAs], which supplies a whole range of packages for different Ubuntu versions. Be sure to read the installation and<br />
usage instructions as Qt is installed to /opt and requires sourcing a script to set up.<br />
<br />
== Compiling on Chrome OS ==<br />
<br />
These instructions will get you setup compiling on Chrome OS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Install dependencies'''<br />
<br />
sudo apt install git build-essential qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools \<br />
qtmultimedia5-dev qttools5-dev \<br />
lua5.1 liblua5.1-0-dev libpcre3-dev libboost-dev zlib1g-dev cmake \<br />
libhunspell-dev lua-rex-pcre2 lua-sql-sqlite3 lua-filesystem lua-zip libyajl-dev \<br />
libzip-dev libglu1-mesa-dev ccache libpugixml-dev mesa-common-dev qtcreator \<br />
libpulse-dev libglib2.0-dev luarocks libboost-all-dev libsecret-1-dev \<br />
ninja-build libsecret-1-dev<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''3. Get Mudlet source'''<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''4. Create a build directory'''<br />
<br />
cd mudlet<br />
mkdir build && cd build<br />
<br />
'''5. Run the following command '''<br />
<br />
cmake .. -G Ninja<br />
<br />
'''then:'''<br />
<br />
ninja<br />
<br />
'''5. Start the application you have just compiled - enjoy'''<br />
<br />
src/mudlet<br />
{{Note}}Did <code>ninja</code> fail with <code>c++: fatal error: Killed signal terminated program cclplus</code>? Try again with <code>ninja -j 2</code><br />
<br />
== Compiling on macOS ==<br />
<br />
These instructions will get you setup compiling on macOS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums] otherwise.<br />
<br />
<br />
'''1. Install prerequisites'''<br />
<br />
Install [https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12 XCode], command line tools for XCode, and [http://brew.sh HomeBrew].<br />
<br />
Once everything is installed, do:<br />
<br />
brew doctor<br />
brew update<br />
brew install git<br />
<br />
'''2. Get Mudlet source'''<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git <br />
<br />
'''3. Go to the parent of the mudlet "src" folder and create (if necessary) a build subdirectory (this is so that we can build out of source which keeps the source code clean)'''<br />
cd Mudlet && mkdir build<br />
<br />
'''3. Setup your environment'''<br />
./CI/travis.osx.before_install.sh<br />
./CI/travis.osx.install.sh<br />
<br />
luarocks config lua_version 5.1<br />
eval `luarocks path --lua-version=5.1`<br />
For the following, one may have to add <code>''_DIR="/opt/homebrew/"''</code> such as <code>PCRE_DIR="/opt/homebrew/"</code> or <code>ZIP_DIR="/opt/homebrew/"</code> if the installation could not find header files.<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lrexlib-pcre PCRE_DIR=`brew --prefix pcre`<br />
brew install sqlite<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luasql-sqlite3 SQLITE_DIR=`brew --prefix sqlite` <br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luautf8<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luafilesystem<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-zip ZIP_DIR=`brew --prefix libzip`<br />
<br />
brew install boost<br />
OK to answer yes to delete files if prompted for the <code>rm</code> command above.<br />
<br />
'''4. Run the following commands'''<br />
<br />
cd ../../build<br />
cmake ../../Mudlet -DCMAKE_PREFIX_PATH=`brew --prefix qt5`<br />
make -j `sysctl -n hw.ncpu`<br />
<br />
<br />
'''5. Enjoy'''<br />
<br />
The mudlet.app is now available in <code>src/</code> for launching:<br />
<br />
open src/Mudlet.app<br />
<br />
'''6. Qt Creator setup'''<br />
<br />
No Lua installation is found, despite it existing on your system? Launch Qt Creator by doing <code>open /Applications/Qt Creator.app</code> (location depends on how you installed it).<br />
<br />
Receiving a <code>No rule to make target ... libQt5UiTools_debug.a</code> error? A workaround is to [https://bugreports.qt.io/browse/QTBUG-81251?focusedCommentId=538705&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-538705 symlink a file].<br />
<br />
Mudlet in Qt Creator is not launching due to <code>dyld: Symbol not found: __cg_jpeg_resync_to_restart</code>? See [https://stackoverflow.com/a/44851430/72944 here] for a workaround.<br />
<br />
====== 7. Troubleshooting ======<br />
If you exhaust all efforts to get YAJL to compile on your local system with homebrew, [https://github.com/lloyd/yajl/ clone from the YAJL repository] then <code>./configure && sudo make install</code>.<br />
<br />
== Compiling on Debian 'Sid' ==<br />
<br />
'''1. Install required packages from main repo.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev<br />
<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Grab latest Mudlet source.'''<br />
<br />
mkdir ~/projects && cd ~/projects && git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
cd ~/projects/mudlet/src<br />
<br />
qmake<br />
<br />
make<br />
<br />
sudo make install<br />
<br />
== Compiling on Debian 11 'Bullseye' ==<br />
<br />
'''1. Install required packages.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev \<br />
qttools5-dev luarocks ccache libpugixml-dev libqt5texttospeech5-dev qtspeech5-flite-plugin \<br />
qtspeech5-speechd-plugin libqt5opengl5-dev ninja-build cmake libsecret-1-dev<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Get Mudlet source.'''<br />
<br />
mkdir ~/source && cd ~/source<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git<br />
<br />
Note: the line above will check out `development` branch source code, and this might not always be stable. You can check out the latest release source code using this command:<br />
<br />
git clone --recursive --branch main https://github.com/Mudlet/Mudlet.git<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
mkdir ~/source/Mudlet/build && cd ~/source/Mudlet/build<br />
<br />
qmake ../src/mudlet.pro<br />
<br />
make -j `nproc`<br />
<br />
sudo make install<br />
<br />
After these steps you can run Mudlet by typing:<br />
<br />
mudlet<br />
<br />
'''4. (Optional) Discord library'''<br />
<br />
If you get the following error;<br />
<br />
Could not find Discord library - searched in:<br />
<br />
you need to specify the discord library in your build. Run the following, changing the path where necessary;<br />
<br />
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/mudlet-dev/Mudlet/3rdparty/discord/rpc/lib/<br />
<br />
and recompile. You should see<br />
<br />
Discord integration loaded. Using functions from: "libdiscord-rpc.so"<br />
<br />
== Compiling on Raspberry Pi OS ==<br />
<br />
These instructions will get you compiling and running Mudlet on Raspberry Pi OS (Buster). Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
''' 1.a Install apt dependencies '''<br />
<br />
sudo apt-get update<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-graph-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev cmake<br />
<br />
<br />
[[File:Apt-get-install-y-n.png|center|thumb|installing apt dependencies]]<br />
<br />
''' 1.b Install luarocks dependencies '''<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl YAJL_LIBDIR=`find /usr -name "libyajl.so" -printf '%h\n'` YAJL_INCDIR=/usr/include<br />
<br />
<br />
[[File:After-luarocks-dependencies.png|center|thumb|after luarocks dependencies]]<br />
<br />
''' 2. Get Mudlet source '''<br />
<br />
mkdir ~/source && cd ~/source <br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
<br />
[[File:After-get-mudlet-source.png|center|thumb|After cloning]]<br />
<br />
''' 3. Create a build directory '''<br />
<br />
cd Mudlet && mkdir build && cd build<br />
<br />
''' 4. Run the following commands to build '''<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake ../src/mudlet.pro<br />
<br />
:If you get a response along the lines of:<br />
<br />
qmake: could not find a Qt installation of ''<br />
<br />
:then you likely have ''qtchooser'' present in your system that allows for both Qt4 and Qt5 (or more than one Qt5 version) and it modifiers qmake and some other Qt development programs to take an additional argument to specify which version to use. In that case you should use:<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake -qt=qt5 ../src/mudlet.pro<br />
<br />
[[File:After-qmake.png|center|thumb|After qmake]]<br />
<br />
''' THEN: '''<br />
:For the fastest compile time while still being able to use the system at all (~35min on a RPi4 with 4GB of ram)<br />
make -j $(expr `nproc` - 1)<br />
<br />
''' OR: '''<br />
<br />
:Use this if you have an older Raspberry Pi. Be prepared for it to take a while (over an hour) - ''it is not recommended to try to more than one compilation task at a time on the older systems with the '''-j''' option as they will only have a system memory with enough space for one of some of those tasks'':<br />
make<br />
<br />
[[File:Success.png|center|thumb|Success!]]<br />
<br />
''' 4. Install the application you have just compiled '''<br />
<br />
sudo make install<br />
<br />
[[File:Installed.png|center|thumb|Installed now]]<br />
<br />
''' 5. Enjoy! '''<br />
<br />
# mudlet is in the path, can just run it<br />
mudlet<br />
<br />
== Compiling on Arch Linux ==<br />
<br />
===AUR Install and Compile===<br />
Mudlet is available in the [https://aur.archlinux.org Arch User Repository].<br />
(If the AUR has become unmaintained/orphaned, then skip below to [https://wiki.mudlet.org/w/Compiling_Mudlet#Manual_Install_and_Compile Manual install].)<br />
<br />
To install it use your favourite AUR helper (helper tool will automatically resove dependancies); example using ''yay'' :<br />
yay -S mudlet<br />
<br />
For more info on this process, visit [https://wiki.archlinux.org/index.php/Arch_User_Repository Arch User Repository - ArchWiki].<br />
<br />
''Note: For the most recent development version of Mudlet, replace 'mudlet' with 'mudlet-git' in the above commands and proceed as described.''<br />
<br />
''Built in fonts have been disabled, but are available in packages listed as optional dependancies.''<br />
<br />
''Discord support in Mudlet depends on an external library provided by discord-rpc-api, which is also available in AUR, choose whichever variant suits you best.''<br />
<br />
===Manual Install and Compile===<br />
These instructions will get you setup compiling on Arch. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo pacman -S --needed cmake qt5-multimedia hunspell libzip lua51-filesystem qt5-gamepad lua51-luautf8 pugixml \<br />
ttf-font qtkeychain-qt5 boost qt5-tools ttf-bitstream-vera ttf-ubuntu-font-family noto-fonts-emoji glu luarocks<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo lua5.1 /usr/bin/luarocks install lcf<br />
sudo lua5.1 /usr/bin/luarocks install luautf8<br />
sudo lua5.1 /usr/bin/luarocks install lua-yajl<br />
sudo lua5.1 /usr/bin/luarocks install lrexlib-pcre<br />
sudo lua5.1 /usr/bin/luarocks install luasql-sqlite3<br />
sudo lua5.1 /usr/bin/luarocks install lua-zip<br />
<br />
There is an optional dependency for discord integration:<br />
git clone https://github.com/discord/discord-rpc<br />
cd discord-rpc<br />
mkdir build<br />
cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=/usr<br />
sudo cmake --build . --config Release --target install<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
'''4. installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''5. optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo pacman -S install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.↵Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybindings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
== Compiling on Fedora (aarch64) ==<br />
<br />
'''1. Install dependencies'''<br />
sudo dnf groupinstall "Development Tools" "Development Libraries"<br />
<br />
sudo dnf install compat-lua compat-lua-devel compat-lua-libs hunspell-devel lua5.1-filesystem luarocks pugixml-devel qtkeychain-qt5-devel bitstream-vera-fonts-all ccache qt-creator qt5-qtmultimedia-devel qt5-qtgamepad-devel yajl-devel qtchooser qt5-qttools-devel qt5-qttools-static zziplib-devel pcre-devel libzip-devel sqlite-devel<br />
<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luazip<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luasql-sqlite3<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lcf<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luautf8<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lua-yajl<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lrexlib-pcre<br />
In your user's home directory:<br />
<br />
If you use a bash shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .bashenv<br />
source .bashenv<br />
If you use a zsh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .zshenv<br />
source .zshenv<br />
If you use a csh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .cshenv<br />
source .cshenv<br />
This should cover paths, but you may want to reboot to be sure.<br />
<br />
'''2. Obtain the source code'''<br />
git clone --recursive --branch=development <nowiki>https://github.com/Mudlet/Mudlet.git</nowiki><br />
mkdir Mudlet/build<br />
cd Mudlet/src<br />
<br />
'''3. Make necessary compiling instruction adjustments'''<br />
<br />
Edit mudlet.pro - find these lines in mudlet.pro and make the following changes:<br />
linux {<br />
LIBS += \<br />
-llua5.1 \<br />
-lhunspell<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
We're adding a - between lua and 5.1 and adding -1.7 to hunspell under LIBS so that it becomes this:<br />
linux {<br />
LIBS += \<br />
-llua-5.1 \<br />
-lhunspell-1.7<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
Save and exit.<br />
<br />
'''4. Compile'''<br />
cd ../build<br />
Run this in the build directory:<br />
WITH_FONTS=NO WITH_OWN_QTKEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share qmake-qt5 PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1 LUA_SEARCH_OUT=lua-5.1 ../src/mudlet.pro<br />
An explanation of the qmake arguments -- we're passing these environment variables to mudlet.pro:<br />
WITH_FONTS=NO WITH_OWN_KEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share<br />
Adding build variables to mudlet.pro so that it finds the correct libraries:<br />
PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1<br />
And finally adding a build variable to translations/translated/updateqm.pri so that it uses the correct version of the Lua compiler (Fedora also comes with 5.4) to generate translation statistics.<br />
LUA_SEARCH_OUT=lua-5.1<br />
Once complete, run the following:<br />
<br />
If you have time to kill (About 10 minutes on an Apple M1 Max in Fedora):<br />
make<br />
If you want it done as fast as possible(Less than a minute on an Apple M1 Max in Fedora):<br />
make -j `nproc`<br />
Or if you want something in between, make -j `nproc` tells it to use all available processor cores. If you want to use a specific number instead (ie 2), you can use:<br />
make -j 2<br />
<br />
'''5. Install'''<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''6. Hang onto the cloned git repo '''<br />
If you need to uninstall, you can go back into the /build directory and 'sudo make uninstall'.<br />
<br />
== Compiling on Gentoo ==<br />
An [https://github.com/toaster/gentoo-overlay overlay containing Mudlet is available] for compiling Mudlet on Gentoo.<br />
<br />
== Compiling on Windows ==<br />
<br />
These instructions will get you setup compiling on Windows. <br />
<br />
Need a hand? Join us on the Mudlet [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Download Mudlet source code'''<br />
<br />
# Install [https://desktop.github.com/ Github Desktop].<br />
# Clone ([https://help.github.com/desktop/guides/contributing-to-projects/cloning-a-repository-from-github-to-github-desktop/#platform-windows instructions]) Mudlet's [https://github.com/mudlet/mudlet repository] to your local drive.<br />
{{note}} You must use a location on <code>C:\</code> without any spaces in folder names! <br />
<br />
'''2. Perform a one-time setup'''<br />
<br />
* Open powershell in the newly cloned folder by typing in <code>powershell</code> in the address bar:<br />
<br />
[[File:Open powershell in a folder.png|none|thumb|418x418px]]<br />
<br />
* Run <code>Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted</code> to enable the setup script to run and press <code>A</code>.<br />
* Run <code>./setup-windows-sdk.ps1</code><br />
<br />
This will automatically download all of the requires tools (including Python 2) and libraries, set them up for you, build Mudlet, and launch it! <br />
<br />
{{note}} If this script exits immediately, please [https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/install/installing-windows-powershell?view=powershell-7.1#upgrading-existing-windows-powershell upgrade your PowerShell version] first. You may also need to [https://learn.microsoft.com/de-de/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.4 allow to run scripts from the internet]<br />
<br />
{{note}} Depending on your Internet connection and computer speed, this one-time setup will take 30 minutes or more - so grab a cup of tea or coffee.<br />
<br />
'''3. Watch the magic happen'''<br />
<br />
Here is a video recording of the setup unfolding, compiling, etc. for your comparsion:<br />
<br />
[[File:Start-of-installation.gif|frame|none|Sometimes the output will get stuck and not progress - just press Enter to make it continue. This is a well-known [https://serverfault.com/questions/204150/sometimes-powershell-stops-sending-output-until-i-press-enter-why Powershell bug.]]]<br />
<br />
During the installation, you'll see the Qt installer window pop-up - this is normal:<br />
<br />
[[File:Qt-installer.gif|thumb|none]]<br />
<br />
The Qt installer might ask you about your data collection preferences - answer as you wish and the automated install will continue:<br />
<br />
[[File:Qt-installer-data-collection.png|thumb|none]]<br />
<br />
The installer's final step will be compiling all of the source code, which looks like this:<br />
<br />
[[File:Compiling-step.gif|thumb|none]]<br />
<br />
After it's all done, a Mudlet version ending in "-dev" will launch automatically:<br />
<br />
[[File:Mudlet-launching.gif|frame|none]]<br />
<br />
If something didn't work right, you can check out the verbose log that is available at <code>C:\src\verbose_output.log</code>.<br />
<br />
=== Coding on Mudlet ===<br />
<br />
Open <code>C:\<path to repository>\src\mudlet.pro</code> in Qt Creator, which resides here: <code>C:\Qt\Tools\QtCreator\bin\qtcreator.exe</code>. Then enable Debug and Release builds and hit ''Configure Project'':<br />
<br />
[[File:Selection_173.png|frame|none]]<br />
<br />
Press <code>Ctrl+5</code> and update project settings. Check how many logical processors are available in your system with the Task Manager:<br />
<br />
[[File:Task-manager.png|thumb|none|2 processors are available in this example]]<br />
<br />
And set this amount in Qt Creator:<br />
<br />
[[File:Change Qt Creator to use many cores.gif|frame|none]]<br />
<br />
Hit run:<br />
<br />
[[File:Selection 176.png|frame|none]]<br />
<br />
Click on '''Compile Output''' to see progress on compiling:<br />
<br />
[[File:Selection 177.png|frame|none]]<br />
<br />
When it's all ready, the new Mudlet with your changes will launch. '''You're all done'''!<br />
<br />
=== Contributing changes ===<br />
<br />
Once you're all done with your changes, contribute them to Mudlet using a [https://help.github.com/desktop/guides/contributing-to-projects/creating-a-pull-request/#platform-windows pull request]. Thanks for improving open-source!<br />
<br />
=== Uninstalling ===<br />
To get rid of everything, remove the following folders:<br />
<br />
C:\Libraries<br />
C:\LuaRocks<br />
C:\MinGW<br />
C:\Python27<br />
C:\Qt<br />
C:\src<br />
<br />
== Compiling on Github Codespaces ==<br />
<br />
[https://github.com/features/codespaces/ Github Codespaces] allow you to code and run Mudlet all from the browser - makes it a lot easier to get started. It also allows you to code Mudlet itself from any computer in the world! <br />
<br />
'''1. Create a new codespace'''<br />
<br />
Create a new Codespace by going to https://github.com/Mudlet/Mudlet using Google Chrome or Microsoft Edge (Firefox at the time of the writing doesn't have working copy/paste). There, click the green "Code" button, select the "Codespaces" tab and click "New codespace".<br />
<br />
[[File:New codespace.png|alt=New codespace screenshot|frameless]]<br />
<br />
'''2. Wait for it to load'''<br />
<br />
This will take a while (~5min) so grab a tea:<br />
<br />
[[File:Building Visual Studio Codespace.png|frameless]]<br />
<br />
'''3. Connect to the environment'''<br />
<br />
Go to the <code>Ports</code> section at the bottom and change the Port Privacy of the Open Mudlet port to Public:<br />
<br />
[[File:Port privacy in Github Codespaces.png|900x900px]]<br />
<br />
<br />
Then connect to your online Linux desktop with <code>mudlet</code> as the password by clicking on the web icon. <br />
<br />
[[File:Connect to remote machine.png|frameless]]<br />
<br />
<br />
In case it can't connect, make sure the port privacy is set to <code>Public</code>. If it still can't connect, try 4-5 more times - eventually it'll work.<br />
<br />
<br />
<br />
We chose a retro 90's look here to fit with the whole hacking theme, so if you see this you're good 😉<br />
<br />
[[File:Github_codespaces_desktop.png|alt=|frameless|400x400px]]<br />
<br />
'''4. Build Mudlet'''<br />
<br />
In Codespaces, hit <code>F7</code> and select <code>Let CMake guess...</code><br />
<br />
[[File:CMake configuration.png|none]]<br />
<br />
It will then start building Mudlet automatically. Using the [https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/about-billing-for-codespaces Basic instance] (only kind available in beta) the first-time build will take ~25min, so take a break here - you've made excellent progress. All follow-up compiles after this will be quicker, by the way.<br />
<br />
[[File:Building Mudlet in codespaces.png|none]]<br />
<br />
'''5. Run Mudlet'''<br />
<br />
[[File:Launch Mudlet.png|none]]<br />
<br />
Hit the little play button at the bottom of the screen, and Mudlet will now launch in the remote connection tab. Not working? [https://discord.gg/kuYvMQ9 We can help]. Otherwise, enjoy!<br />
<br />
[[File:Mudlet running remotely.png |500px]]<br />
<br />
Note: When the codespace is unused for a while, it will disconnect. It'll never disconnect while you're actively using it. See [https://github.com/microsoft/vscode-dev-containers/issues/588 Github issue] for details.<br />
<br />
== Developing with Docker ==<br />
<br />
Docker is a system designed for more reproducible and isolated builds. A docker setup exists and has been tested using Pop OS! 20.04 (which is derived from Ubuntu 20.04). First, follow the instructions to install both [https://docs.docker.com/get-docker/ docker] and [https://docs.docker.com/compose/install/ docker-compose].<br />
<br />
Clone the development branch<br />
<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
cd Mudlet/docker<br />
<br />
Make a local copy of the .env.template file:<br />
<br />
cp .env.template .env<br />
<br />
If you wish to customize things like the number of cores to use for building mudlet, feel free to change the corresponding values in the .env file.<br />
<br />
To run Qt-Creator and develop Mudlet, run <code>docker-compose up dev</code>.<br />
<br />
To run Mudlet, run <code>docker-compose up mudlet</code>. Note: At the moment, the mudlet build will not persist settings past container rebuilds.<br />
<br />
== Compiling on Windows 7+ (MSYS2 Alternative)==<br />
<br />
''INCOMPLETE, IN PROGRESS''<br />
<br />
Go to http://www.msys2.org/ to download the 64 bit MSYS2 installer (as of 2020/05/24 32 bit hosts - for '''compiling''' software, but ''not'' for using code built with it have been deprecated, the last installer for that 32-bit systems is held at: http://repo.msys2.org/distrib/i686/msys2-i686-20200517.exe) and follow the installation instructions (Steps 1 to 8 on that page), these instructions assume that "C:\msys64" or "C:\msys32" is used depending on the bitness of the system it is being installed on.<br />
<br />
Install the following packages (using "pacman -S ''packageName''"), the ones with a '''-i686-''' in the middle are the ones for 32-bit (i686) targets and '''-x86_64-''' are the ones for 64-bit targets - it is possible to install both for building Mudlet for target PCs of both bitnesses on a 64-bit host, it is not clear whether the reverse is true with a 32-bit host. These will pull in a number of other required packages as well (the ''--needed'' option prevents the re-installation of packages that have already been installed by MSYS2/Mingw-w64's own setup/installation process) - as some of the packages, e.g. ''base-devel'' are actually ''groups'' you will be requested to select which members of that group are actually required, it is easiest to just go with the default which is to install ALL of the packages in that group!<br />
<br />
: For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-i686-toolchain mingw-w64-i686-qt-creator mingw-w64-i686-qt5-multimedia mingw-w64-i686-libzip mingw-w64-i686-pugixml mingw-w64-i686-lua51 mingw-w64-i686-lua51-lpeg mingw-w64-i686-lua51-lsqlite3 mingw-w64-i686-hunspell mingw-w64-i686-boost mingw-w64-i686-yajl mingw-w64-i686-clang mingw-w64-i686-cmake mingw-w64-i686-SDL unzip<br />
</syntaxhighlight><br />
<br />
: For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-x86_64-toolchain mingw-w64-x86_64-qt-creator mingw-w64-x86_64-qt5-multimedia mingw-w64-x86_64-libzip mingw-w64-x86_64-pugixml mingw-w64-x86_64-lua51 mingw-w64-x86_64-lua51-lpeg mingw-w64-x86_64-lua51-lsqlite3 mingw-w64-x86_64-hunspell mingw-w64-x86_64-boost mingw-w64-x86_64-yajl mingw-w64-x86_64-clang mingw-w64-x86_64-cmake mingw-w64-x86_64-SDL unzip<br />
</syntaxhighlight><br />
<br />
::The ''*-zziplib'' libraries are used by the ''luazip'' luarock {from the Kepler project} but Mudlet will work perfectly well with the alternative ''lua-zip'' {from the brimworks GitHub repository - which also provides the ''lua-yajl'' rock} which does not require this library - although it is possible that it might still be pulled into the system as a dependency of another MSYS2 package.<br />
<br />
:Note that this will install the MSYS2 builds of the Qt Libraries and Creator IDE - ''THE ON/OFF-LINE INSTALLER OF THE QT LIBRARIES AND CREATOR VIA DOWNLOADS FROM QT ARE NOT USEFUL IN THIS SETUP!''<br />
<br />
:{| class="wikitable"<br />
|-<br />
|'''Attention - Luarocks packages problem'''<br />
|-<br />
| Recently the Luarocks project attempted to adopt the MSYS2/Mingw-w64 platform as one it would supported natively and the MSYS2/Mingw-w64 project went and upgraded its luarocks packages to make use of the changes and also on-board other improvements (and the version number increased from ''2.4.4-2'' to ''3.5.0-1'') unfortunately this completely broke them and although the issue has been reported ([https://github.com/msys2/MINGW-packages/issues/9037 MSYS2 Issue 9037]) a fix has not yet materialised. The only way to work around this in the meantime is to download the older package (with '''wget''') and install it manually (with '''pacman -U):<br />
|-<br />
|For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:19:09-- https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97905 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-i686-lua51-luarocks-2.4.4-2- 100%[===========================================================================>] 95.61K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:19:10 (1.43 MB/s) - ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97905/97905]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-i686-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-i686-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|-<br />
|For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:17:32-- https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97935 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-x86_64-lua51-luarocks-2.4.4- 100%[===========================================================================>] 95.64K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:17:32 (1.28 MB/s) - ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97935/97935]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-x86_64-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-x86_64-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|}<br />
<br />
::{| class="wikitable"<br />
|-<br />
|'''Warning for those planning to build ''both'' 32 and 64 bit versions'''<br />
|-<br />
|If one is planning to build ''both'' bitness binaries an additional step is necessary as, by default, the MSYS2/Mingw-w64 ''luarocks'' setup seems to place any ''.lua'' or ''.dll'' modules it builds/installs on a per user (the so-called ''local'' basis) into the same directories with the same names. This is no good for two reasons:<br />
* It is difficult to work out which bitness a particular module is for and whilst 32-bit modules ''might'' work in a 64-bit environment the reverse is definitely not the case<br />
* It confuses the Luarocks package management systems (as effectively there will be two different luarocks systems operated side-by-side)<br />
<br />
This can be worked around by:<br />
* Editing the '''.\etc\luarocks\config-5.1.lua''' for each bitness so that the ''rocks_trees'' table entry for the ''user'' key is changed from this in '''both''' files:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks]] },</syntaxhighlight><br />
to something different for each of them, say, for example, for the the 64-bit one:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks-x64]] },</syntaxhighlight><br />
* Then by specifying the ''rocktree'' name ('''user''') on the command line when '''installing''' or '''building''' a luarock with the ''--tree user'' argument - note that for some inexplicable reason the ''--local'' argument that '''''should''''' do the same thing does not seem to work for these two actions, it is not clear whether this is a MSYS2/Mingw-w64 specific issue or it goes further upstream to Luarocks in general. Thus, in the next step it will be necessary to change from using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --local rockname<br />
</syntaxhighlight><br />
to, for the example given:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --tree user rockname<br />
</syntaxhighlight><br />
where ''user'' is the literal string "user" to match the Lua table key in the rock_trees and not, in this case, a representation of the user-name/account of the person performing the action.<br />
|}<br />
<br />
From the Windows ''Start menu'' start a shell appropriate for the target with the bitness to be built for i.e. '''"MSYS2 Mingw 32-Bit"''' or '''"MSYS2 Mingw 64-Bit"'''. This will likely position the current directory to the root directory of the MSYS2 environment, the text about the prompt line (the one with the "$") will contain three different bits of colored text '''username@computername'''; one of '''MSYS2'''/'''MINGW32'''/'''MINGW''' depending on the type of shell you currently in use and '''/''' representing the root directory (which will actually be the directory MSYS2 was installed to, for example on the author's system this is "C:/msys64"). Change to the home directory in MYSY by entering "cd" on its own with no argument (it will show up as '''~''' and it would work out to be, for '''user''' to be '''c:/msys64/home/user''' or '''c:/msys32/home/user''' (if both bitnessess are to be built it will be necessary to repeat the following step twice, one for each and also observe the steps in the above warning) install the following luarocks:<br />
<br />
:{| class="wikitable sortable"<br />
|-<br />
! rockname<br />
|-<br />
| lrexlib-pcre<br />
|-<br />
| lua-yajl<br />
|-<br />
| luafilesystem<br />
|-<br />
| luasql-sqlite3<br />
|-<br />
| luautf8<br />
|-<br />
| luazip or lua-zip<br />
|}<br />
by using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install [--local] rockname<br />
</syntaxhighlight><br />
The ''--local'' argument is an optional one that causes the luarock and the lua module to be installed on a per-user basis rather than on a system wide one, this may be important if the PC is used by multiple users and more than one of them uses Lua in any form.<br />
<br />
Now create somewhere to work on the Mudlet source, assuming that other software coding with other pieces of software will be done, create a sub-directory in the home directory, and then make one just for Mudlet under that:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ mkdir ./src<br />
<br />
MINGW64 user@computer ~<br />
$ mkdir ./src/mudlet<br />
</syntaxhighlight><br />
<br />
Change to that directory and get the source code:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ cd ./src/mudlet<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git clone git://github.com/Mudlet/Mudlet.git .<br />
</syntaxhighlight><br />
<br />
If you are planning to contribute to the Mudlet code you will want to visit Github and create your own GitHub repository, you can then push commits (changes to the code) to there and raise a Pull Request for a Mudlet Maker to drag the changes over to the above repository. You will want to add your repository and perhaps those of some other contributors so you can track what they are doing and see/try/experiment with their PRs before they get merged. Therefore you will want to add some other repositories into the mix. The names you use to identify those other repositories will show up in any utility that works with the repository you have just created in the above "clone" operation and can be anything you like but it makes sense to have clear names. So to add "myName", and those of the leading active contributors to the Mudlet codebase you will use:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Mine https://github.com/myName/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Vadim https://github.com/vadi2/Mudlet.git <br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add SlySven https://github.com/SlySven/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Kebap https://github.com/Kebap/Mudlet.git<br />
</syntaxhighlight><br />
<br />
Now obtain ''all'' the versions of the code with:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git fetch --all<br />
</syntaxhighlight><br />
<br />
This will produce a lot of lines of output the first time and it might take a little while on a slow connection...<br />
<br />
{Section missing - it turns out that the default GUI git tools that the author of this section would normally use: "gitk" and "git gui" have some problems in the versions currently supplied from the MSYS2 system - and it was necessary to import them from the set that the Git4Win have patched - see https://github.com/git-for-windows/git/wiki/Install-inside-MSYS2-proper }<br />
<br />
Some modifications to the qmake/cmake project files are needed and these are now supported in the main ''development'' branch in the upstream {the Mudlet organisation's own GitHub repository} which requires that there is an environmental variable '''WITH_MAIN_BUILD_SYSTEM''' and it is set to the (case-insensitive) value '''NO''':<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export WITH_MAIN_BUILD_SYSTEM=NO<br />
</syntaxhighlight><br />
<br />
Also the '''MINGW_BASE_DIR''' environmental variable will need to be set to the root directory for the MINGW-W64 installation for the appropriate bitness of the target to be made. For building on a 64-Bit Host {the PC that is ''compiling'' the code} to make a 64-Bit application this will likely be '''C:/msys64/mingw64''' and for a 32-Bit application it will probably be '''C:/msys64/ming32'''.<br />
: E.g. <syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw64 # To build a 64-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
: Or: <syntaxhighlight lang="shell"><br />
MINGW32 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw32 # To build a 32-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
Now checkout a branch {ideally, if working on solving a new issue, or adding a feature or resolving a bug, one should create a new branch that is a copy of the current, upstream ''development'' branch} and then work on it with Qt Creator:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ qtcreator &<br />
</syntaxhighlight><br />
<br />
Load in the '''mudlet.pro''' ''qmake'' project file in the '''src''' subdirectory (e.g. for this example: '''c:/msys64/home/user/src/mudlet/src/mudlet.pro''') and get hacking...<br />
<br />
= Setting up IDEs =<br />
== CLion ==<br />
=== Qt not detected ===<br />
If you'd like to use CLion and it is giving the following error:<br />
<br />
<nowiki><br />
By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has<br />
asked CMake to find a package configuration file provided by "Qt5Core", but<br />
CMake did not find one.<br />
<br />
...<br />
</nowiki><br />
<br />
You can fix this by setting <code>-DCMAKE_PREFIX_PATH=<your Qt + version + compiler location></code>. For example: <code>-DCMAKE_PREFIX_PATH=/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code> [[File:CLion CMake settings - finidng Qt.png|700px|none]]<br />
<br />
=== CLion setup on Windows ===<br />
After running <code>setup-windows-sdk.ps1</code> make sure to set Cmake options to:<br />
-DCMAKE_PREFIX_PATH=C:\Qt\Tools\mingw730_32;C:\Qt\5.14.2\mingw73_32 -DBoost_INCLUDE_DIR=C:\Libraries\boost_1_77_0<br />
''Directories might vary slightly, when different Qt, Boost or MinGW version will be used.''<br />
<br />
[[File:Clion Settings - Cmake.png|frameless|700x700px]]<br />
<br />
<br />
<br />
You will need 32 bit version of MinGW. Set it in the <code>Toolset</code> field to:<br />
C:\Qt\Tools\mingw730_32<br />
<br />
''Directory may be slightly different if MinGW version used will change.''<br />
<br />
[[File:Toolchain.png|frameless|700x700px]]<br />
<br />
=== Clang Tidy ===<br />
Ensure that CLion is set to run the project's [https://www.jetbrains.com/help/clion/clang-tidy-checks-support.html#paticularcheck .clang-tidy checks] with the <code>Prefer .clang-tidy files over IDE settings</code> option:<br />
<br />
[[File:Clang Tidy CLIon.png|700px|none]]<br />
<br />
This helps us catch any issues just a bit earlier.<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in CLion, adjust the CMake settings:<br />
<br />
[[File:Clion_cmake_settings.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
=== Clang Format ===<br />
Ensure that [https://www.jetbrains.com/help/clion/clangformat-as-alternative-formatter.html#clion-support CLion is set to use] the <code>.clang-format</code> formatting style:<br />
<br />
[[File:Clang-format CLion.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
== Visual Studio Code ==<br />
<br />
To set the path in Visual Studio Code, open settings, search for <code>cmake environment</code> and set the <code>CMAKE_PREFIX_PATH</code> to your path, such as <code>/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code>:<br />
<br />
[[File:CMake path in Visual Studio Code.png|none]]<br />
<br />
===Clang Tidy===<br />
clang-tidy catches common programming issues, run it by selecting 'Analysis' from the command palette (Ctrl+Shift+P by default):<br />
<br />
[[File:Clang-tidy in vscode.png|none]]<br />
<br />
It is also possible [https://devblogs.microsoft.com/cppblog/visual-studio-code-c-december-2021-update-clang-tidy/ check status of analysis and cancel if needed].<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in VSCode, set the <code>cmake.configureSettings</code> variable:<br />
<br />
[[File:Cmake.configureSettings option in vscode.png|frameless|890x890px]]<br />
<br />
[[File:Choosing which sanitizers in vscode to use.png|frameless|891x891px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
== Qt Creator==<br />
===Clang Tidy and Clazy===<br />
<br />
Configure Mudlet-specific checks for [https://clang.llvm.org/extra/clang-tidy/ clang-tidy] and [https://github.com/KDE/clazy clazy] tools help catch any issues early on. See [https://doc.qt.io/qtcreator/creator-clang-tools.html Qt Creator's instructions] for setting this up - clang-tidy can use the <code>.clang-tidy</code> file that's available at the root of the repository, and for clazy enable <code>level0</code> and <code>level1</code> checks.<br />
<br />
[[File:Clang tidy configuration.png|frame|none]]<br />
[[File:Clazy configuration.png|frame|none]]<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in Qt creator, head to <code>Projects</code> - <code>Build</code>: <br />
<br />
[[File:Sanitisers in qt creator.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
==Clang Format==<br />
Ensure that Qt Creator is set to use the <code>.clang-format</code> formatting style in the C++ settings. Turn on <code>Format instead of indenting</code> for <code>Ctrl+I</code> to format code, and ensure <code>Override Clang Format configuration file</code> is disabled:<br />
<br />
[[File:Qt Creator clang format.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
<br />
=Building with multiple versions of Lua=<br />
Mudlet uses Lua 5.1 only, so if you are compiling on a system that also has later versions installed, you might get the following error: <code>‘LUA_GLOBALSINDEX’ was not declared in this scope</code>.<br />
<br />
To fix this, pass the path to Lua headers explicitly. For CMake: <code>-DLUA_INCLUDE_DIR=/usr/include/lua5.1</code> (adjust as needed).<br />
<br />
= Compile Time Flags =<br />
<br />
<nowiki><br />
DEBUG_UTF8_PROCESSING - for decoding the UTF-8 (1 byte with the MSB set or 2, 3 or 4 bytes) encoding<br />
DEBUG_GB_PROCESSING - for decoding the GBK (2 bytes) or GB18030 (2 or 4 bytes) encodiing<br />
DEBUG_BIG5_PROCESSING - for decoding the Big5-ETEN or Big5-HKSCS encodings<br />
DEBUG_EUC_KR_PROCESSING - for decoding the EUC_KR encoding<br />
DEBUG_SGR_PROCESSING - decoding the <ESC>[ codes (that pair of bytes being the CSI "Control Sequence Introducer" - including the one ending in m which is the "Set Graphics Rendition" that Mudlet (and other MUD clients and other things) use to control colours and other font effects.<br />
DEBUG_OSC_PROCESSING - decode the <ESC>] codes (that MUST end with a <ESC>\) - currently Mudlet only handles a couple of these OSC "Operating System Commands".<br />
DEBUG_MXP_PROCESSING - stuff to do with the MXP protocol - which uses a <ESC> ... z sequence of characters to do some things...<br />
</nowiki></div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Scripting&diff=20909Manual:Scripting2024-02-05T21:09:34Z<p>Kebap: /* Discord Messages */ Shrink large picture into thumbnail</p>
<hr />
<div>{{TOC right}}<br />
=Scripting with Mudlet=<br />
<br />
Lua tables can basically be considered multidimensional arrays and dictionaries at the same time. If we have the table matches, matches[2] is the first element, matches[n+1] the n-th element.<br />
<br />
<syntaxhighlight lang="lua"><br />
a = "Tom"<br />
matches[2] = "Betty"<br />
b = matches[2]<br />
c = a .. b and e will equal "TomBetty"<br />
</syntaxhighlight><br />
<br />
To output a table you can use a convenience function - ''display(mytable)'', which is built into Mudlet.<br />
<br />
==Lua interface functions - triggers, timers etc.==<br />
<br />
How to get data from regex capture groups? Regular expression capture groups (e.g. "(\d+)" ) are passed on to Lua scripts as a Lua table matches. To make use of this information inside Lua scripts, you need to specify the number of the capture group within the regex.<br />
<br />
<code>Example: You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
This regex contains 3 capture groups, but only the 2 green colored ones contain data as the red capture group is a non-capturing group. Consequently, your Lua script gets passed only 2 instead of 3 capture groups and matches[4] is undefined.<br />
<br />
In your Lua script you may write following program in order to print the number and status of your weapons on the screen:<br />
<br />
<code>You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
<syntaxhighlight lang="lua"><br />
number_of_weapons = matches[2]<br />
status_of_weapons = matches[3]<br />
notice = number_of_weapons .. status_of_weapons<br />
echo( notice )<br />
send( "put weapons in backpack" )<br />
<br />
-- the following 2 lines color the first capture<br />
-- group red and the second group blue<br />
-- see below for details<br />
<br />
selectCaptureGroup( 2 )<br />
setFgColor( 255,0,0 )<br />
<br />
selectCaptureGroup( 3 )<br />
setFgColor( 0,0,255 )</syntaxhighlight><br />
<br />
The best way is to use selectCaptureGroup( number ) to select the proper capture group and then perform your actions on it e.g. replace(), highlight etc. Note: Both selectCaptureGroup() and matches[n] start with group 1 (which is the whole match. The defined capture groups start with 2).<br />
<br />
How to select all occurrences of "Tom" and highlight them?<br />
<br />
You add a function like this to a script containing you main function definitions. Note that script items differ from all other "scripts" in triggers, timers, actions etc. because they require you to put your code in proper functions that can be called by your other trigger-scripts, timer-scripts etc. via normal function calls. Trigger-scripts, timer-scripts etc. cannot contain any function definitions because they are automatically generated functions themselves because this makes usage a lot easier.<br />
<br />
To come back to our question how to select all occurrences of "Tom" and highlight them:<br />
<br />
<syntaxhighlight lang="lua"><br />
function setBgColorAll( word, r, g, b )<br />
i = 0<br />
word_count = 1<br />
while i > -1 do<br />
i = selectString(word, word_count)<br />
if i == -1 then<br />
return<br />
end<br />
word_count = word_count +1<br />
setBgColor( r, g, b )<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
Then you simply define a substring matching trigger on the word "Tom" and in the trigger script you call above function:<br />
<br />
<syntaxhighlight lang="lua">setBgColorAll("Tom", 255,50,50)</syntaxhighlight><br />
<br />
Since Mudlet 4.11+ it is possible to use name capture groups. You can verify if feature availability by checking <code>mudlet.supports.namedPatterns</code> flag.<br />
Let's say you have multiple patterns that you want to handle with one code.<br />
<br />
<code>^My name is (?<name>\w+)\. My class is (?<class>\w+)\.</code><br />
<br />
<code>^I am (?<class\w+)\ and my name is (?<name>\w+)\.</code><br />
<br />
Notice that class and name come in different order, therefore in first case we will have name under <code>matches[2]</code> and in second case under <code>matches[3]</code>.<br />
With named capture groups in both cases we will have name available under <code>matches.name</code> and class under <code>matches.class</code>.<br />
<br />
Code example to handle named matches above:<br />
<syntaxhighlight lang="lua"><br />
echo("Name: " .. matches.name .. "\n")<br />
echo("Class: " .. matches.class .. "\n")<br />
</syntaxhighlight><br />
<br />
==Sending commands or printing information messages==<br />
<br />
To print information messages on the session screen you can use the echo( message ) function, or insertText( text ). Currently, it only takes one string as argument.<br />
<br />
To send a command to the MUD, you can use the send( command ) function. In Alias scripts the command that is being sent to the MUD is contained in the variable command that you can change in the context of Alias scripts. Alias take regular expressions, as well. As a result, you can use following regex and script to talk like Yoda: Perl regex:<br />
<br />
<code> say (\w+).*(\w*).*(.*) </code><br />
<br />
script:<br />
<br />
<syntaxhighlight lang="lua"><br />
send( "say " .. matches[4] .." " .. matches[2] .." ".. matches[3] )<br />
</syntaxhighlight><br />
<br />
Note: The variable "command" contains what was entered in the command line or issued via the expandAlias( ) function. If you use expandAlias( command ) inside an alias script the command would be doubled. You have to use send( ) inside an alias script to prevent recursion. This will send the data directly and bypass the alias expansion.<br />
<br />
===Changing and formatting text from the MUD===<br />
<br />
When sending commands to the MUD - from now on referred to as output stream - alias scripts find the command that was issued by the user stored in the variable "command".<br />
<br />
By manipulating the value, the command can easily be changed before it is being sent to the MUD.<br />
<br />
However, things get much more complicated with the data received from the MUD, from now on referred to as input stream. Before triggers can be run on the MUD data, Mudlet has to strip all format codes from the text and store it in data structures associated with the text. Consequently, the text that is being passed on to the trigger processing unit is a small subset of the data received from the MUD. If you want to edit, replace, delete or reformat text from within your trigger scripts you have to keep this in mind if you don’t want to lose all text format information such as colors etc.<br />
<br />
As the text is linked with data structures containing the format of the text, the cursor position inside the line is important if data is being changed. You select a word or a sequence of characters from the line and then issue commands to do actions on the selected data.<br />
<br />
Replacing the word "Tom" with "Betty" in the line: Jim, Tom and Lucy are learning a new spell. This could be done with following script:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Tom",1)<br />
replace("Betty")<br />
</syntaxhighlight><br />
<br />
Things get more complicated if there are two or more occurrences of "Tom" in the line e.g. Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
The above example code would select the first occurrence of "Tom" in this line and ignore the second. If you want to work on the the second occurrence of "Tom" you have to specify the occurrence number in the call to select().<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString( "Tom", 2 )<br />
replace( "Betty" )<br />
</syntaxhighlight><br />
<br />
This code would change the second "Tom" and leave the first "Tom" alone. The function call<br />
<br />
<syntaxhighlight lang="lua">replaceAll( "Betty" )</syntaxhighlight><br />
<br />
will replace all occurrences of "Tom" with "Betty" in the line if "Tom" has been selected before. replaceAll() is a convenience function defined in LuaGlobal.lua.<br />
<br />
Colorization example: You want to change to color of the words "ugly monster" to red on a white background.<br />
<br />
You add a new trigger and define the regex: ugly monster In the script you write:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("ugly monster", 1 )<br />
setFgColor(255,0,0)<br />
setBgColor(255,255,255)<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
Another means to select text is to select a range of characters by specifying cursor positions. If we have following line: Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
<syntaxhighlight lang="lua">selectSection( 28, 3 )</syntaxhighlight><br />
<br />
This example would select the second Tom. The first argument to selectSection is the cursor position within the line and the second argument is the length of the selection.<br />
<br />
<syntaxhighlight lang="lua">selectCaptureGroup( number )</syntaxhighlight><br />
<br />
This function selects the captureGroup number if you use Perl regular expressions containing capture groups. The first capture group starts with index 1.<br />
<br />
==Deleting Text - Gagging==<br />
<br />
<syntaxhighlight lang="lua">deleteLine()</syntaxhighlight><br />
<br />
This function deletes the current line - or any line where the cursor is currently placed. You can use repeated calls to this function to effectively erase the entire text buffer. If you want to delete or gag certain words only, you can select the text that you want to delete and then replace it with an empty string e.g:<br />
<br />
If you get this line form the MUD: "Mary and Tom walk to the diner."<br />
<br />
<syntaxhighlight lang="lua">selectString( "Tom", 1 )<br />
replace( "" )</syntaxhighlight><br />
<br />
Then the output will be changed to: "Mary and walk to the diner."<br />
<br />
==Cursor Movement and Cursor Placement==<br />
Mudlet allows you to insert text arbitrarily within the buffer - in the previous line, in the previous ten lines, or even the first line that you've ever saw. These are the tools to help you with the job:<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( windowName, x, y )]]</code> This will move the user cursor of window windowName to the absolute (x/y) coordinates in the text.<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( "main", 20, 3950 )]]</code> will move the cursor on the 20th character from the left on line number 3950. To determine the current cursor position you can use getLineNumber() and getColumnNumber() as well as [[Manual:UI_Functions#getLastLineNumber|getLastLineNumber()]] to get the number of the last line in the text buffer. moveCursorEnd("main") will move the cursor of the main display to end of the buffer. This is always a new line of size 1 containing the character \n.<br />
<br />
<code>number_of_last_line_in_text = [[Manual:UI_Functions#getLineCount|getLineCount()]]</code> returns the number of the last line of the text in the console buffer. This number will change as soon as a new \n is printed either by the user or when a new line arrives from the MUD. All lines from the MUD are terminated with \n which is called line feed or the new line character. This control character ends the current line and move the cursor to the beginning of the next line, thus creating a new, empty line below the line that contains the \n.<br />
<br />
<code>line_number_of_the_current_cursor_position = [[Manual:UI_Functions#getLineNumber|getLineNumber()]]</code><br />
<br />
<code>column_number_of_the_current_cursor_position = [[Manual:UI_Functions#getColumnNumber|getColumnNumber()]]</code><br />
<br />
<code>luaTable_containing_textlines = [[Manual:UI_Functions#getLines|getLines( absolute_line_number_from, absolute_line_number_to )]]</code> this will return a Lua table containing all lines between the absolute positions from and to.<br />
<br />
{{note}} This function uses absolute line numbers, not relative ones like in [[Manual:UI_Functions#moveCursor|moveCursor()]].<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor()]]</code> returns true or false depending on whether the move was possible and done.<br />
<br />
=== Inserting text in the middle of the line ===<br />
Here's an example where we'll append the text ''(one)'' right after the word ''exit'' in the line of <code>You see a single exit leading west.</code><br />
<br />
[[File:Inserting text.png|center|650px]]<br />
<br />
The pattern we used was an ''exact match'' for <code>You see a single exit leading west.</code> and the code is:<br />
<br />
<syntaxhighlight lang="lua"><br />
if moveCursor(string.find(line, "exit")+#("exit")-1, getLineNumber()) then<br />
insertText("(one)")<br />
end<br />
</syntaxhighlight><br />
<br />
What happened here:<br />
* we triggered on the desired line using our pattern above<br />
* we used [[Manual:UI_Functions#moveCursor|moveCursor()]] to place the cursor in the desired position within the line. [[Manual:UI_Functions#moveCursor|moveCursor()]] takes both the line number and the position within the line to place our virtual cursor on, so<br />
** we used [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] to find the position of the word "exit" within the line<br />
** but [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] returns us the position of the first character of the word we want, while we want to have the text be right after it - so we find out how long our word is with <code>#("exit")</code>, add that to the number returned by [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] which gets us the first character + the length of the word - which isn't quite at the end of the word, but the word plus the space (because of [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] and the first character) - so we substract 1 to move our cursor right at the end of the word<br />
** we then use [[Manual:UI_Functions#getLineNumber|getLineNumber()]] to get the current line number, so our cursor is placed on the current line, at our desired position<br />
* lastly we finally insert the text with [[Manual:UI_Functions#insertText|insertText()]], which puts the text exactly where our virtual cursor is<br />
<br />
Done! You can also use [[Manual:UI_Functions#cinsertText|cinsertText()]] for coloured inserts, and other functions [[Manual:Scripting#Cursor_Movement_and_Cursor_Placement|mentioned above]] and in the [[Manual:UI_Functions|API manual]] to help you do what you'd like.<br />
<br />
==User defined dockable windows==<br />
<br />
You may want to use dock windows to display information you gathered in your scripts, or you may want to use them as chat windows etc. Check out [[Manual:Geyser#Geyser.UserWindow|Geyser.UserWindow]] on how to add them!<br />
<br />
==Dynamic Triggers==<br />
<br />
<code>triggerID = tempTrigger( substring pattern, code ) creates a fast substring matching trigger</code> <br />
<br />
<code>triggerID = tempRegexTrigger( regex, code ) creates a regular expression matching trigger</code><br />
<br />
<code>triggerID = tempBeginOfLineTrigger( begin of line pattern, code ) creates a fast begin of line substring trigger</code><br />
<br />
=Scripting howtos=<br />
==How to convert a string to value?==<br />
Say you'd like to capture a number from a trigger, but the capture always ends up being a "string" (or, just text on which you can't do any maths on) even if it's a number. To convert it to a number, you'd want to use the ''tonumber()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
myage = tonumber(matches[2])<br />
</syntaxhighlight><br />
<br />
==How to highlight my current target?==<br />
<br />
You can put the following script into your targetting alias:<br />
<br />
<syntaxhighlight lang="lua">if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
Where target is your target variable. Note that you have to use the full name, capitalized. If you’d like the script to auto-capitalize for you, you can use this version:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = target:title()<br />
if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
{{note}} Ensure you're on Mudlet 3.5.0+ so you can put ''function()'' in a ''[[Manual:Lua_Functions#tempTrigger|tempTrigger()]]''.<br />
<br />
==How to format an echo to a miniConsole?==<br />
<br />
One of the ways you can create multi-line displays in a miniConsole with variable information is with string.format and the use of [[ ]] brackets for text, which allow for multiple line in text:<br />
<br />
<syntaxhighlight lang="lua"><br />
local WindowWidth, WindowHeight = getMainWindowSize();<br />
createMiniConsole("sys",WindowWidth-650,0,650,300)<br />
<br />
local name, age, sex = "Bob", 34, "male"<br />
<br />
cecho("sys", string.format([[<br />
<br />
/---------\<br />
%s<br />
%dyrs<br />
sex - %s <br />
\---------/<br />
]], name, age, sex))<br />
</syntaxhighlight><br />
<br />
==How to play a sound when I receive communication while afk?==<br />
<br />
[[File:Play_sound_when_afk_trigger.png]]<br />
<br />
For this to work, place the line you'd like to trigger on in the first pattern box and select the appropriate pattern type. Then add ''return not hasFocus()'' with the Lua function as the second pattern, enable the AND trigger, and set the line delta to zero. Then just enable ''play sound'', choose your sound and you're set!<br />
<br />
==How can I make a key that toggles between commands?==<br />
To make a key that toggles between two actions, for example - sleep/wake, you can use this as the script:<br />
<br />
<syntaxhighlight lang="lua"><br />
if not sleeping then<br />
send("sleep")<br />
sleeping = true<br />
else<br />
send("wake")<br />
sleeping = false<br />
end<br />
</syntaxhighlight><br />
<br />
<!-- Old Heading: How can I make a trigger that goes off only if the next line is not a particular one? --><br />
==How can I make a trigger with a next-line condition?==<br />
<br />
Here's how you can set it up - replace ''line1'' and ''line2'' with appropriate lines.<br />
<br />
[[File:Trigger_multiline_not_another_example.png|center]]<br />
<br />
Here's [[Media:Match only of next line is *not* line2.xml.zip|the Mudlet XML]] you can download for this!<br />
<br />
==How to target self or something else?==<br />
<br />
[[File:Buffselforother.png|border|350px]]<br />
<br />
Using regex and an 'or' statement allows us to consolidate multiple aliases, or an if statement, into a single more simple alias. <br />
When a regex is found it will use it, but if you don't specify one then the alternative will be used. The use of 'or' can be used with any function in Mudlet.<br />
In this example, one can type "buff" to buff themself, or "buff ally" to buff their ally instead.<br />
<br />
<syntaxhighlight lang="lua"><br />
^buff(?: (\w+))?$<br />
<br />
send("cast buff on "..(matches[2] or "myself"))<br />
</syntaxhighlight><br />
<br />
==How to delete everything between two lines?==<br />
When deleteLine() is called, every following line shifts back in numerical position. Thus if we know where we're starting and how many lines to expect, we can use a for loop to gag everything between line a and b by leaving the cursor in one spot. In the below example, line_a_number is the number of the line you want to start at, and line_b_number is the ending line. To gag x number of lines instead, use line_a_number + x in place of line_b_number.<br />
<br />
<syntaxhighlight lang="lua"><br />
for i = line_a_number, line_b_number, 1<br />
do<br />
moveCursor(0, line_a_number)<br />
selectCurrentLine()<br />
deleteLine()<br />
end<br />
</syntaxhighlight><br />
<br />
== How to capture foreground line color information? ==<br />
Here's an example that loops through each character in a line of text and prints the character and its foreground color to a miniconsole if the color has changed from the previous character:<br />
<br />
Trigger: <code>^</code> (regex)<br />
<br />
Code:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer =<br />
miniconsoleContainer or Adjustable.Container:new({name = "miniconsoleContainer"})<br />
myMiniconsole =<br />
Geyser.MiniConsole:new(<br />
{<br />
name = "myMiniconsole",<br />
x = 0,<br />
y = 0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width = "100%",<br />
height = "100%",<br />
},<br />
miniconsoleContainer<br />
)<br />
<br />
local index = 0<br />
local line = getCurrentLine()<br />
local linesize = #line<br />
local currentlinenumber = getLineNumber()<br />
local r, g, b = 0, 0, 0<br />
local cr, cg, cb -- last seen colors<br />
while index < linesize do<br />
index = index + 1<br />
moveCursor("main", index, currentlinenumber)<br />
selectString(line:sub(index), 1)<br />
r, g, b = getFgColor()<br />
if cr ~= r or cg ~= g or cb ~= b then<br />
cr, cg, cb = r, g, b<br />
myMiniconsole:echo(string.format("rgb(%d,%d,%d)%s", r, g, b, line:sub(index, index)))<br />
else<br />
myMiniconsole:echo(string.format("%s", line:sub(index, index)))<br />
end<br />
line:sub(index, index)<br />
end<br />
myMiniconsole:echo("\n")<br />
</syntaxhighlight><br />
<br />
==How to enter a carriage return / enter command?==<br />
Say you'd like to gag the following line, and just continue ... <br />
<br />
[ Press Enter to continue ]<br />
<br />
<syntaxhighlight lang="lua"><br />
Trigger: [ Press Enter to continue ] (set to exact match)<br />
Code: deleteLine()<br />
send("\n")<br />
</syntaxhighlight><br />
<br />
==How to repeat commands with #?==<br />
Install the [https://forums.mudlet.org/viewtopic.php?f=6&t=1275 following alias], and with it <code>#5 mycommand</code> will get repeated five times.<br />
<br />
== How to move the command line over? ==<br />
<br />
To move the command line over to the right, create a new script and add the following to it:<br />
<br />
<syntaxhighlight lang="css"><br />
setCmdLineStyleSheet("main", [[<br />
QPlainTextEdit {<br />
padding-left: 100px; /* change 100 to your number */<br />
background-color: black; /* change it to your background color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
== How to add a background for Mudlets buttons? ==<br />
You can give Mudlets buttons a background to have them blend in with your UI by doing this:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- replace the /home/vadi/Pictures/tile.png location below with the one of your picture!<br />
-- you can download the sample tile.png from https://opengameart.org/content/bevouliin-free-game-background-for-game-developers<br />
local backgroundpath = [[/home/vadi/Pictures/tile.png]]<br />
-- Windows:<br />
-- local backgroundpath = [[C:/Users/Vadim/Downloads/Free game background/transparent PNG/tile.png]]<br />
<br />
setAppStyleSheet([[<br />
QToolBar {<br />
border-image: url(]]..backgroundpath..[[);<br />
<br />
}<br />
<br />
QToolBar QToolButton:!hover {<br />
color: white;<br />
}<br />
QToolBar QToolButton:hover {<br />
color: black;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
Result:<br />
<br />
[[File:Mudlet tiled buttons.png|frame|left]]<br />
<br clear=all><br />
<br />
= Advanced scripting tips =<br />
== Do stuff after all triggers/aliases/scripts are run ==<br />
This little snippet will have your commands be executed right after, depending on the context you run it in, all triggers, aliases or scripts are completed:<br />
<br />
<syntaxhighlight lang="lua">tempTimer(0, [[mycode]])</syntaxhighlight><br />
<br />
== How to delete the previous and current lines ==<br />
<br />
This little snippet comes from [http://forums.mudlet.org/viewtopic.php?f=9&t=2411&p=10685#p10685 Iocun]:<br />
<br />
<syntaxhighlight lang="lua"><br />
moveCursor(0,getLineCount()-1)<br />
deleteLine()<br />
moveCursor(0,getLineCount())<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=db: Mudlet's database frontend=<br />
<br />
The DB package is meant to provide easier access to a database, so you don’t have to know SQL or use the luasql module to set and get at your data. However, it does require that the luasql module be compiled and included in Mudlet to function.<br />
<br />
==Creating a Database==<br />
<br />
Before you can store anything in a database, you need to create one. You may have as many independent databases as you wish, with each having as many unique tables-- what we will call sheets in this package, so as to avoid confusion with Lua tables - think spreadsheets.<br />
<br />
To create a database, you use the db:create() function, passing it the name of your database and a Lua table containing its schema configuration. A schema is a mold for your database - it defines what goes where. Using the spreadsheet example, this would mean that you’d define what goes into each column. A simple example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes"}})<br />
</syntaxhighlight><br />
<br />
This will create a database which contains two sheets: one named friends, the other named enemies. Each has three columns, name, city and notes-- and the datatype of each are strings, though the types are very flexible and can be changed basically whenever you would like. It’ll be stored in a file named Database_people.db in your Mudlet config directory on the hard drive should you want to share it.<br />
<br />
It’s okay to run this function repeatedly, or to place it at the top-level of a script so that it gets run each time the script is saved: the DB package will not wipe out or clear the existing data in this case. <br />
<br />
{{Note}} You may not create a column or field name which begins with an underscore. This is strictly reserved to the db package for special use.<br />
<br />
{{Note}} Adding new columns to an existing database did not work in Mudlet 2.1 - see [[Manual:Lua_Functions#db:create|db:create()]] on how to deal with this.<br />
<br />
<!--<br />
More importantly, this allows you to add columns to an existing sheet. If you change that line to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes", "enemied"}})<br />
</syntaxhighlight><br />
<br />
It will notice that there is a new column on enemies, and add it to the existing sheet-- though the value will end up as nil for any rows which are already present. Similarly, you can add whole new sheets this way. It is not presently possible to -remove- columns or sheets without deleting the database and starting over.<br />
--><br />
<br />
==Adding Data==<br />
<br />
To add data to your database, you must first obtain a reference (variable) for it. You do that with the db:get_database function, such as:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("people")<br />
</syntaxhighlight><br />
<br />
The database object contains certain convenience functions (discussed later, but all are preceded with an underscore), but also a reference to every sheet that currently exists within the database. You then use the db:add() function to add data to the specified sheet.<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends, {name="Ixokai", city="Magnagora"})<br />
</syntaxhighlight><br />
<br />
If you would like to add multiple rows at once to the same table, you can do that by just passing in multiple tables:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends,<br />
{name="Ixokai", city="Magnagora"},<br />
{name="Vadi", city="New Celest"},<br />
{name="Heiko", city="Hallifax", notes="The Boss"}<br />
)<br />
</syntaxhighlight><br />
<br />
Notice that by default, all columns of every table are considered optional-- if you don’t include it in the add, then it will be set to its default value (which is nil by default)<br />
<br />
For those familiar with databases: with the DB package, you don’t have to worry about committing or rolling back any changes, it will commit after each action automatically. If you would like more control than this, see Transactions below.<br />
<br />
You also cannot control what is the primary key of any sheets managed with DB, nor do you have to create one. Each row will get a unique integer ID that automatically increments, and this field can be accessed as "_row_id".<br />
<br />
==Querying==<br />
<br />
Putting data in isn’t any fun if you can’t get it out. If you want every row from the sheet, you can do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends)<br />
</syntaxhighlight><br />
<br />
But rarely is that actually useful; usually you want to get only select data. For example, you only want to get people from the city of Magnagora. To do that you need to specify what criteria the system should use to determine what to return to you. It looks like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
So the basic command is - db:fetch(_sheet_, _what to filter by_)<br />
<br />
The following filter operations are defined:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:eq(field, value[, case_insensitive]) -- Defaults to case insensitive, pass true as the last arg to<br />
reverse this behavior.<br />
db:not_eq(field, value[, case_insensitive) -- Not Equal To<br />
db:lt(field, value) -- Less Than<br />
db:lte(field, value) -- Less Than or Equal to.<br />
db:gt(field, value) -- Greater Than<br />
db:gte(field, value) -- Greater Than or Equal To<br />
db:is_nil(field) -- If the column is nil<br />
db:is_not_nil(field) -- If the column is not nil<br />
db:like(field, pattern) -- A simple matching pattern. An underscore matches any single character,<br />
and a percent(%) matches zero or more characters. Case insensitive.<br />
db:not_like(field, pattern) -- As above, except it'll give you everything but what you ask for.<br />
db:between(field, lower_bound, upper_bound) -- Tests if the field is between the given bounds (numbers only).<br />
db:not_between(field, lower_bound, upper_bound) -- As above, only... not.<br />
db:in_(field, table) -- Tests if the field is in the values of the table. NOTE the trailing underscore!<br />
db:not_in(field, table) -- Tests if the field is NOT in the values of the table *<br />
</syntaxhighlight><br />
<br />
The db:in_ operator takes a little more explanation. Given a table, it tests if any of the values in the table are in the sheet. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:in_(mydb.friends.city, {"Magnagora", "New Celest"})<br />
</syntaxhighlight><br />
<br />
It tests if city == "Magnagora" OR city == "New Celest", but with a more concise syntax for longer lists of items.<br />
<br />
There are also two logical operators:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:AND(operation1, ..., operationN)<br />
db:OR(operation1, operation2)<br />
</syntaxhighlight><br />
<br />
You may pass multiple operations to db:fetch in a table array, and they will be joined together with an AND by default. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends,<br />
{db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "X%")}<br />
)<br />
</syntaxhighlight><br />
<br />
This will return every record in the sheet which is in the city of Magnagora, and has a name that starts with an X. Again note that in LIKE patterns, a percent is zero or more characters — this is the same effect as "X.*" in pcre patterns. Similarly, an underscore matches any single characters and so is the same as a dot in pcre.<br />
<br />
Passing multiple expressions in an array to db:fetch is just a convenience, as its exactly the same as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:AND(db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "I%")))<br />
</syntaxhighlight><br />
<br />
The db:OR operation only takes two arguments, and will check to see if either of the two is true. You can nest these logical operators as deeply as you need to.<br />
<br />
You can also just pass in a string directly to db:fetch, but you have to be very careful as this will be passed straight to the SQL layer. If you don’t know any SQL then you want to avoid this… for example, in SQL there’s a very big difference between double and single quotes. If you don’t know that, then stick to the db functions. But an example is:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, "city == 'Magnagora'")<br />
</syntaxhighlight><br />
<br />
Now, the return value of db:fetch() is always a table array that contains a table dictionary representing the full contents of all matching rows in the sheet. These are standard Lua tables, and you can perform all normal Lua operations on them. For example, to find out how many total items are contained in your results, you can simply do #results. If a request from the friends sheet were to return one row that you stored in the results variable, it would look like this if passed into the display() function:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'name': 'Bob',<br />
'city': 'Magnagora',<br />
'notes': 'Trademaster of Tailoring'<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
And if you were to echo(#results), it would show 1.<br />
<br />
The order of the returned rows from db:fetch is generally the same as the order in which you entered them into the database, but no actual guarantees are made to this. If you care about the order then you can pass one or two optional parameters after the query to db:fetch() to control this.<br />
<br />
The first table is an array of fields that indicate the column names to sort by; the second is a flag to switch from the default ascending(smallest to largest) sort, to a descending(largest to smallest) sort. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city})<br />
</syntaxhighlight><br />
<br />
This will return all your friends in Magnagora, sorted by their name, from smallest to largest. To reverse this, you would simply do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city}, true)<br />
</syntaxhighlight><br />
<br />
Including more then one field in the array will indicate that in the case that two rows have the same value, the second field should be used to sort them.<br />
<br />
If you would like to return ALL rows from a sheet, but still sort them, you can do that by passing nil into the query portion. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, nil, {mydb.friends.city, mydb.friends.name})<br />
</syntaxhighlight><br />
<br />
This will return every friend you have, sorted first by city and then their name.<br />
<br />
==Indexes and Types==<br />
<br />
The sheets we’ve defined thus far are very simple, but you can take more control over the process if you need to. For example, you may assign default values and types to columns, and the DB package will attempt to coerce them as appropriate. To do that, you change your db:create() call as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
This is almost the same as the original definition, but we’ve defined that our first four fields are strings with a default value of blank, and the new kills field which is an integer that starts off at 0. The only way to set a datatype is to set a default value at this time.<br />
<br />
Please note, beneath the DB package is SQLite, and SQLite is very data-type neutral. It doesn’t really care very much if you break those rules and put an integer in a string field or vice-versa, but the DB package will — to a limited degree — attempt to convert as appropriate, especially for the operations that work on numbers.<br />
<br />
You may also create both standard and unique indexes. A unique index enforces that a certain criteria can only happen once in the sheet. Now, before you go and make indexes, pause and consider. There is no right or wrong answer when it comes to what to index: it depends on what kind of queries you do regularly. If in doubt, don’t make an index. Indexes will speed up reading data from the sheet, but they will slow down writing data.<br />
<br />
To add an index, pass either the _index or _unique keys in the table definition. An example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" }<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Now, bear in mind: _index = { "name", "city"} creates two indexes in this sheet. One on the city field, one on the name field. But, _index = { {"name", "city"} } creates one index: on the combination of the two. Compound indexes help speed up queries which frequently scan two fields together, but don’t help if you scan one or the other.<br />
<br />
The admonition against making indexes willy-nilly holds double for compound indexes: do it only if you really need to!<br />
<br />
===Uniqueness===<br />
<br />
As was specified, the _unique key can be used to create a unique index. This will make it so a table can only have one record which fulfills that index. If you use an index such as _unique = { "name" } then names must be unique in the sheet. You can specify more than one key to be unique; in that case they will be checked in an OR condition.<br />
<br />
Now, if you use db:add() to insert a record which would violate the unique constraint, a hard error will be thrown which will stop your script. Sometimes that level of protection is too much, and in that case you can specify how the db layer handles violations.<br />
<br />
There are three possible ways in which the layer can handle such violations; the default is to FAIL and error out.<br />
<br />
You can also specify that the db layer should IGNORE any commands that would cause the unique constraint to be violated, or the new data should REPLACE the existing row.<br />
<br />
For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento"})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the name field being declared to be unique, these two commands can’t succeed normally. The first db:add() will create a record with the name of Bob, and the second would cause the uniqueness of the name field to be violated. With the default behavior (FAIL), the second db:add() call will raise an error and halt the script.<br />
<br />
If you want the IGNORE behavior, the second command will not cause any errors and it will simply fail silently. Bob’s city will still be Sacramento.<br />
<br />
With the REPLACE behavior, the second command will cause its data to completely overwrite and replace the first record. Bob’s city will now be San Francisco.<br />
<br />
A word of caution with REPLACE, given:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento", notes="This is something."})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the REPLACE behavior, the second record will overwrite the first-- but the second record does not have the notes field set. So Bob will now not have any notes. It doesn’t -just- replace existing fields with new ones, it replaces the entire record.<br />
<br />
To specify which behavior the db layer should use, add a _violations key to the table definition:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" },<br />
_violations = "IGNORE"<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Note that the _violations behavior is sheet-specific.<br />
<br />
===Timestamps===<br />
<br />
In addition to strings and floats, the db module also has basic support for timestamps. In the database itself this is recorded as an integer (seconds since 1970) called an epoch, but you can easily convert them to strings for display, or even time tables to use with Lua’s built-in time support.<br />
<br />
The most common use for the Timestamp type is where you want the database to automatically record the current time whenever you insert a new row into a sheet. The following example illustrates that:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:create("combat_log",<br />
{<br />
kills = {<br />
name = "",<br />
area = "",<br />
killed = db:Timestamp("CURRENT_TIMESTAMP"),<br />
_index = { {"name", "killed"} }<br />
}<br />
}<br />
)<br />
<br />
-- observe that we don't provide the killed field here - DB automatically fills it in for us.<br />
db:add(mydb.kills, {name="Drow", area="Undervault"})<br />
<br />
results = db:fetch(mydb.kills)<br />
display(results)<br />
</syntaxhighlight><br />
<br />
The result of that final display would show you this on a newly created sheet:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'_row_id': 1<br />
'area': 'Undervault'<br />
'name': 'Drow'<br />
'killed': table {<br />
'_timestamp': 1264317670<br />
}<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
As you can see from this output, the killed fields contains a timestamp-- and that timestamp is stored as an epoch value in the GMT timezone. For your convenience, the db.Timestamp type offers three functions to get the value of the timestamp in easy formats. They are <code>as_string</code>, <code>as_number</code> and <code>as_table</code>, and are called on the timestamp value itself.<br />
<br />
The as_number function returns the epoch number, and the as_table function returns a time table. The as_string function returns a string representation of the timestamp, with a default format of "%m-%d-%Y %H:%M:%S". You can override this format to anything you would like. Details of what you can do with epoch values, time tables, and what format codes you can use are specified in the Lua manual at: http://www.lua.org/pil/22.1.html for the Lua date/time functions.<br />
<br />
A quick example of the usage of these functions is:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.kills)<br />
for _, row in ipairs(results) do<br />
echo("You killed " .. row.name .. " at: " .. (row.killed and row.killed:as_string() or "no time") .."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==Deleting==<br />
<br />
The db:delete function is used to delete rows from the sheet. It takes two arguments, the first being the sheet you are deleting and the second a query string built using the same functions used to build db:fetch() queries.<br />
<br />
For example, to delete all your enemies in the city of Magnagora, you would do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these! You may inadvertantly wipe out huge chunks of your sheets if you don’t have the query parameters set just to what you need them to be. Its advised that you first run a db:fetch() with those parameters to test out the results they return.<br />
<br />
As a convenience, you may also pass in a result table that was previously retrieved via db:fetch and it will delete only that record from the table. For example, the following will get all of the enemies in Magnagora, and then delete the first one:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
db:delete(mydb.enemies, db:eq(mydb.enemies._row_id, results[1]._row_id))<br />
</syntaxhighlight><br />
<br />
That is equivalent to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
You can even pass a number directly to db:delete if you know what _row_id you want to purge.<br />
<br />
A final note of caution: if you want to delete all the records in a sheet, you can do so by only passing in the table reference. To try to protect you from doing this inadvertently, you must also pass true as the query after:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, true)<br />
</syntaxhighlight><br />
<br />
==Updating==<br />
<br />
If you make a change to a table that you have received via db:fetch(), you can save those changes back to the database by doing:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:update(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
A more powerful (and somewhat dangerous, be careful!) function to make changes to the database is db:set, which is capable of making sweeping changes to a column in every row of a sheet. Beware, if you have previously obtained a table from db:fetch, that table will NOT represent this change.<br />
<br />
The db:set() function takes two arguments: the field to change, the value to set it to, and the db:fetch() like query to indicate which rows should be affected. If you pass true as the last argument, ALL rows will be changed.<br />
<br />
To clear out the notes of all of our friends in Magnagora, we could do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:set(mydb.friends.notes, "", db:eq(mydb.friends.notes, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these!<br />
<br />
==Transactions==<br />
<br />
As was specified earlier, by default the db module commits everything immediately whenever you make a change. For power-users, if you would like to control transactions yourself, the following functions are provided on your database instance:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("my_database")<br />
mydb:_begin()<br />
mydb:_commit()<br />
mydb:_rollback()<br />
mydb:_end()<br />
</syntaxhighlight><br />
<br />
Once you issue a mydb._begin() command, autocommit mode will be turned off and stay off until you do a mydb._end(). Thus, if you want to always use transactions explicitly, just put a mydb._begin() right after your db:create() and that database will always be in manual commit mode.<br />
<br />
==Viewing and editing the database contents==<br />
<br />
A good tool to view and edit the database contents in raw form is [http://afoucal.free.fr/index.php/applications/sqlite-sorcerer/ SQlite Sorcerer] (free and available for Linux, Windows, Mac).<br />
<br />
==Debugging raw queries==<br />
<br />
If you'd like to see the queries that db: is running for you, you can enable debug mode with ''db.debug_sql = true''.<br />
<br />
=Discord Messages=<br />
<br />
Can you send messages from Mudlet to Discord? Totally. Here is an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
function sendToDiscord(data)<br />
local url = "https://discord.com/api/webhooks/1204151397977821184/Cu8ZQQo9R11AyIt3DxpOEeB8MtVMA6_AEfXoZaYxqEAOu_6hwhtA2cRLIw-VIs7py7p8"<br />
local headers = {["Content-Type"] = "application/json"}<br />
local json = yajl.to_string(data)<br />
postHTTP(json, url, headers)<br />
end<br />
<br />
local data = {<br />
content = "Hello, Discord!",<br />
embeds = {<br />
{<br />
title = "This is an embed",<br />
url = "https://example.com",<br />
image = {<br />
url = "https://example.com/image.jpg"<br />
}<br />
}<br />
}<br />
}<br />
<br />
sendToDiscord(data)<br />
<br />
</syntaxhighlight><br />
<br />
Sure enough, after starting this script, you can see a message in Discord:<br />
<br />
[[File:Message to Discord.png|border|center]]<br />
<br />
What you just need to do is create a webhook in a channel. Go to channel settings, then create this:<br />
<br />
[[File:Webhook in Discord.png|border|thumbnail|center]]<br />
<br />
Here you can find more documentation on which fields Discord allows: https://discord.com/developers/docs/resources/webhook#execute-webhook<br />
<br />
All this is one way though. Mudlet won't listen to messages from Discord. For that you'd probably have to make a Discord bot first.<br />
<br />
=Discord Rich Presence=<br />
[[File:Rich_Presence_Midmud.gif|frame]]<br />
<!-- [[File:Rich Presence Achaea.gif|frame]] --><br />
<br />
Discord Rich Presence in Mudlet allows you, the player, to show off the game you're playing and you, the game author, to get your game shown off! Advertise your game for free alongside AAA titles in server player lists :)<br />
<br />
To respect the players privacy, this option is disabled by default - enable it by ticking the Discord option for the profile:<br />
<br />
[[File:Enable Discord.png|border|center]]<br />
<br />
Once enabled, a Discord-capable game will show information in your Discord!<br />
<br />
To fine-tune the information you'd like to see displayed, go to Settings, Chat tab:<br />
<br />
[[File:Discord Privacy.png|center|400px]]<br />
<br />
== Implementing ==<br />
As a game author, you have two ways of adding Discord support to your game: via GMCP (easy) or via Lua.<br />
<br />
Adding support via GMCP means that your players don't have to install any Lua scripts which is a nicer experience. To do so, implement the [[Standards:Discord_GMCP|Discord over GMCP]] specification and [https://www.mudlet.org/contact/ get in touch] to let us know your game implements GMCP.<br />
<br />
=== GMCP ===<br />
Here's a quick cheatsheet to implement the [[Standards:Discord_GMCP|GMCP spec]]:<br />
<br />
# Create a discord [https://discordapp.com/developers/applications/me application]<br />
# Upload game logo for "rich presence invite image"<br />
# Upload same game logo in "Rich Presence Assets" with the name of <code>server-icon</code><br />
# Upon receiving "External.Discord.Hello" from the game client, reply with "External.Discord.Info" with <code>applicationid</code> ([[:File:Mudlet Discord ApplicationID.png|see screenshot]]) and "External.Discord.Status" <br />
# Send "External.Discord.Status" whenever you need to send data to the client, and fill it with the values have changed since the last status. Discord has [https://discordapp.com/developers/docs/rich-presence/best-practices#tips some ideas] for filling it in.<br />
# Done. Mudlet will enable the Discord checkbox upon receiving the <code>applicationid</code> from the game at least once.<br />
<br />
=== Lua ===<br />
An alternative way to add Discord support as a game author is [[Manual:Discord_Functions|via Lua]] - all of Discords functionality can be manipulated from it. Create a discord [https://discordapp.com/developers/applications/me application] and set it with [[Manual:Discord_Functions#setDiscordApplicationID|setDiscordApplicationID()]], then set the set the rest of the options as necessary:<br />
<br />
[[File:Discord fields.png|frame|center|Credit: Discord]]<br />
<br />
If you're a game player and your game doesn't support Discord, you can still use the functionality to set the detail, status, party and time information as desired.<br />
<br />
{{MudletVersion|3.14}}<br />
<br />
=MUD Client Media Protocol=<br />
<br />
==Client.Media==<br />
Want to add accessibility and excitement into your game? How about implementing sound and music via GMCP?<br />
<br />
The Client.Media family of GMCP packages provide a way for games to send sound and music events. GMCP media events are sent in one direction: from game server to to game client.<br />
<br />
===Client.Media in Mudlet===<br />
<br />
Media files may be downloaded manually or automatically if certain conditions are met.<br />
<br />
{{MudletVersion|4.4}}<br />
<br />
Mudlet accepts case-insensitive GMCP for the Client.Media namespace (for example, these are all acceptable: "Client.Media.Play", "client.media.play", "cLiEnT.MeDiA.Play").<br />
<br />
===Enabling Media===<br />
When a new profile opens, Mudlet adds to the Core.Supports.Set GMCP package "Client.Media 1" to signal to servers that it supports processing media files via GMCP:<br />
<br />
<syntaxhighlight lang="json"><br />
Core.Supports.Set ["Client.Media 1", ...]<br />
</syntaxhighlight><br />
<br />
To process Client.Media GMCP data in Mudlet, these boxes in the Settings window of Mudlet must be checked:<br />
<br />
# The "Enable GMCP" box in the Miscellaneous section.<br />
# The "Allow server to download and play media" box in the Game protocols section.<br />
<br />
These boxes are checked by default upon the start of a new profile in Mudlet.<br />
<br />
===Storing Media===<br />
<br />
Mudlet plays files cached in the "media" folder within a game's profile. To get files into the "media" folder you could perform either of these options:<br />
<br />
# Copy media files or extract them from an archive (zip)<br />
# Automatically download them from external resources such as your game's web server on the Internet.<br />
<br />
To enable the second option (Internet), use the "url" parameter made available in the "Client.Media.Default", "Client.Media.Load" and "Client.Media.Play" GMCP packages described below.<br />
<br />
===Loading Media===<br />
<br />
Send a '''Client.Media.Default''' GMCP event to setup the default URL directory to load sound or music files from external resources. This would typically be done once upon player login. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
|-<br />
|}<br />
<br />
For example, to setup the default URL directory for your game:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Default {<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
If downloading from external resources, it is recommended to use Client.Media.Default, set this default URL directory once, and let Mudlet download all of your media files automatically from this one resource location. Otherwise, explicitly set the "url" parameter on all of your Client.Media.Load GMCP and Client.Media.Play GMCP events to ensure that files are downloaded from the intended location(s).<br />
<br />
Send '''Client.Media.Load''' GMCP events to load sound or music files. This could be done when the player logs into your game or at the beginning of a zone that will need the media.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if a url was not set above with Client.Media.Default.<br />
|-<br />
|}<br />
<br />
For example, download the sound of a sword swooshing within the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Load {<br />
"name": "sword1.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
===Playing Media===<br />
<br />
Send '''Client.Media.Play''' GMCP events to play sound or music files.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely and a url was not set above with Client.Media.Default or Client.Media.Load.<br />
|-<br />
| style="text-align:center;"| No<br />
| "type"<br />
| "sound" or "music"<br />
| "sound"<br />
| style="text-align:left;"|<br />
* Identifies the type of media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "tag"<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "volume"<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| "fadein"<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"fadeout"<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| "start"<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
* 1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"loops"<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the sound or music to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a lower priority while this media plays.<br />
|-<br />
| style="text-align:center;" |No<br />
|"continue"<br />
| true or false<br />
|true<br />
| style="text-align:left;" |<br />
*Only valid for media files with a "type" of "music".<br />
*Continues playing matching new music files when true.<br />
*Restarts matching new music files when false.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
|}<br />
<br />
==== name====<br />
<br />
For example, to simply play the sound of a cow mooing already stored in the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Or some lightning stored in a "weather" sub-folder under the "media" folder.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "weather/lightning.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
The "name" parameter may be used for stopping media with the Client.Media.Stop GMCP event.<br />
<br />
====url====<br />
<br />
If you maintain your sound files on the Internet and don't set a default URL with Client.Media.Default, or preload them with Client.Media.Load, include the "url" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
====type: sound====<br />
<br />
Media files default to a "type" of "sound" when the "type" parameter is not specified, such as in the example above. It is good practice to specify the "type" parameter to best keep media organized within your implementation:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====tag====<br />
<br />
To play the sound of a sword swooshing and categorized as "combat":<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat"<br />
}<br />
</syntaxhighlight><br />
<br />
The "tag" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====type: music====<br />
<br />
Add background music to your environment through use of the "music" value set upon the "type" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====volume: 1 to 100====<br />
<br />
As the character draws nearer to or farther from the environmental feature, consider adjusting the "volume" parameter. Example values, followed by syntax examples:<br />
<br />
*Maximum: 100 (recommended to use rarely)<br />
*High: 75<br />
*Default: 50<br />
* Low: 25<br />
* Minimum: 1 (recommended to use rarely)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment",<br />
"volume": 75<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "volume" values of type string ("75") into integers (75) as needed.<br />
<br />
====fadein====<br />
<br />
Increase volume from the start of the media [start position, volume one] to the number in milliseconds specified with the "fadein" parameter [position start + milliseconds, volume specified with the "volume" parameter]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade in)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "monty_python.mp3",<br />
"type": "music",<br />
"volume": 100,<br />
"fadein": 1000<br />
}<br />
</syntaxhighlight><br />
+---------------------------+-----------------------+<br />
| Fade in 1000 milliseconds | Normal |<br />
+---------------------------+-----------------------+<br />
Volume 1|........::::::::::iiiiiiiii%%%%%%%%%%%%%%%%%%%%%%%%|Volume 100<br />
+---------------------------+-----------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadein" values of type string ("1000") into integers (1000) as needed.<br />
<br />
==== fadeout====<br />
<br />
Decrease volume from a position in milliseconds subtracted from the duration of the media [position duration - milliseconds, volume specified with the "volume" parameter] to the end of the media [position duration, volume one]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade out)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "the_matrix.mp3",<br />
"type": "music",<br />
"volume": 50,<br />
"fadeout": 333<br />
}<br />
</syntaxhighlight><br />
+-----------------------+---------------------------+<br />
| Normal | Fade out 333 milliseconds |<br />
+-----------------------+---------------------------+<br />
Volume 50|%%%%%%%%%%%%%%%%%%%%%%%%iiiiiiiii::::::::::........|Volume 1<br />
+-----------------------+---------------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadeout" values of type string ("333") into integers (333) as needed.<br />
<br />
==== start ====<br />
<br />
Start playing a media track at the number of milliseconds specified. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (start from beginning)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "mudlet_beatboxing.mp3",<br />
"type": "music",<br />
"volume": 75,<br />
"start": 1000<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "start" values of type string ("100") into integers (100) as needed.<br />
<br />
==== loops: -1, 1 or more ====<br />
<br />
The "loops" parameter controls how many times the sound repeats and defaults to 1 if not specified. A value of -1 will loop the file indefinitely.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "clock/hour_bell.wav",<br />
"type": "sound",<br />
"loops": 3<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "underdark.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "loops" values of type string ("-1") into integers (-1) as needed.<br />
<br />
==== priority: 1 to 100 ====<br />
<br />
The "priority" parameter sets precedence for Client.Media.Play GMCP events that include a "priority" setting. The values for the "priority" parameter range between 1 and 100. Given that two Client.Media.Play GMCP events have the same priority, the media already playing will continue playing. In Mudlet, media without priority set is not included comparisons based on priority.<br />
<br />
A common place to find priority implemented is with combat. In the following example, imagine a combat scenario where some sounds of sword thrusts were interrupted by a successful blocking maneuver.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3,<br />
"priority": 60<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "block1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"priority": 70<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "priority" values of type string ("25") into integers (25) as needed.<br />
<br />
The "priority" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====continue: true or false (for music)====<br />
<br />
Typically sent with the "type" of "music" is the parameter "continue", which presents the following values:<br />
<br />
*true: continues music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
*false: restarts music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "city.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"continue": true<br />
}<br />
</syntaxhighlight><br />
<br />
If the "continue" parameter is not specified, behavior will default to ''true'' for music.<br />
<br />
Although using the boolean type is recommended, Mudlet parses "continue" values of type string ("true" and "false") into boolean (''true'' and ''false'') as needed, as not all game drivers support a boolean type.<br />
<br />
==== key====<br />
<br />
The "key" parameter enables media categorization, similar to the "tag" parameter, however it adds a feature of uniqueness that halts media currently playing with the same key, replacing it with the media that arrived from a new Client.Media.Play GMCP event. This update will only occur if the "name" or "url" associated with the currently playing media does not match the new media, while the key is identical.<br />
<br />
In the example below, consider that a player moves from a sewer area to a village. The "key" parameter is used to stop the previously playing ''sewer.mp3'' and start playing ''village.mp3'' within the second Client.Media.Play GMCP event. <br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sewer.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "village.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
The "key" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
{{note}} Where music is bound to change, continue or stop as a player enters a new room, consider allowing for a slight pause of 1 heart beat or tick to send the Client.Media.Play or Client.Media.Stop GMCP events. This practice reduces the number of Client.Media.Play GMCP events sent when the player travels through several rooms quickly.<br />
<br />
==== randomization====<br />
<br />
Wildcards ''*'' (asterisk) and ''?'' (question mark) may be used within the name to randomize media file(s) selection.<br />
<br />
Given that media files underdark.wav, underdark.mp3 and underdark_dark_elven_moshpit.mp3 were all present in the media/environment directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play using the ''*'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "underdark*",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": false<br />
}<br />
</syntaxhighlight><br />
<br />
If media files sword1.wav, sword2.wav and sword3.wav were all present in the media/combat directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play per each loop using the ''?'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "combat/sword?.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3<br />
}<br />
</syntaxhighlight><br />
<br />
=== Stopping Media ===<br />
<br />
Send '''Client.Media.Stop''' GMCP events to stop sound or music media.<br />
<br />
{| class="wikitable"<br />
!Required<br />
!Key<br />
!Value<br />
! style="text-align:left;" |Purpose<br />
|-<br />
| style="text-align:center;" | No<br />
| "name"<br />
|<file name><br />
| style="text-align:left;" |<br />
*Stops playing media by name matching the value specified.<br />
|-<br />
| style="text-align:center;" | No<br />
|"type"<br />
|"sound" or "music"<br />
| style="text-align:left;" | <br />
*Stops playing media by type matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
| "tag"<br />
|<tag><br />
| style="text-align:left;" |<br />
*Stops playing media by tag matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
| style="text-align:left;" |<br />
*Stops playing media with priority less than or equal to the value.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
| style="text-align:left;" | <br />
*Stops playing media by key matching the value specified.<br />
|-<br />
|}<br />
<br />
====all====<br />
<br />
Send the Client.Media.Stop GMCP event with no parameters to stop all playing media within a given game profile.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {}<br />
</syntaxhighlight><br />
<br />
====parameters====<br />
<br />
Send any combination of the name, type, tag, priority or sound parameters and valid corresponding values to stop playing media that matches ''all'' combinations of the parameters.<br />
<br />
Stop the rain.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"name": "rain.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media using the "type" of "sound".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "tag" of "combat" ''and'' that has a "priority" less than or equal to 50.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"tag": "combat",<br />
"priority": 50<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "key" of "area-music".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
=GUI Scripting in Mudlet=<br />
Mudlet has extremely powerful GUI capabilities built into it, and with the inclusion of the Geyser and Vyzors layout managers in Mudlet's Lua API it is quicker and easier to get a basic UI created.<br />
<br />
==Geyser==<br />
Geyser is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
Geyser's manual is quite extensive - [[Manual:Geyser|follow here]] to read up on it.<br />
<br />
===UI template===<br />
Akaya has created a UI template based on Geyser that can serve as a quick start for customizing the Mudlet interface to your character:<br />
<br />
[[File:Geyser UI template.png|center|800px|border]]<br />
<br />
To get started with it, see the forum thread about [http://forums.mudlet.org/viewtopic.php?f=6&t=4098 Geyser UI Template].<br />
<br />
==Simple Window Manager==<br />
Simple Window Manager is a light-weight script designed to provide the GUI object placement and sizing functionality seen in Geyser and Vyzor without any of the extras. Any GUI object, once created normally, can be added to the SWM along with a corner to base its positioning info off of, the distance from that corner, and the size of the object in any combination of pixels and percentages of the screen. SWM does all the behind the scenes work to keep all objects it has been given to manage in their correct places and sizes as the screen changes size. All other interactions with GUI objects are handled using standard functions built into Mudlet.<br />
<br />
Simple Window Managers manual, and download, can be [http://forums.mudlet.org/viewtopic.php?f=6&t=3529 found here].<br />
<br />
==Useful Resources==<br />
There are several useful resources you can refer to when creating your GUI.<br />
<br /><br />
<br />
;Wiki Resources<br />
*[[Manual:Geyser|Geyser Tutorial]]:<br />
:Excellent for getting an initial feel of how to use the Geyser layout manager.<br />
*[[Manual:Lua_Functions#UI_Functions|GUI API]]:<br />
:The GUI section of the Lua API manual<br />
;External Resources<br />
*[http://forums.mudlet.org/viewforum.php?f=11 Geyser subforum]:<br />
:The Geyser Layout Manager subforum on Mudlet's forums.<br />
*[http://forums.mudlet.org/viewtopic.php?f=5&t=1376 GUI Screenshots]:<br />
:A pinned thread on Mudlet's forums for showing what your GUI looks like. Useful for ideas and to see what is possible.<br />
*[http://forums.mudlet.org/viewtopic.php?f=9&t=1974 Godwars II Mudlet UI]:<br />
:A forum thread which follows the evolution of the UI provided by [http://www.godwars2.org God Wars II]<br />
[[Category:Mudlet Manual]]<br />
<br />
==Resetting your UI==<br />
While scripting your UI, you can reset it completely and have your scripts be loaded from scratch with the [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] function - in the input line, type <code>lua resetProfile()</code>.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Scripting&diff=20908Manual:Scripting2024-02-05T21:01:32Z<p>Kebap: /* Discord Messenges */ Rename section to /* Discord Messages */</p>
<hr />
<div>{{TOC right}}<br />
=Scripting with Mudlet=<br />
<br />
Lua tables can basically be considered multidimensional arrays and dictionaries at the same time. If we have the table matches, matches[2] is the first element, matches[n+1] the n-th element.<br />
<br />
<syntaxhighlight lang="lua"><br />
a = "Tom"<br />
matches[2] = "Betty"<br />
b = matches[2]<br />
c = a .. b and e will equal "TomBetty"<br />
</syntaxhighlight><br />
<br />
To output a table you can use a convenience function - ''display(mytable)'', which is built into Mudlet.<br />
<br />
==Lua interface functions - triggers, timers etc.==<br />
<br />
How to get data from regex capture groups? Regular expression capture groups (e.g. "(\d+)" ) are passed on to Lua scripts as a Lua table matches. To make use of this information inside Lua scripts, you need to specify the number of the capture group within the regex.<br />
<br />
<code>Example: You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
This regex contains 3 capture groups, but only the 2 green colored ones contain data as the red capture group is a non-capturing group. Consequently, your Lua script gets passed only 2 instead of 3 capture groups and matches[4] is undefined.<br />
<br />
In your Lua script you may write following program in order to print the number and status of your weapons on the screen:<br />
<br />
<code>You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
<syntaxhighlight lang="lua"><br />
number_of_weapons = matches[2]<br />
status_of_weapons = matches[3]<br />
notice = number_of_weapons .. status_of_weapons<br />
echo( notice )<br />
send( "put weapons in backpack" )<br />
<br />
-- the following 2 lines color the first capture<br />
-- group red and the second group blue<br />
-- see below for details<br />
<br />
selectCaptureGroup( 2 )<br />
setFgColor( 255,0,0 )<br />
<br />
selectCaptureGroup( 3 )<br />
setFgColor( 0,0,255 )</syntaxhighlight><br />
<br />
The best way is to use selectCaptureGroup( number ) to select the proper capture group and then perform your actions on it e.g. replace(), highlight etc. Note: Both selectCaptureGroup() and matches[n] start with group 1 (which is the whole match. The defined capture groups start with 2).<br />
<br />
How to select all occurrences of "Tom" and highlight them?<br />
<br />
You add a function like this to a script containing you main function definitions. Note that script items differ from all other "scripts" in triggers, timers, actions etc. because they require you to put your code in proper functions that can be called by your other trigger-scripts, timer-scripts etc. via normal function calls. Trigger-scripts, timer-scripts etc. cannot contain any function definitions because they are automatically generated functions themselves because this makes usage a lot easier.<br />
<br />
To come back to our question how to select all occurrences of "Tom" and highlight them:<br />
<br />
<syntaxhighlight lang="lua"><br />
function setBgColorAll( word, r, g, b )<br />
i = 0<br />
word_count = 1<br />
while i > -1 do<br />
i = selectString(word, word_count)<br />
if i == -1 then<br />
return<br />
end<br />
word_count = word_count +1<br />
setBgColor( r, g, b )<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
Then you simply define a substring matching trigger on the word "Tom" and in the trigger script you call above function:<br />
<br />
<syntaxhighlight lang="lua">setBgColorAll("Tom", 255,50,50)</syntaxhighlight><br />
<br />
Since Mudlet 4.11+ it is possible to use name capture groups. You can verify if feature availability by checking <code>mudlet.supports.namedPatterns</code> flag.<br />
Let's say you have multiple patterns that you want to handle with one code.<br />
<br />
<code>^My name is (?<name>\w+)\. My class is (?<class>\w+)\.</code><br />
<br />
<code>^I am (?<class\w+)\ and my name is (?<name>\w+)\.</code><br />
<br />
Notice that class and name come in different order, therefore in first case we will have name under <code>matches[2]</code> and in second case under <code>matches[3]</code>.<br />
With named capture groups in both cases we will have name available under <code>matches.name</code> and class under <code>matches.class</code>.<br />
<br />
Code example to handle named matches above:<br />
<syntaxhighlight lang="lua"><br />
echo("Name: " .. matches.name .. "\n")<br />
echo("Class: " .. matches.class .. "\n")<br />
</syntaxhighlight><br />
<br />
==Sending commands or printing information messages==<br />
<br />
To print information messages on the session screen you can use the echo( message ) function, or insertText( text ). Currently, it only takes one string as argument.<br />
<br />
To send a command to the MUD, you can use the send( command ) function. In Alias scripts the command that is being sent to the MUD is contained in the variable command that you can change in the context of Alias scripts. Alias take regular expressions, as well. As a result, you can use following regex and script to talk like Yoda: Perl regex:<br />
<br />
<code> say (\w+).*(\w*).*(.*) </code><br />
<br />
script:<br />
<br />
<syntaxhighlight lang="lua"><br />
send( "say " .. matches[4] .." " .. matches[2] .." ".. matches[3] )<br />
</syntaxhighlight><br />
<br />
Note: The variable "command" contains what was entered in the command line or issued via the expandAlias( ) function. If you use expandAlias( command ) inside an alias script the command would be doubled. You have to use send( ) inside an alias script to prevent recursion. This will send the data directly and bypass the alias expansion.<br />
<br />
===Changing and formatting text from the MUD===<br />
<br />
When sending commands to the MUD - from now on referred to as output stream - alias scripts find the command that was issued by the user stored in the variable "command".<br />
<br />
By manipulating the value, the command can easily be changed before it is being sent to the MUD.<br />
<br />
However, things get much more complicated with the data received from the MUD, from now on referred to as input stream. Before triggers can be run on the MUD data, Mudlet has to strip all format codes from the text and store it in data structures associated with the text. Consequently, the text that is being passed on to the trigger processing unit is a small subset of the data received from the MUD. If you want to edit, replace, delete or reformat text from within your trigger scripts you have to keep this in mind if you don’t want to lose all text format information such as colors etc.<br />
<br />
As the text is linked with data structures containing the format of the text, the cursor position inside the line is important if data is being changed. You select a word or a sequence of characters from the line and then issue commands to do actions on the selected data.<br />
<br />
Replacing the word "Tom" with "Betty" in the line: Jim, Tom and Lucy are learning a new spell. This could be done with following script:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Tom",1)<br />
replace("Betty")<br />
</syntaxhighlight><br />
<br />
Things get more complicated if there are two or more occurrences of "Tom" in the line e.g. Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
The above example code would select the first occurrence of "Tom" in this line and ignore the second. If you want to work on the the second occurrence of "Tom" you have to specify the occurrence number in the call to select().<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString( "Tom", 2 )<br />
replace( "Betty" )<br />
</syntaxhighlight><br />
<br />
This code would change the second "Tom" and leave the first "Tom" alone. The function call<br />
<br />
<syntaxhighlight lang="lua">replaceAll( "Betty" )</syntaxhighlight><br />
<br />
will replace all occurrences of "Tom" with "Betty" in the line if "Tom" has been selected before. replaceAll() is a convenience function defined in LuaGlobal.lua.<br />
<br />
Colorization example: You want to change to color of the words "ugly monster" to red on a white background.<br />
<br />
You add a new trigger and define the regex: ugly monster In the script you write:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("ugly monster", 1 )<br />
setFgColor(255,0,0)<br />
setBgColor(255,255,255)<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
Another means to select text is to select a range of characters by specifying cursor positions. If we have following line: Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
<syntaxhighlight lang="lua">selectSection( 28, 3 )</syntaxhighlight><br />
<br />
This example would select the second Tom. The first argument to selectSection is the cursor position within the line and the second argument is the length of the selection.<br />
<br />
<syntaxhighlight lang="lua">selectCaptureGroup( number )</syntaxhighlight><br />
<br />
This function selects the captureGroup number if you use Perl regular expressions containing capture groups. The first capture group starts with index 1.<br />
<br />
==Deleting Text - Gagging==<br />
<br />
<syntaxhighlight lang="lua">deleteLine()</syntaxhighlight><br />
<br />
This function deletes the current line - or any line where the cursor is currently placed. You can use repeated calls to this function to effectively erase the entire text buffer. If you want to delete or gag certain words only, you can select the text that you want to delete and then replace it with an empty string e.g:<br />
<br />
If you get this line form the MUD: "Mary and Tom walk to the diner."<br />
<br />
<syntaxhighlight lang="lua">selectString( "Tom", 1 )<br />
replace( "" )</syntaxhighlight><br />
<br />
Then the output will be changed to: "Mary and walk to the diner."<br />
<br />
==Cursor Movement and Cursor Placement==<br />
Mudlet allows you to insert text arbitrarily within the buffer - in the previous line, in the previous ten lines, or even the first line that you've ever saw. These are the tools to help you with the job:<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( windowName, x, y )]]</code> This will move the user cursor of window windowName to the absolute (x/y) coordinates in the text.<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( "main", 20, 3950 )]]</code> will move the cursor on the 20th character from the left on line number 3950. To determine the current cursor position you can use getLineNumber() and getColumnNumber() as well as [[Manual:UI_Functions#getLastLineNumber|getLastLineNumber()]] to get the number of the last line in the text buffer. moveCursorEnd("main") will move the cursor of the main display to end of the buffer. This is always a new line of size 1 containing the character \n.<br />
<br />
<code>number_of_last_line_in_text = [[Manual:UI_Functions#getLineCount|getLineCount()]]</code> returns the number of the last line of the text in the console buffer. This number will change as soon as a new \n is printed either by the user or when a new line arrives from the MUD. All lines from the MUD are terminated with \n which is called line feed or the new line character. This control character ends the current line and move the cursor to the beginning of the next line, thus creating a new, empty line below the line that contains the \n.<br />
<br />
<code>line_number_of_the_current_cursor_position = [[Manual:UI_Functions#getLineNumber|getLineNumber()]]</code><br />
<br />
<code>column_number_of_the_current_cursor_position = [[Manual:UI_Functions#getColumnNumber|getColumnNumber()]]</code><br />
<br />
<code>luaTable_containing_textlines = [[Manual:UI_Functions#getLines|getLines( absolute_line_number_from, absolute_line_number_to )]]</code> this will return a Lua table containing all lines between the absolute positions from and to.<br />
<br />
{{note}} This function uses absolute line numbers, not relative ones like in [[Manual:UI_Functions#moveCursor|moveCursor()]].<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor()]]</code> returns true or false depending on whether the move was possible and done.<br />
<br />
=== Inserting text in the middle of the line ===<br />
Here's an example where we'll append the text ''(one)'' right after the word ''exit'' in the line of <code>You see a single exit leading west.</code><br />
<br />
[[File:Inserting text.png|center|650px]]<br />
<br />
The pattern we used was an ''exact match'' for <code>You see a single exit leading west.</code> and the code is:<br />
<br />
<syntaxhighlight lang="lua"><br />
if moveCursor(string.find(line, "exit")+#("exit")-1, getLineNumber()) then<br />
insertText("(one)")<br />
end<br />
</syntaxhighlight><br />
<br />
What happened here:<br />
* we triggered on the desired line using our pattern above<br />
* we used [[Manual:UI_Functions#moveCursor|moveCursor()]] to place the cursor in the desired position within the line. [[Manual:UI_Functions#moveCursor|moveCursor()]] takes both the line number and the position within the line to place our virtual cursor on, so<br />
** we used [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] to find the position of the word "exit" within the line<br />
** but [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] returns us the position of the first character of the word we want, while we want to have the text be right after it - so we find out how long our word is with <code>#("exit")</code>, add that to the number returned by [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] which gets us the first character + the length of the word - which isn't quite at the end of the word, but the word plus the space (because of [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] and the first character) - so we substract 1 to move our cursor right at the end of the word<br />
** we then use [[Manual:UI_Functions#getLineNumber|getLineNumber()]] to get the current line number, so our cursor is placed on the current line, at our desired position<br />
* lastly we finally insert the text with [[Manual:UI_Functions#insertText|insertText()]], which puts the text exactly where our virtual cursor is<br />
<br />
Done! You can also use [[Manual:UI_Functions#cinsertText|cinsertText()]] for coloured inserts, and other functions [[Manual:Scripting#Cursor_Movement_and_Cursor_Placement|mentioned above]] and in the [[Manual:UI_Functions|API manual]] to help you do what you'd like.<br />
<br />
==User defined dockable windows==<br />
<br />
You may want to use dock windows to display information you gathered in your scripts, or you may want to use them as chat windows etc. Check out [[Manual:Geyser#Geyser.UserWindow|Geyser.UserWindow]] on how to add them!<br />
<br />
==Dynamic Triggers==<br />
<br />
<code>triggerID = tempTrigger( substring pattern, code ) creates a fast substring matching trigger</code> <br />
<br />
<code>triggerID = tempRegexTrigger( regex, code ) creates a regular expression matching trigger</code><br />
<br />
<code>triggerID = tempBeginOfLineTrigger( begin of line pattern, code ) creates a fast begin of line substring trigger</code><br />
<br />
=Scripting howtos=<br />
==How to convert a string to value?==<br />
Say you'd like to capture a number from a trigger, but the capture always ends up being a "string" (or, just text on which you can't do any maths on) even if it's a number. To convert it to a number, you'd want to use the ''tonumber()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
myage = tonumber(matches[2])<br />
</syntaxhighlight><br />
<br />
==How to highlight my current target?==<br />
<br />
You can put the following script into your targetting alias:<br />
<br />
<syntaxhighlight lang="lua">if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
Where target is your target variable. Note that you have to use the full name, capitalized. If you’d like the script to auto-capitalize for you, you can use this version:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = target:title()<br />
if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
{{note}} Ensure you're on Mudlet 3.5.0+ so you can put ''function()'' in a ''[[Manual:Lua_Functions#tempTrigger|tempTrigger()]]''.<br />
<br />
==How to format an echo to a miniConsole?==<br />
<br />
One of the ways you can create multi-line displays in a miniConsole with variable information is with string.format and the use of [[ ]] brackets for text, which allow for multiple line in text:<br />
<br />
<syntaxhighlight lang="lua"><br />
local WindowWidth, WindowHeight = getMainWindowSize();<br />
createMiniConsole("sys",WindowWidth-650,0,650,300)<br />
<br />
local name, age, sex = "Bob", 34, "male"<br />
<br />
cecho("sys", string.format([[<br />
<br />
/---------\<br />
%s<br />
%dyrs<br />
sex - %s <br />
\---------/<br />
]], name, age, sex))<br />
</syntaxhighlight><br />
<br />
==How to play a sound when I receive communication while afk?==<br />
<br />
[[File:Play_sound_when_afk_trigger.png]]<br />
<br />
For this to work, place the line you'd like to trigger on in the first pattern box and select the appropriate pattern type. Then add ''return not hasFocus()'' with the Lua function as the second pattern, enable the AND trigger, and set the line delta to zero. Then just enable ''play sound'', choose your sound and you're set!<br />
<br />
==How can I make a key that toggles between commands?==<br />
To make a key that toggles between two actions, for example - sleep/wake, you can use this as the script:<br />
<br />
<syntaxhighlight lang="lua"><br />
if not sleeping then<br />
send("sleep")<br />
sleeping = true<br />
else<br />
send("wake")<br />
sleeping = false<br />
end<br />
</syntaxhighlight><br />
<br />
<!-- Old Heading: How can I make a trigger that goes off only if the next line is not a particular one? --><br />
==How can I make a trigger with a next-line condition?==<br />
<br />
Here's how you can set it up - replace ''line1'' and ''line2'' with appropriate lines.<br />
<br />
[[File:Trigger_multiline_not_another_example.png|center]]<br />
<br />
Here's [[Media:Match only of next line is *not* line2.xml.zip|the Mudlet XML]] you can download for this!<br />
<br />
==How to target self or something else?==<br />
<br />
[[File:Buffselforother.png|border|350px]]<br />
<br />
Using regex and an 'or' statement allows us to consolidate multiple aliases, or an if statement, into a single more simple alias. <br />
When a regex is found it will use it, but if you don't specify one then the alternative will be used. The use of 'or' can be used with any function in Mudlet.<br />
In this example, one can type "buff" to buff themself, or "buff ally" to buff their ally instead.<br />
<br />
<syntaxhighlight lang="lua"><br />
^buff(?: (\w+))?$<br />
<br />
send("cast buff on "..(matches[2] or "myself"))<br />
</syntaxhighlight><br />
<br />
==How to delete everything between two lines?==<br />
When deleteLine() is called, every following line shifts back in numerical position. Thus if we know where we're starting and how many lines to expect, we can use a for loop to gag everything between line a and b by leaving the cursor in one spot. In the below example, line_a_number is the number of the line you want to start at, and line_b_number is the ending line. To gag x number of lines instead, use line_a_number + x in place of line_b_number.<br />
<br />
<syntaxhighlight lang="lua"><br />
for i = line_a_number, line_b_number, 1<br />
do<br />
moveCursor(0, line_a_number)<br />
selectCurrentLine()<br />
deleteLine()<br />
end<br />
</syntaxhighlight><br />
<br />
== How to capture foreground line color information? ==<br />
Here's an example that loops through each character in a line of text and prints the character and its foreground color to a miniconsole if the color has changed from the previous character:<br />
<br />
Trigger: <code>^</code> (regex)<br />
<br />
Code:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer =<br />
miniconsoleContainer or Adjustable.Container:new({name = "miniconsoleContainer"})<br />
myMiniconsole =<br />
Geyser.MiniConsole:new(<br />
{<br />
name = "myMiniconsole",<br />
x = 0,<br />
y = 0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width = "100%",<br />
height = "100%",<br />
},<br />
miniconsoleContainer<br />
)<br />
<br />
local index = 0<br />
local line = getCurrentLine()<br />
local linesize = #line<br />
local currentlinenumber = getLineNumber()<br />
local r, g, b = 0, 0, 0<br />
local cr, cg, cb -- last seen colors<br />
while index < linesize do<br />
index = index + 1<br />
moveCursor("main", index, currentlinenumber)<br />
selectString(line:sub(index), 1)<br />
r, g, b = getFgColor()<br />
if cr ~= r or cg ~= g or cb ~= b then<br />
cr, cg, cb = r, g, b<br />
myMiniconsole:echo(string.format("rgb(%d,%d,%d)%s", r, g, b, line:sub(index, index)))<br />
else<br />
myMiniconsole:echo(string.format("%s", line:sub(index, index)))<br />
end<br />
line:sub(index, index)<br />
end<br />
myMiniconsole:echo("\n")<br />
</syntaxhighlight><br />
<br />
==How to enter a carriage return / enter command?==<br />
Say you'd like to gag the following line, and just continue ... <br />
<br />
[ Press Enter to continue ]<br />
<br />
<syntaxhighlight lang="lua"><br />
Trigger: [ Press Enter to continue ] (set to exact match)<br />
Code: deleteLine()<br />
send("\n")<br />
</syntaxhighlight><br />
<br />
==How to repeat commands with #?==<br />
Install the [https://forums.mudlet.org/viewtopic.php?f=6&t=1275 following alias], and with it <code>#5 mycommand</code> will get repeated five times.<br />
<br />
== How to move the command line over? ==<br />
<br />
To move the command line over to the right, create a new script and add the following to it:<br />
<br />
<syntaxhighlight lang="css"><br />
setCmdLineStyleSheet("main", [[<br />
QPlainTextEdit {<br />
padding-left: 100px; /* change 100 to your number */<br />
background-color: black; /* change it to your background color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
== How to add a background for Mudlets buttons? ==<br />
You can give Mudlets buttons a background to have them blend in with your UI by doing this:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- replace the /home/vadi/Pictures/tile.png location below with the one of your picture!<br />
-- you can download the sample tile.png from https://opengameart.org/content/bevouliin-free-game-background-for-game-developers<br />
local backgroundpath = [[/home/vadi/Pictures/tile.png]]<br />
-- Windows:<br />
-- local backgroundpath = [[C:/Users/Vadim/Downloads/Free game background/transparent PNG/tile.png]]<br />
<br />
setAppStyleSheet([[<br />
QToolBar {<br />
border-image: url(]]..backgroundpath..[[);<br />
<br />
}<br />
<br />
QToolBar QToolButton:!hover {<br />
color: white;<br />
}<br />
QToolBar QToolButton:hover {<br />
color: black;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
Result:<br />
<br />
[[File:Mudlet tiled buttons.png|frame|left]]<br />
<br clear=all><br />
<br />
= Advanced scripting tips =<br />
== Do stuff after all triggers/aliases/scripts are run ==<br />
This little snippet will have your commands be executed right after, depending on the context you run it in, all triggers, aliases or scripts are completed:<br />
<br />
<syntaxhighlight lang="lua">tempTimer(0, [[mycode]])</syntaxhighlight><br />
<br />
== How to delete the previous and current lines ==<br />
<br />
This little snippet comes from [http://forums.mudlet.org/viewtopic.php?f=9&t=2411&p=10685#p10685 Iocun]:<br />
<br />
<syntaxhighlight lang="lua"><br />
moveCursor(0,getLineCount()-1)<br />
deleteLine()<br />
moveCursor(0,getLineCount())<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=db: Mudlet's database frontend=<br />
<br />
The DB package is meant to provide easier access to a database, so you don’t have to know SQL or use the luasql module to set and get at your data. However, it does require that the luasql module be compiled and included in Mudlet to function.<br />
<br />
==Creating a Database==<br />
<br />
Before you can store anything in a database, you need to create one. You may have as many independent databases as you wish, with each having as many unique tables-- what we will call sheets in this package, so as to avoid confusion with Lua tables - think spreadsheets.<br />
<br />
To create a database, you use the db:create() function, passing it the name of your database and a Lua table containing its schema configuration. A schema is a mold for your database - it defines what goes where. Using the spreadsheet example, this would mean that you’d define what goes into each column. A simple example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes"}})<br />
</syntaxhighlight><br />
<br />
This will create a database which contains two sheets: one named friends, the other named enemies. Each has three columns, name, city and notes-- and the datatype of each are strings, though the types are very flexible and can be changed basically whenever you would like. It’ll be stored in a file named Database_people.db in your Mudlet config directory on the hard drive should you want to share it.<br />
<br />
It’s okay to run this function repeatedly, or to place it at the top-level of a script so that it gets run each time the script is saved: the DB package will not wipe out or clear the existing data in this case. <br />
<br />
{{Note}} You may not create a column or field name which begins with an underscore. This is strictly reserved to the db package for special use.<br />
<br />
{{Note}} Adding new columns to an existing database did not work in Mudlet 2.1 - see [[Manual:Lua_Functions#db:create|db:create()]] on how to deal with this.<br />
<br />
<!--<br />
More importantly, this allows you to add columns to an existing sheet. If you change that line to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes", "enemied"}})<br />
</syntaxhighlight><br />
<br />
It will notice that there is a new column on enemies, and add it to the existing sheet-- though the value will end up as nil for any rows which are already present. Similarly, you can add whole new sheets this way. It is not presently possible to -remove- columns or sheets without deleting the database and starting over.<br />
--><br />
<br />
==Adding Data==<br />
<br />
To add data to your database, you must first obtain a reference (variable) for it. You do that with the db:get_database function, such as:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("people")<br />
</syntaxhighlight><br />
<br />
The database object contains certain convenience functions (discussed later, but all are preceded with an underscore), but also a reference to every sheet that currently exists within the database. You then use the db:add() function to add data to the specified sheet.<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends, {name="Ixokai", city="Magnagora"})<br />
</syntaxhighlight><br />
<br />
If you would like to add multiple rows at once to the same table, you can do that by just passing in multiple tables:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends,<br />
{name="Ixokai", city="Magnagora"},<br />
{name="Vadi", city="New Celest"},<br />
{name="Heiko", city="Hallifax", notes="The Boss"}<br />
)<br />
</syntaxhighlight><br />
<br />
Notice that by default, all columns of every table are considered optional-- if you don’t include it in the add, then it will be set to its default value (which is nil by default)<br />
<br />
For those familiar with databases: with the DB package, you don’t have to worry about committing or rolling back any changes, it will commit after each action automatically. If you would like more control than this, see Transactions below.<br />
<br />
You also cannot control what is the primary key of any sheets managed with DB, nor do you have to create one. Each row will get a unique integer ID that automatically increments, and this field can be accessed as "_row_id".<br />
<br />
==Querying==<br />
<br />
Putting data in isn’t any fun if you can’t get it out. If you want every row from the sheet, you can do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends)<br />
</syntaxhighlight><br />
<br />
But rarely is that actually useful; usually you want to get only select data. For example, you only want to get people from the city of Magnagora. To do that you need to specify what criteria the system should use to determine what to return to you. It looks like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
So the basic command is - db:fetch(_sheet_, _what to filter by_)<br />
<br />
The following filter operations are defined:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:eq(field, value[, case_insensitive]) -- Defaults to case insensitive, pass true as the last arg to<br />
reverse this behavior.<br />
db:not_eq(field, value[, case_insensitive) -- Not Equal To<br />
db:lt(field, value) -- Less Than<br />
db:lte(field, value) -- Less Than or Equal to.<br />
db:gt(field, value) -- Greater Than<br />
db:gte(field, value) -- Greater Than or Equal To<br />
db:is_nil(field) -- If the column is nil<br />
db:is_not_nil(field) -- If the column is not nil<br />
db:like(field, pattern) -- A simple matching pattern. An underscore matches any single character,<br />
and a percent(%) matches zero or more characters. Case insensitive.<br />
db:not_like(field, pattern) -- As above, except it'll give you everything but what you ask for.<br />
db:between(field, lower_bound, upper_bound) -- Tests if the field is between the given bounds (numbers only).<br />
db:not_between(field, lower_bound, upper_bound) -- As above, only... not.<br />
db:in_(field, table) -- Tests if the field is in the values of the table. NOTE the trailing underscore!<br />
db:not_in(field, table) -- Tests if the field is NOT in the values of the table *<br />
</syntaxhighlight><br />
<br />
The db:in_ operator takes a little more explanation. Given a table, it tests if any of the values in the table are in the sheet. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:in_(mydb.friends.city, {"Magnagora", "New Celest"})<br />
</syntaxhighlight><br />
<br />
It tests if city == "Magnagora" OR city == "New Celest", but with a more concise syntax for longer lists of items.<br />
<br />
There are also two logical operators:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:AND(operation1, ..., operationN)<br />
db:OR(operation1, operation2)<br />
</syntaxhighlight><br />
<br />
You may pass multiple operations to db:fetch in a table array, and they will be joined together with an AND by default. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends,<br />
{db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "X%")}<br />
)<br />
</syntaxhighlight><br />
<br />
This will return every record in the sheet which is in the city of Magnagora, and has a name that starts with an X. Again note that in LIKE patterns, a percent is zero or more characters — this is the same effect as "X.*" in pcre patterns. Similarly, an underscore matches any single characters and so is the same as a dot in pcre.<br />
<br />
Passing multiple expressions in an array to db:fetch is just a convenience, as its exactly the same as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:AND(db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "I%")))<br />
</syntaxhighlight><br />
<br />
The db:OR operation only takes two arguments, and will check to see if either of the two is true. You can nest these logical operators as deeply as you need to.<br />
<br />
You can also just pass in a string directly to db:fetch, but you have to be very careful as this will be passed straight to the SQL layer. If you don’t know any SQL then you want to avoid this… for example, in SQL there’s a very big difference between double and single quotes. If you don’t know that, then stick to the db functions. But an example is:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, "city == 'Magnagora'")<br />
</syntaxhighlight><br />
<br />
Now, the return value of db:fetch() is always a table array that contains a table dictionary representing the full contents of all matching rows in the sheet. These are standard Lua tables, and you can perform all normal Lua operations on them. For example, to find out how many total items are contained in your results, you can simply do #results. If a request from the friends sheet were to return one row that you stored in the results variable, it would look like this if passed into the display() function:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'name': 'Bob',<br />
'city': 'Magnagora',<br />
'notes': 'Trademaster of Tailoring'<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
And if you were to echo(#results), it would show 1.<br />
<br />
The order of the returned rows from db:fetch is generally the same as the order in which you entered them into the database, but no actual guarantees are made to this. If you care about the order then you can pass one or two optional parameters after the query to db:fetch() to control this.<br />
<br />
The first table is an array of fields that indicate the column names to sort by; the second is a flag to switch from the default ascending(smallest to largest) sort, to a descending(largest to smallest) sort. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city})<br />
</syntaxhighlight><br />
<br />
This will return all your friends in Magnagora, sorted by their name, from smallest to largest. To reverse this, you would simply do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city}, true)<br />
</syntaxhighlight><br />
<br />
Including more then one field in the array will indicate that in the case that two rows have the same value, the second field should be used to sort them.<br />
<br />
If you would like to return ALL rows from a sheet, but still sort them, you can do that by passing nil into the query portion. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, nil, {mydb.friends.city, mydb.friends.name})<br />
</syntaxhighlight><br />
<br />
This will return every friend you have, sorted first by city and then their name.<br />
<br />
==Indexes and Types==<br />
<br />
The sheets we’ve defined thus far are very simple, but you can take more control over the process if you need to. For example, you may assign default values and types to columns, and the DB package will attempt to coerce them as appropriate. To do that, you change your db:create() call as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
This is almost the same as the original definition, but we’ve defined that our first four fields are strings with a default value of blank, and the new kills field which is an integer that starts off at 0. The only way to set a datatype is to set a default value at this time.<br />
<br />
Please note, beneath the DB package is SQLite, and SQLite is very data-type neutral. It doesn’t really care very much if you break those rules and put an integer in a string field or vice-versa, but the DB package will — to a limited degree — attempt to convert as appropriate, especially for the operations that work on numbers.<br />
<br />
You may also create both standard and unique indexes. A unique index enforces that a certain criteria can only happen once in the sheet. Now, before you go and make indexes, pause and consider. There is no right or wrong answer when it comes to what to index: it depends on what kind of queries you do regularly. If in doubt, don’t make an index. Indexes will speed up reading data from the sheet, but they will slow down writing data.<br />
<br />
To add an index, pass either the _index or _unique keys in the table definition. An example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" }<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Now, bear in mind: _index = { "name", "city"} creates two indexes in this sheet. One on the city field, one on the name field. But, _index = { {"name", "city"} } creates one index: on the combination of the two. Compound indexes help speed up queries which frequently scan two fields together, but don’t help if you scan one or the other.<br />
<br />
The admonition against making indexes willy-nilly holds double for compound indexes: do it only if you really need to!<br />
<br />
===Uniqueness===<br />
<br />
As was specified, the _unique key can be used to create a unique index. This will make it so a table can only have one record which fulfills that index. If you use an index such as _unique = { "name" } then names must be unique in the sheet. You can specify more than one key to be unique; in that case they will be checked in an OR condition.<br />
<br />
Now, if you use db:add() to insert a record which would violate the unique constraint, a hard error will be thrown which will stop your script. Sometimes that level of protection is too much, and in that case you can specify how the db layer handles violations.<br />
<br />
There are three possible ways in which the layer can handle such violations; the default is to FAIL and error out.<br />
<br />
You can also specify that the db layer should IGNORE any commands that would cause the unique constraint to be violated, or the new data should REPLACE the existing row.<br />
<br />
For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento"})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the name field being declared to be unique, these two commands can’t succeed normally. The first db:add() will create a record with the name of Bob, and the second would cause the uniqueness of the name field to be violated. With the default behavior (FAIL), the second db:add() call will raise an error and halt the script.<br />
<br />
If you want the IGNORE behavior, the second command will not cause any errors and it will simply fail silently. Bob’s city will still be Sacramento.<br />
<br />
With the REPLACE behavior, the second command will cause its data to completely overwrite and replace the first record. Bob’s city will now be San Francisco.<br />
<br />
A word of caution with REPLACE, given:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento", notes="This is something."})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the REPLACE behavior, the second record will overwrite the first-- but the second record does not have the notes field set. So Bob will now not have any notes. It doesn’t -just- replace existing fields with new ones, it replaces the entire record.<br />
<br />
To specify which behavior the db layer should use, add a _violations key to the table definition:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" },<br />
_violations = "IGNORE"<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Note that the _violations behavior is sheet-specific.<br />
<br />
===Timestamps===<br />
<br />
In addition to strings and floats, the db module also has basic support for timestamps. In the database itself this is recorded as an integer (seconds since 1970) called an epoch, but you can easily convert them to strings for display, or even time tables to use with Lua’s built-in time support.<br />
<br />
The most common use for the Timestamp type is where you want the database to automatically record the current time whenever you insert a new row into a sheet. The following example illustrates that:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:create("combat_log",<br />
{<br />
kills = {<br />
name = "",<br />
area = "",<br />
killed = db:Timestamp("CURRENT_TIMESTAMP"),<br />
_index = { {"name", "killed"} }<br />
}<br />
}<br />
)<br />
<br />
-- observe that we don't provide the killed field here - DB automatically fills it in for us.<br />
db:add(mydb.kills, {name="Drow", area="Undervault"})<br />
<br />
results = db:fetch(mydb.kills)<br />
display(results)<br />
</syntaxhighlight><br />
<br />
The result of that final display would show you this on a newly created sheet:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'_row_id': 1<br />
'area': 'Undervault'<br />
'name': 'Drow'<br />
'killed': table {<br />
'_timestamp': 1264317670<br />
}<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
As you can see from this output, the killed fields contains a timestamp-- and that timestamp is stored as an epoch value in the GMT timezone. For your convenience, the db.Timestamp type offers three functions to get the value of the timestamp in easy formats. They are <code>as_string</code>, <code>as_number</code> and <code>as_table</code>, and are called on the timestamp value itself.<br />
<br />
The as_number function returns the epoch number, and the as_table function returns a time table. The as_string function returns a string representation of the timestamp, with a default format of "%m-%d-%Y %H:%M:%S". You can override this format to anything you would like. Details of what you can do with epoch values, time tables, and what format codes you can use are specified in the Lua manual at: http://www.lua.org/pil/22.1.html for the Lua date/time functions.<br />
<br />
A quick example of the usage of these functions is:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.kills)<br />
for _, row in ipairs(results) do<br />
echo("You killed " .. row.name .. " at: " .. (row.killed and row.killed:as_string() or "no time") .."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==Deleting==<br />
<br />
The db:delete function is used to delete rows from the sheet. It takes two arguments, the first being the sheet you are deleting and the second a query string built using the same functions used to build db:fetch() queries.<br />
<br />
For example, to delete all your enemies in the city of Magnagora, you would do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these! You may inadvertantly wipe out huge chunks of your sheets if you don’t have the query parameters set just to what you need them to be. Its advised that you first run a db:fetch() with those parameters to test out the results they return.<br />
<br />
As a convenience, you may also pass in a result table that was previously retrieved via db:fetch and it will delete only that record from the table. For example, the following will get all of the enemies in Magnagora, and then delete the first one:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
db:delete(mydb.enemies, db:eq(mydb.enemies._row_id, results[1]._row_id))<br />
</syntaxhighlight><br />
<br />
That is equivalent to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
You can even pass a number directly to db:delete if you know what _row_id you want to purge.<br />
<br />
A final note of caution: if you want to delete all the records in a sheet, you can do so by only passing in the table reference. To try to protect you from doing this inadvertently, you must also pass true as the query after:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, true)<br />
</syntaxhighlight><br />
<br />
==Updating==<br />
<br />
If you make a change to a table that you have received via db:fetch(), you can save those changes back to the database by doing:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:update(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
A more powerful (and somewhat dangerous, be careful!) function to make changes to the database is db:set, which is capable of making sweeping changes to a column in every row of a sheet. Beware, if you have previously obtained a table from db:fetch, that table will NOT represent this change.<br />
<br />
The db:set() function takes two arguments: the field to change, the value to set it to, and the db:fetch() like query to indicate which rows should be affected. If you pass true as the last argument, ALL rows will be changed.<br />
<br />
To clear out the notes of all of our friends in Magnagora, we could do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:set(mydb.friends.notes, "", db:eq(mydb.friends.notes, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these!<br />
<br />
==Transactions==<br />
<br />
As was specified earlier, by default the db module commits everything immediately whenever you make a change. For power-users, if you would like to control transactions yourself, the following functions are provided on your database instance:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("my_database")<br />
mydb:_begin()<br />
mydb:_commit()<br />
mydb:_rollback()<br />
mydb:_end()<br />
</syntaxhighlight><br />
<br />
Once you issue a mydb._begin() command, autocommit mode will be turned off and stay off until you do a mydb._end(). Thus, if you want to always use transactions explicitly, just put a mydb._begin() right after your db:create() and that database will always be in manual commit mode.<br />
<br />
==Viewing and editing the database contents==<br />
<br />
A good tool to view and edit the database contents in raw form is [http://afoucal.free.fr/index.php/applications/sqlite-sorcerer/ SQlite Sorcerer] (free and available for Linux, Windows, Mac).<br />
<br />
==Debugging raw queries==<br />
<br />
If you'd like to see the queries that db: is running for you, you can enable debug mode with ''db.debug_sql = true''.<br />
<br />
=Discord Messages=<br />
<br />
Can you send messages from Mudlet to Discord? Totally. Here is an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
function sendToDiscord(data)<br />
local url = "https://discord.com/api/webhooks/1204151397977821184/Cu8ZQQo9R11AyIt3DxpOEeB8MtVMA6_AEfXoZaYxqEAOu_6hwhtA2cRLIw-VIs7py7p8"<br />
local headers = {["Content-Type"] = "application/json"}<br />
local json = yajl.to_string(data)<br />
postHTTP(json, url, headers)<br />
end<br />
<br />
local data = {<br />
content = "Hello, Discord!",<br />
embeds = {<br />
{<br />
title = "This is an embed",<br />
url = "https://example.com",<br />
image = {<br />
url = "https://example.com/image.jpg"<br />
}<br />
}<br />
}<br />
}<br />
<br />
sendToDiscord(data)<br />
<br />
</syntaxhighlight><br />
<br />
Sure enough, after starting this script, you can see a message in Discord:<br />
<br />
[[File:Message to Discord.png|border|center]]<br />
<br />
What you just need to do is create a webhook in a channel. Go to channel settings, then create this:<br />
<br />
[[File:Webhook in Discord.png|border|center]]<br />
<br />
Here you can find more documentation on which fields Discord allows: https://discord.com/developers/docs/resources/webhook#execute-webhook<br />
<br />
All this is one way though. Mudlet won't listen to messages from Discord. For that you'd probably have to make a Discord bot first.<br />
<br />
=Discord Rich Presence=<br />
[[File:Rich_Presence_Midmud.gif|frame]]<br />
<!-- [[File:Rich Presence Achaea.gif|frame]] --><br />
<br />
Discord Rich Presence in Mudlet allows you, the player, to show off the game you're playing and you, the game author, to get your game shown off! Advertise your game for free alongside AAA titles in server player lists :)<br />
<br />
To respect the players privacy, this option is disabled by default - enable it by ticking the Discord option for the profile:<br />
<br />
[[File:Enable Discord.png|border|center]]<br />
<br />
Once enabled, a Discord-capable game will show information in your Discord!<br />
<br />
To fine-tune the information you'd like to see displayed, go to Settings, Chat tab:<br />
<br />
[[File:Discord Privacy.png|center|400px]]<br />
<br />
== Implementing ==<br />
As a game author, you have two ways of adding Discord support to your game: via GMCP (easy) or via Lua.<br />
<br />
Adding support via GMCP means that your players don't have to install any Lua scripts which is a nicer experience. To do so, implement the [[Standards:Discord_GMCP|Discord over GMCP]] specification and [https://www.mudlet.org/contact/ get in touch] to let us know your game implements GMCP.<br />
<br />
=== GMCP ===<br />
Here's a quick cheatsheet to implement the [[Standards:Discord_GMCP|GMCP spec]]:<br />
<br />
# Create a discord [https://discordapp.com/developers/applications/me application]<br />
# Upload game logo for "rich presence invite image"<br />
# Upload same game logo in "Rich Presence Assets" with the name of <code>server-icon</code><br />
# Upon receiving "External.Discord.Hello" from the game client, reply with "External.Discord.Info" with <code>applicationid</code> ([[:File:Mudlet Discord ApplicationID.png|see screenshot]]) and "External.Discord.Status" <br />
# Send "External.Discord.Status" whenever you need to send data to the client, and fill it with the values have changed since the last status. Discord has [https://discordapp.com/developers/docs/rich-presence/best-practices#tips some ideas] for filling it in.<br />
# Done. Mudlet will enable the Discord checkbox upon receiving the <code>applicationid</code> from the game at least once.<br />
<br />
=== Lua ===<br />
An alternative way to add Discord support as a game author is [[Manual:Discord_Functions|via Lua]] - all of Discords functionality can be manipulated from it. Create a discord [https://discordapp.com/developers/applications/me application] and set it with [[Manual:Discord_Functions#setDiscordApplicationID|setDiscordApplicationID()]], then set the set the rest of the options as necessary:<br />
<br />
[[File:Discord fields.png|frame|center|Credit: Discord]]<br />
<br />
If you're a game player and your game doesn't support Discord, you can still use the functionality to set the detail, status, party and time information as desired.<br />
<br />
{{MudletVersion|3.14}}<br />
<br />
=MUD Client Media Protocol=<br />
<br />
==Client.Media==<br />
Want to add accessibility and excitement into your game? How about implementing sound and music via GMCP?<br />
<br />
The Client.Media family of GMCP packages provide a way for games to send sound and music events. GMCP media events are sent in one direction: from game server to to game client.<br />
<br />
===Client.Media in Mudlet===<br />
<br />
Media files may be downloaded manually or automatically if certain conditions are met.<br />
<br />
{{MudletVersion|4.4}}<br />
<br />
Mudlet accepts case-insensitive GMCP for the Client.Media namespace (for example, these are all acceptable: "Client.Media.Play", "client.media.play", "cLiEnT.MeDiA.Play").<br />
<br />
===Enabling Media===<br />
When a new profile opens, Mudlet adds to the Core.Supports.Set GMCP package "Client.Media 1" to signal to servers that it supports processing media files via GMCP:<br />
<br />
<syntaxhighlight lang="json"><br />
Core.Supports.Set ["Client.Media 1", ...]<br />
</syntaxhighlight><br />
<br />
To process Client.Media GMCP data in Mudlet, these boxes in the Settings window of Mudlet must be checked:<br />
<br />
# The "Enable GMCP" box in the Miscellaneous section.<br />
# The "Allow server to download and play media" box in the Game protocols section.<br />
<br />
These boxes are checked by default upon the start of a new profile in Mudlet.<br />
<br />
===Storing Media===<br />
<br />
Mudlet plays files cached in the "media" folder within a game's profile. To get files into the "media" folder you could perform either of these options:<br />
<br />
# Copy media files or extract them from an archive (zip)<br />
# Automatically download them from external resources such as your game's web server on the Internet.<br />
<br />
To enable the second option (Internet), use the "url" parameter made available in the "Client.Media.Default", "Client.Media.Load" and "Client.Media.Play" GMCP packages described below.<br />
<br />
===Loading Media===<br />
<br />
Send a '''Client.Media.Default''' GMCP event to setup the default URL directory to load sound or music files from external resources. This would typically be done once upon player login. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
|-<br />
|}<br />
<br />
For example, to setup the default URL directory for your game:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Default {<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
If downloading from external resources, it is recommended to use Client.Media.Default, set this default URL directory once, and let Mudlet download all of your media files automatically from this one resource location. Otherwise, explicitly set the "url" parameter on all of your Client.Media.Load GMCP and Client.Media.Play GMCP events to ensure that files are downloaded from the intended location(s).<br />
<br />
Send '''Client.Media.Load''' GMCP events to load sound or music files. This could be done when the player logs into your game or at the beginning of a zone that will need the media.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if a url was not set above with Client.Media.Default.<br />
|-<br />
|}<br />
<br />
For example, download the sound of a sword swooshing within the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Load {<br />
"name": "sword1.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
===Playing Media===<br />
<br />
Send '''Client.Media.Play''' GMCP events to play sound or music files.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely and a url was not set above with Client.Media.Default or Client.Media.Load.<br />
|-<br />
| style="text-align:center;"| No<br />
| "type"<br />
| "sound" or "music"<br />
| "sound"<br />
| style="text-align:left;"|<br />
* Identifies the type of media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "tag"<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "volume"<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| "fadein"<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"fadeout"<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| "start"<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
* 1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"loops"<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the sound or music to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a lower priority while this media plays.<br />
|-<br />
| style="text-align:center;" |No<br />
|"continue"<br />
| true or false<br />
|true<br />
| style="text-align:left;" |<br />
*Only valid for media files with a "type" of "music".<br />
*Continues playing matching new music files when true.<br />
*Restarts matching new music files when false.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
|}<br />
<br />
==== name====<br />
<br />
For example, to simply play the sound of a cow mooing already stored in the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Or some lightning stored in a "weather" sub-folder under the "media" folder.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "weather/lightning.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
The "name" parameter may be used for stopping media with the Client.Media.Stop GMCP event.<br />
<br />
====url====<br />
<br />
If you maintain your sound files on the Internet and don't set a default URL with Client.Media.Default, or preload them with Client.Media.Load, include the "url" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
====type: sound====<br />
<br />
Media files default to a "type" of "sound" when the "type" parameter is not specified, such as in the example above. It is good practice to specify the "type" parameter to best keep media organized within your implementation:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====tag====<br />
<br />
To play the sound of a sword swooshing and categorized as "combat":<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat"<br />
}<br />
</syntaxhighlight><br />
<br />
The "tag" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====type: music====<br />
<br />
Add background music to your environment through use of the "music" value set upon the "type" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====volume: 1 to 100====<br />
<br />
As the character draws nearer to or farther from the environmental feature, consider adjusting the "volume" parameter. Example values, followed by syntax examples:<br />
<br />
*Maximum: 100 (recommended to use rarely)<br />
*High: 75<br />
*Default: 50<br />
* Low: 25<br />
* Minimum: 1 (recommended to use rarely)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment",<br />
"volume": 75<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "volume" values of type string ("75") into integers (75) as needed.<br />
<br />
====fadein====<br />
<br />
Increase volume from the start of the media [start position, volume one] to the number in milliseconds specified with the "fadein" parameter [position start + milliseconds, volume specified with the "volume" parameter]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade in)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "monty_python.mp3",<br />
"type": "music",<br />
"volume": 100,<br />
"fadein": 1000<br />
}<br />
</syntaxhighlight><br />
+---------------------------+-----------------------+<br />
| Fade in 1000 milliseconds | Normal |<br />
+---------------------------+-----------------------+<br />
Volume 1|........::::::::::iiiiiiiii%%%%%%%%%%%%%%%%%%%%%%%%|Volume 100<br />
+---------------------------+-----------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadein" values of type string ("1000") into integers (1000) as needed.<br />
<br />
==== fadeout====<br />
<br />
Decrease volume from a position in milliseconds subtracted from the duration of the media [position duration - milliseconds, volume specified with the "volume" parameter] to the end of the media [position duration, volume one]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade out)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "the_matrix.mp3",<br />
"type": "music",<br />
"volume": 50,<br />
"fadeout": 333<br />
}<br />
</syntaxhighlight><br />
+-----------------------+---------------------------+<br />
| Normal | Fade out 333 milliseconds |<br />
+-----------------------+---------------------------+<br />
Volume 50|%%%%%%%%%%%%%%%%%%%%%%%%iiiiiiiii::::::::::........|Volume 1<br />
+-----------------------+---------------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadeout" values of type string ("333") into integers (333) as needed.<br />
<br />
==== start ====<br />
<br />
Start playing a media track at the number of milliseconds specified. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (start from beginning)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "mudlet_beatboxing.mp3",<br />
"type": "music",<br />
"volume": 75,<br />
"start": 1000<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "start" values of type string ("100") into integers (100) as needed.<br />
<br />
==== loops: -1, 1 or more ====<br />
<br />
The "loops" parameter controls how many times the sound repeats and defaults to 1 if not specified. A value of -1 will loop the file indefinitely.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "clock/hour_bell.wav",<br />
"type": "sound",<br />
"loops": 3<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "underdark.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "loops" values of type string ("-1") into integers (-1) as needed.<br />
<br />
==== priority: 1 to 100 ====<br />
<br />
The "priority" parameter sets precedence for Client.Media.Play GMCP events that include a "priority" setting. The values for the "priority" parameter range between 1 and 100. Given that two Client.Media.Play GMCP events have the same priority, the media already playing will continue playing. In Mudlet, media without priority set is not included comparisons based on priority.<br />
<br />
A common place to find priority implemented is with combat. In the following example, imagine a combat scenario where some sounds of sword thrusts were interrupted by a successful blocking maneuver.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3,<br />
"priority": 60<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "block1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"priority": 70<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "priority" values of type string ("25") into integers (25) as needed.<br />
<br />
The "priority" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====continue: true or false (for music)====<br />
<br />
Typically sent with the "type" of "music" is the parameter "continue", which presents the following values:<br />
<br />
*true: continues music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
*false: restarts music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "city.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"continue": true<br />
}<br />
</syntaxhighlight><br />
<br />
If the "continue" parameter is not specified, behavior will default to ''true'' for music.<br />
<br />
Although using the boolean type is recommended, Mudlet parses "continue" values of type string ("true" and "false") into boolean (''true'' and ''false'') as needed, as not all game drivers support a boolean type.<br />
<br />
==== key====<br />
<br />
The "key" parameter enables media categorization, similar to the "tag" parameter, however it adds a feature of uniqueness that halts media currently playing with the same key, replacing it with the media that arrived from a new Client.Media.Play GMCP event. This update will only occur if the "name" or "url" associated with the currently playing media does not match the new media, while the key is identical.<br />
<br />
In the example below, consider that a player moves from a sewer area to a village. The "key" parameter is used to stop the previously playing ''sewer.mp3'' and start playing ''village.mp3'' within the second Client.Media.Play GMCP event. <br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sewer.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "village.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
The "key" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
{{note}} Where music is bound to change, continue or stop as a player enters a new room, consider allowing for a slight pause of 1 heart beat or tick to send the Client.Media.Play or Client.Media.Stop GMCP events. This practice reduces the number of Client.Media.Play GMCP events sent when the player travels through several rooms quickly.<br />
<br />
==== randomization====<br />
<br />
Wildcards ''*'' (asterisk) and ''?'' (question mark) may be used within the name to randomize media file(s) selection.<br />
<br />
Given that media files underdark.wav, underdark.mp3 and underdark_dark_elven_moshpit.mp3 were all present in the media/environment directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play using the ''*'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "underdark*",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": false<br />
}<br />
</syntaxhighlight><br />
<br />
If media files sword1.wav, sword2.wav and sword3.wav were all present in the media/combat directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play per each loop using the ''?'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "combat/sword?.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3<br />
}<br />
</syntaxhighlight><br />
<br />
=== Stopping Media ===<br />
<br />
Send '''Client.Media.Stop''' GMCP events to stop sound or music media.<br />
<br />
{| class="wikitable"<br />
!Required<br />
!Key<br />
!Value<br />
! style="text-align:left;" |Purpose<br />
|-<br />
| style="text-align:center;" | No<br />
| "name"<br />
|<file name><br />
| style="text-align:left;" |<br />
*Stops playing media by name matching the value specified.<br />
|-<br />
| style="text-align:center;" | No<br />
|"type"<br />
|"sound" or "music"<br />
| style="text-align:left;" | <br />
*Stops playing media by type matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
| "tag"<br />
|<tag><br />
| style="text-align:left;" |<br />
*Stops playing media by tag matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
| style="text-align:left;" |<br />
*Stops playing media with priority less than or equal to the value.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
| style="text-align:left;" | <br />
*Stops playing media by key matching the value specified.<br />
|-<br />
|}<br />
<br />
====all====<br />
<br />
Send the Client.Media.Stop GMCP event with no parameters to stop all playing media within a given game profile.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {}<br />
</syntaxhighlight><br />
<br />
====parameters====<br />
<br />
Send any combination of the name, type, tag, priority or sound parameters and valid corresponding values to stop playing media that matches ''all'' combinations of the parameters.<br />
<br />
Stop the rain.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"name": "rain.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media using the "type" of "sound".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "tag" of "combat" ''and'' that has a "priority" less than or equal to 50.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"tag": "combat",<br />
"priority": 50<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "key" of "area-music".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
=GUI Scripting in Mudlet=<br />
Mudlet has extremely powerful GUI capabilities built into it, and with the inclusion of the Geyser and Vyzors layout managers in Mudlet's Lua API it is quicker and easier to get a basic UI created.<br />
<br />
==Geyser==<br />
Geyser is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
Geyser's manual is quite extensive - [[Manual:Geyser|follow here]] to read up on it.<br />
<br />
===UI template===<br />
Akaya has created a UI template based on Geyser that can serve as a quick start for customizing the Mudlet interface to your character:<br />
<br />
[[File:Geyser UI template.png|center|800px|border]]<br />
<br />
To get started with it, see the forum thread about [http://forums.mudlet.org/viewtopic.php?f=6&t=4098 Geyser UI Template].<br />
<br />
==Simple Window Manager==<br />
Simple Window Manager is a light-weight script designed to provide the GUI object placement and sizing functionality seen in Geyser and Vyzor without any of the extras. Any GUI object, once created normally, can be added to the SWM along with a corner to base its positioning info off of, the distance from that corner, and the size of the object in any combination of pixels and percentages of the screen. SWM does all the behind the scenes work to keep all objects it has been given to manage in their correct places and sizes as the screen changes size. All other interactions with GUI objects are handled using standard functions built into Mudlet.<br />
<br />
Simple Window Managers manual, and download, can be [http://forums.mudlet.org/viewtopic.php?f=6&t=3529 found here].<br />
<br />
==Useful Resources==<br />
There are several useful resources you can refer to when creating your GUI.<br />
<br /><br />
<br />
;Wiki Resources<br />
*[[Manual:Geyser|Geyser Tutorial]]:<br />
:Excellent for getting an initial feel of how to use the Geyser layout manager.<br />
*[[Manual:Lua_Functions#UI_Functions|GUI API]]:<br />
:The GUI section of the Lua API manual<br />
;External Resources<br />
*[http://forums.mudlet.org/viewforum.php?f=11 Geyser subforum]:<br />
:The Geyser Layout Manager subforum on Mudlet's forums.<br />
*[http://forums.mudlet.org/viewtopic.php?f=5&t=1376 GUI Screenshots]:<br />
:A pinned thread on Mudlet's forums for showing what your GUI looks like. Useful for ideas and to see what is possible.<br />
*[http://forums.mudlet.org/viewtopic.php?f=9&t=1974 Godwars II Mudlet UI]:<br />
:A forum thread which follows the evolution of the UI provided by [http://www.godwars2.org God Wars II]<br />
[[Category:Mudlet Manual]]<br />
<br />
==Resetting your UI==<br />
While scripting your UI, you can reset it completely and have your scripts be loaded from scratch with the [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] function - in the input line, type <code>lua resetProfile()</code>.</div>Kebaphttps://wiki.mudlet.org/index.php?title=File:Webhook_in_Discord.png&diff=20907File:Webhook in Discord.png2024-02-05T21:00:30Z<p>Kebap: Discord channel settings, tab "Integrations", a new webhook was added: name is "Mudlet Test", channel is "#mudlet-testing"</p>
<hr />
<div>== Summary ==<br />
Discord channel settings, tab "Integrations", a new webhook was added: name is "Mudlet Test", channel is "#mudlet-testing"</div>Kebaphttps://wiki.mudlet.org/index.php?title=File:Message_to_Discord.png&diff=20906File:Message to Discord.png2024-02-05T20:58:50Z<p>Kebap: A message "Hello, Discord" from a user called "Mudlet Test" (marked as "Bot"), including a link* reading "This is an embed".
*: Not visible in picture, the link goes to https://example.com</p>
<hr />
<div>== Summary ==<br />
A message "Hello, Discord" from a user called "Mudlet Test" (marked as "Bot"), including a link* reading "This is an embed".<br />
<br />
*: Not visible in picture, the link goes to https://example.com</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Scripting&diff=20905Manual:Scripting2024-02-05T20:56:55Z<p>Kebap: /* Discord Messenges */ Add pictures to illustrate details</p>
<hr />
<div>{{TOC right}}<br />
=Scripting with Mudlet=<br />
<br />
Lua tables can basically be considered multidimensional arrays and dictionaries at the same time. If we have the table matches, matches[2] is the first element, matches[n+1] the n-th element.<br />
<br />
<syntaxhighlight lang="lua"><br />
a = "Tom"<br />
matches[2] = "Betty"<br />
b = matches[2]<br />
c = a .. b and e will equal "TomBetty"<br />
</syntaxhighlight><br />
<br />
To output a table you can use a convenience function - ''display(mytable)'', which is built into Mudlet.<br />
<br />
==Lua interface functions - triggers, timers etc.==<br />
<br />
How to get data from regex capture groups? Regular expression capture groups (e.g. "(\d+)" ) are passed on to Lua scripts as a Lua table matches. To make use of this information inside Lua scripts, you need to specify the number of the capture group within the regex.<br />
<br />
<code>Example: You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
This regex contains 3 capture groups, but only the 2 green colored ones contain data as the red capture group is a non-capturing group. Consequently, your Lua script gets passed only 2 instead of 3 capture groups and matches[4] is undefined.<br />
<br />
In your Lua script you may write following program in order to print the number and status of your weapons on the screen:<br />
<br />
<code>You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
<syntaxhighlight lang="lua"><br />
number_of_weapons = matches[2]<br />
status_of_weapons = matches[3]<br />
notice = number_of_weapons .. status_of_weapons<br />
echo( notice )<br />
send( "put weapons in backpack" )<br />
<br />
-- the following 2 lines color the first capture<br />
-- group red and the second group blue<br />
-- see below for details<br />
<br />
selectCaptureGroup( 2 )<br />
setFgColor( 255,0,0 )<br />
<br />
selectCaptureGroup( 3 )<br />
setFgColor( 0,0,255 )</syntaxhighlight><br />
<br />
The best way is to use selectCaptureGroup( number ) to select the proper capture group and then perform your actions on it e.g. replace(), highlight etc. Note: Both selectCaptureGroup() and matches[n] start with group 1 (which is the whole match. The defined capture groups start with 2).<br />
<br />
How to select all occurrences of "Tom" and highlight them?<br />
<br />
You add a function like this to a script containing you main function definitions. Note that script items differ from all other "scripts" in triggers, timers, actions etc. because they require you to put your code in proper functions that can be called by your other trigger-scripts, timer-scripts etc. via normal function calls. Trigger-scripts, timer-scripts etc. cannot contain any function definitions because they are automatically generated functions themselves because this makes usage a lot easier.<br />
<br />
To come back to our question how to select all occurrences of "Tom" and highlight them:<br />
<br />
<syntaxhighlight lang="lua"><br />
function setBgColorAll( word, r, g, b )<br />
i = 0<br />
word_count = 1<br />
while i > -1 do<br />
i = selectString(word, word_count)<br />
if i == -1 then<br />
return<br />
end<br />
word_count = word_count +1<br />
setBgColor( r, g, b )<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
Then you simply define a substring matching trigger on the word "Tom" and in the trigger script you call above function:<br />
<br />
<syntaxhighlight lang="lua">setBgColorAll("Tom", 255,50,50)</syntaxhighlight><br />
<br />
Since Mudlet 4.11+ it is possible to use name capture groups. You can verify if feature availability by checking <code>mudlet.supports.namedPatterns</code> flag.<br />
Let's say you have multiple patterns that you want to handle with one code.<br />
<br />
<code>^My name is (?<name>\w+)\. My class is (?<class>\w+)\.</code><br />
<br />
<code>^I am (?<class\w+)\ and my name is (?<name>\w+)\.</code><br />
<br />
Notice that class and name come in different order, therefore in first case we will have name under <code>matches[2]</code> and in second case under <code>matches[3]</code>.<br />
With named capture groups in both cases we will have name available under <code>matches.name</code> and class under <code>matches.class</code>.<br />
<br />
Code example to handle named matches above:<br />
<syntaxhighlight lang="lua"><br />
echo("Name: " .. matches.name .. "\n")<br />
echo("Class: " .. matches.class .. "\n")<br />
</syntaxhighlight><br />
<br />
==Sending commands or printing information messages==<br />
<br />
To print information messages on the session screen you can use the echo( message ) function, or insertText( text ). Currently, it only takes one string as argument.<br />
<br />
To send a command to the MUD, you can use the send( command ) function. In Alias scripts the command that is being sent to the MUD is contained in the variable command that you can change in the context of Alias scripts. Alias take regular expressions, as well. As a result, you can use following regex and script to talk like Yoda: Perl regex:<br />
<br />
<code> say (\w+).*(\w*).*(.*) </code><br />
<br />
script:<br />
<br />
<syntaxhighlight lang="lua"><br />
send( "say " .. matches[4] .." " .. matches[2] .." ".. matches[3] )<br />
</syntaxhighlight><br />
<br />
Note: The variable "command" contains what was entered in the command line or issued via the expandAlias( ) function. If you use expandAlias( command ) inside an alias script the command would be doubled. You have to use send( ) inside an alias script to prevent recursion. This will send the data directly and bypass the alias expansion.<br />
<br />
===Changing and formatting text from the MUD===<br />
<br />
When sending commands to the MUD - from now on referred to as output stream - alias scripts find the command that was issued by the user stored in the variable "command".<br />
<br />
By manipulating the value, the command can easily be changed before it is being sent to the MUD.<br />
<br />
However, things get much more complicated with the data received from the MUD, from now on referred to as input stream. Before triggers can be run on the MUD data, Mudlet has to strip all format codes from the text and store it in data structures associated with the text. Consequently, the text that is being passed on to the trigger processing unit is a small subset of the data received from the MUD. If you want to edit, replace, delete or reformat text from within your trigger scripts you have to keep this in mind if you don’t want to lose all text format information such as colors etc.<br />
<br />
As the text is linked with data structures containing the format of the text, the cursor position inside the line is important if data is being changed. You select a word or a sequence of characters from the line and then issue commands to do actions on the selected data.<br />
<br />
Replacing the word "Tom" with "Betty" in the line: Jim, Tom and Lucy are learning a new spell. This could be done with following script:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Tom",1)<br />
replace("Betty")<br />
</syntaxhighlight><br />
<br />
Things get more complicated if there are two or more occurrences of "Tom" in the line e.g. Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
The above example code would select the first occurrence of "Tom" in this line and ignore the second. If you want to work on the the second occurrence of "Tom" you have to specify the occurrence number in the call to select().<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString( "Tom", 2 )<br />
replace( "Betty" )<br />
</syntaxhighlight><br />
<br />
This code would change the second "Tom" and leave the first "Tom" alone. The function call<br />
<br />
<syntaxhighlight lang="lua">replaceAll( "Betty" )</syntaxhighlight><br />
<br />
will replace all occurrences of "Tom" with "Betty" in the line if "Tom" has been selected before. replaceAll() is a convenience function defined in LuaGlobal.lua.<br />
<br />
Colorization example: You want to change to color of the words "ugly monster" to red on a white background.<br />
<br />
You add a new trigger and define the regex: ugly monster In the script you write:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("ugly monster", 1 )<br />
setFgColor(255,0,0)<br />
setBgColor(255,255,255)<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
Another means to select text is to select a range of characters by specifying cursor positions. If we have following line: Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
<syntaxhighlight lang="lua">selectSection( 28, 3 )</syntaxhighlight><br />
<br />
This example would select the second Tom. The first argument to selectSection is the cursor position within the line and the second argument is the length of the selection.<br />
<br />
<syntaxhighlight lang="lua">selectCaptureGroup( number )</syntaxhighlight><br />
<br />
This function selects the captureGroup number if you use Perl regular expressions containing capture groups. The first capture group starts with index 1.<br />
<br />
==Deleting Text - Gagging==<br />
<br />
<syntaxhighlight lang="lua">deleteLine()</syntaxhighlight><br />
<br />
This function deletes the current line - or any line where the cursor is currently placed. You can use repeated calls to this function to effectively erase the entire text buffer. If you want to delete or gag certain words only, you can select the text that you want to delete and then replace it with an empty string e.g:<br />
<br />
If you get this line form the MUD: "Mary and Tom walk to the diner."<br />
<br />
<syntaxhighlight lang="lua">selectString( "Tom", 1 )<br />
replace( "" )</syntaxhighlight><br />
<br />
Then the output will be changed to: "Mary and walk to the diner."<br />
<br />
==Cursor Movement and Cursor Placement==<br />
Mudlet allows you to insert text arbitrarily within the buffer - in the previous line, in the previous ten lines, or even the first line that you've ever saw. These are the tools to help you with the job:<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( windowName, x, y )]]</code> This will move the user cursor of window windowName to the absolute (x/y) coordinates in the text.<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( "main", 20, 3950 )]]</code> will move the cursor on the 20th character from the left on line number 3950. To determine the current cursor position you can use getLineNumber() and getColumnNumber() as well as [[Manual:UI_Functions#getLastLineNumber|getLastLineNumber()]] to get the number of the last line in the text buffer. moveCursorEnd("main") will move the cursor of the main display to end of the buffer. This is always a new line of size 1 containing the character \n.<br />
<br />
<code>number_of_last_line_in_text = [[Manual:UI_Functions#getLineCount|getLineCount()]]</code> returns the number of the last line of the text in the console buffer. This number will change as soon as a new \n is printed either by the user or when a new line arrives from the MUD. All lines from the MUD are terminated with \n which is called line feed or the new line character. This control character ends the current line and move the cursor to the beginning of the next line, thus creating a new, empty line below the line that contains the \n.<br />
<br />
<code>line_number_of_the_current_cursor_position = [[Manual:UI_Functions#getLineNumber|getLineNumber()]]</code><br />
<br />
<code>column_number_of_the_current_cursor_position = [[Manual:UI_Functions#getColumnNumber|getColumnNumber()]]</code><br />
<br />
<code>luaTable_containing_textlines = [[Manual:UI_Functions#getLines|getLines( absolute_line_number_from, absolute_line_number_to )]]</code> this will return a Lua table containing all lines between the absolute positions from and to.<br />
<br />
{{note}} This function uses absolute line numbers, not relative ones like in [[Manual:UI_Functions#moveCursor|moveCursor()]].<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor()]]</code> returns true or false depending on whether the move was possible and done.<br />
<br />
=== Inserting text in the middle of the line ===<br />
Here's an example where we'll append the text ''(one)'' right after the word ''exit'' in the line of <code>You see a single exit leading west.</code><br />
<br />
[[File:Inserting text.png|center|650px]]<br />
<br />
The pattern we used was an ''exact match'' for <code>You see a single exit leading west.</code> and the code is:<br />
<br />
<syntaxhighlight lang="lua"><br />
if moveCursor(string.find(line, "exit")+#("exit")-1, getLineNumber()) then<br />
insertText("(one)")<br />
end<br />
</syntaxhighlight><br />
<br />
What happened here:<br />
* we triggered on the desired line using our pattern above<br />
* we used [[Manual:UI_Functions#moveCursor|moveCursor()]] to place the cursor in the desired position within the line. [[Manual:UI_Functions#moveCursor|moveCursor()]] takes both the line number and the position within the line to place our virtual cursor on, so<br />
** we used [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] to find the position of the word "exit" within the line<br />
** but [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] returns us the position of the first character of the word we want, while we want to have the text be right after it - so we find out how long our word is with <code>#("exit")</code>, add that to the number returned by [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] which gets us the first character + the length of the word - which isn't quite at the end of the word, but the word plus the space (because of [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] and the first character) - so we substract 1 to move our cursor right at the end of the word<br />
** we then use [[Manual:UI_Functions#getLineNumber|getLineNumber()]] to get the current line number, so our cursor is placed on the current line, at our desired position<br />
* lastly we finally insert the text with [[Manual:UI_Functions#insertText|insertText()]], which puts the text exactly where our virtual cursor is<br />
<br />
Done! You can also use [[Manual:UI_Functions#cinsertText|cinsertText()]] for coloured inserts, and other functions [[Manual:Scripting#Cursor_Movement_and_Cursor_Placement|mentioned above]] and in the [[Manual:UI_Functions|API manual]] to help you do what you'd like.<br />
<br />
==User defined dockable windows==<br />
<br />
You may want to use dock windows to display information you gathered in your scripts, or you may want to use them as chat windows etc. Check out [[Manual:Geyser#Geyser.UserWindow|Geyser.UserWindow]] on how to add them!<br />
<br />
==Dynamic Triggers==<br />
<br />
<code>triggerID = tempTrigger( substring pattern, code ) creates a fast substring matching trigger</code> <br />
<br />
<code>triggerID = tempRegexTrigger( regex, code ) creates a regular expression matching trigger</code><br />
<br />
<code>triggerID = tempBeginOfLineTrigger( begin of line pattern, code ) creates a fast begin of line substring trigger</code><br />
<br />
=Scripting howtos=<br />
==How to convert a string to value?==<br />
Say you'd like to capture a number from a trigger, but the capture always ends up being a "string" (or, just text on which you can't do any maths on) even if it's a number. To convert it to a number, you'd want to use the ''tonumber()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
myage = tonumber(matches[2])<br />
</syntaxhighlight><br />
<br />
==How to highlight my current target?==<br />
<br />
You can put the following script into your targetting alias:<br />
<br />
<syntaxhighlight lang="lua">if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
Where target is your target variable. Note that you have to use the full name, capitalized. If you’d like the script to auto-capitalize for you, you can use this version:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = target:title()<br />
if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
{{note}} Ensure you're on Mudlet 3.5.0+ so you can put ''function()'' in a ''[[Manual:Lua_Functions#tempTrigger|tempTrigger()]]''.<br />
<br />
==How to format an echo to a miniConsole?==<br />
<br />
One of the ways you can create multi-line displays in a miniConsole with variable information is with string.format and the use of [[ ]] brackets for text, which allow for multiple line in text:<br />
<br />
<syntaxhighlight lang="lua"><br />
local WindowWidth, WindowHeight = getMainWindowSize();<br />
createMiniConsole("sys",WindowWidth-650,0,650,300)<br />
<br />
local name, age, sex = "Bob", 34, "male"<br />
<br />
cecho("sys", string.format([[<br />
<br />
/---------\<br />
%s<br />
%dyrs<br />
sex - %s <br />
\---------/<br />
]], name, age, sex))<br />
</syntaxhighlight><br />
<br />
==How to play a sound when I receive communication while afk?==<br />
<br />
[[File:Play_sound_when_afk_trigger.png]]<br />
<br />
For this to work, place the line you'd like to trigger on in the first pattern box and select the appropriate pattern type. Then add ''return not hasFocus()'' with the Lua function as the second pattern, enable the AND trigger, and set the line delta to zero. Then just enable ''play sound'', choose your sound and you're set!<br />
<br />
==How can I make a key that toggles between commands?==<br />
To make a key that toggles between two actions, for example - sleep/wake, you can use this as the script:<br />
<br />
<syntaxhighlight lang="lua"><br />
if not sleeping then<br />
send("sleep")<br />
sleeping = true<br />
else<br />
send("wake")<br />
sleeping = false<br />
end<br />
</syntaxhighlight><br />
<br />
<!-- Old Heading: How can I make a trigger that goes off only if the next line is not a particular one? --><br />
==How can I make a trigger with a next-line condition?==<br />
<br />
Here's how you can set it up - replace ''line1'' and ''line2'' with appropriate lines.<br />
<br />
[[File:Trigger_multiline_not_another_example.png|center]]<br />
<br />
Here's [[Media:Match only of next line is *not* line2.xml.zip|the Mudlet XML]] you can download for this!<br />
<br />
==How to target self or something else?==<br />
<br />
[[File:Buffselforother.png|border|350px]]<br />
<br />
Using regex and an 'or' statement allows us to consolidate multiple aliases, or an if statement, into a single more simple alias. <br />
When a regex is found it will use it, but if you don't specify one then the alternative will be used. The use of 'or' can be used with any function in Mudlet.<br />
In this example, one can type "buff" to buff themself, or "buff ally" to buff their ally instead.<br />
<br />
<syntaxhighlight lang="lua"><br />
^buff(?: (\w+))?$<br />
<br />
send("cast buff on "..(matches[2] or "myself"))<br />
</syntaxhighlight><br />
<br />
==How to delete everything between two lines?==<br />
When deleteLine() is called, every following line shifts back in numerical position. Thus if we know where we're starting and how many lines to expect, we can use a for loop to gag everything between line a and b by leaving the cursor in one spot. In the below example, line_a_number is the number of the line you want to start at, and line_b_number is the ending line. To gag x number of lines instead, use line_a_number + x in place of line_b_number.<br />
<br />
<syntaxhighlight lang="lua"><br />
for i = line_a_number, line_b_number, 1<br />
do<br />
moveCursor(0, line_a_number)<br />
selectCurrentLine()<br />
deleteLine()<br />
end<br />
</syntaxhighlight><br />
<br />
== How to capture foreground line color information? ==<br />
Here's an example that loops through each character in a line of text and prints the character and its foreground color to a miniconsole if the color has changed from the previous character:<br />
<br />
Trigger: <code>^</code> (regex)<br />
<br />
Code:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer =<br />
miniconsoleContainer or Adjustable.Container:new({name = "miniconsoleContainer"})<br />
myMiniconsole =<br />
Geyser.MiniConsole:new(<br />
{<br />
name = "myMiniconsole",<br />
x = 0,<br />
y = 0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width = "100%",<br />
height = "100%",<br />
},<br />
miniconsoleContainer<br />
)<br />
<br />
local index = 0<br />
local line = getCurrentLine()<br />
local linesize = #line<br />
local currentlinenumber = getLineNumber()<br />
local r, g, b = 0, 0, 0<br />
local cr, cg, cb -- last seen colors<br />
while index < linesize do<br />
index = index + 1<br />
moveCursor("main", index, currentlinenumber)<br />
selectString(line:sub(index), 1)<br />
r, g, b = getFgColor()<br />
if cr ~= r or cg ~= g or cb ~= b then<br />
cr, cg, cb = r, g, b<br />
myMiniconsole:echo(string.format("rgb(%d,%d,%d)%s", r, g, b, line:sub(index, index)))<br />
else<br />
myMiniconsole:echo(string.format("%s", line:sub(index, index)))<br />
end<br />
line:sub(index, index)<br />
end<br />
myMiniconsole:echo("\n")<br />
</syntaxhighlight><br />
<br />
==How to enter a carriage return / enter command?==<br />
Say you'd like to gag the following line, and just continue ... <br />
<br />
[ Press Enter to continue ]<br />
<br />
<syntaxhighlight lang="lua"><br />
Trigger: [ Press Enter to continue ] (set to exact match)<br />
Code: deleteLine()<br />
send("\n")<br />
</syntaxhighlight><br />
<br />
==How to repeat commands with #?==<br />
Install the [https://forums.mudlet.org/viewtopic.php?f=6&t=1275 following alias], and with it <code>#5 mycommand</code> will get repeated five times.<br />
<br />
== How to move the command line over? ==<br />
<br />
To move the command line over to the right, create a new script and add the following to it:<br />
<br />
<syntaxhighlight lang="css"><br />
setCmdLineStyleSheet("main", [[<br />
QPlainTextEdit {<br />
padding-left: 100px; /* change 100 to your number */<br />
background-color: black; /* change it to your background color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
== How to add a background for Mudlets buttons? ==<br />
You can give Mudlets buttons a background to have them blend in with your UI by doing this:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- replace the /home/vadi/Pictures/tile.png location below with the one of your picture!<br />
-- you can download the sample tile.png from https://opengameart.org/content/bevouliin-free-game-background-for-game-developers<br />
local backgroundpath = [[/home/vadi/Pictures/tile.png]]<br />
-- Windows:<br />
-- local backgroundpath = [[C:/Users/Vadim/Downloads/Free game background/transparent PNG/tile.png]]<br />
<br />
setAppStyleSheet([[<br />
QToolBar {<br />
border-image: url(]]..backgroundpath..[[);<br />
<br />
}<br />
<br />
QToolBar QToolButton:!hover {<br />
color: white;<br />
}<br />
QToolBar QToolButton:hover {<br />
color: black;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
Result:<br />
<br />
[[File:Mudlet tiled buttons.png|frame|left]]<br />
<br clear=all><br />
<br />
= Advanced scripting tips =<br />
== Do stuff after all triggers/aliases/scripts are run ==<br />
This little snippet will have your commands be executed right after, depending on the context you run it in, all triggers, aliases or scripts are completed:<br />
<br />
<syntaxhighlight lang="lua">tempTimer(0, [[mycode]])</syntaxhighlight><br />
<br />
== How to delete the previous and current lines ==<br />
<br />
This little snippet comes from [http://forums.mudlet.org/viewtopic.php?f=9&t=2411&p=10685#p10685 Iocun]:<br />
<br />
<syntaxhighlight lang="lua"><br />
moveCursor(0,getLineCount()-1)<br />
deleteLine()<br />
moveCursor(0,getLineCount())<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=db: Mudlet's database frontend=<br />
<br />
The DB package is meant to provide easier access to a database, so you don’t have to know SQL or use the luasql module to set and get at your data. However, it does require that the luasql module be compiled and included in Mudlet to function.<br />
<br />
==Creating a Database==<br />
<br />
Before you can store anything in a database, you need to create one. You may have as many independent databases as you wish, with each having as many unique tables-- what we will call sheets in this package, so as to avoid confusion with Lua tables - think spreadsheets.<br />
<br />
To create a database, you use the db:create() function, passing it the name of your database and a Lua table containing its schema configuration. A schema is a mold for your database - it defines what goes where. Using the spreadsheet example, this would mean that you’d define what goes into each column. A simple example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes"}})<br />
</syntaxhighlight><br />
<br />
This will create a database which contains two sheets: one named friends, the other named enemies. Each has three columns, name, city and notes-- and the datatype of each are strings, though the types are very flexible and can be changed basically whenever you would like. It’ll be stored in a file named Database_people.db in your Mudlet config directory on the hard drive should you want to share it.<br />
<br />
It’s okay to run this function repeatedly, or to place it at the top-level of a script so that it gets run each time the script is saved: the DB package will not wipe out or clear the existing data in this case. <br />
<br />
{{Note}} You may not create a column or field name which begins with an underscore. This is strictly reserved to the db package for special use.<br />
<br />
{{Note}} Adding new columns to an existing database did not work in Mudlet 2.1 - see [[Manual:Lua_Functions#db:create|db:create()]] on how to deal with this.<br />
<br />
<!--<br />
More importantly, this allows you to add columns to an existing sheet. If you change that line to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes", "enemied"}})<br />
</syntaxhighlight><br />
<br />
It will notice that there is a new column on enemies, and add it to the existing sheet-- though the value will end up as nil for any rows which are already present. Similarly, you can add whole new sheets this way. It is not presently possible to -remove- columns or sheets without deleting the database and starting over.<br />
--><br />
<br />
==Adding Data==<br />
<br />
To add data to your database, you must first obtain a reference (variable) for it. You do that with the db:get_database function, such as:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("people")<br />
</syntaxhighlight><br />
<br />
The database object contains certain convenience functions (discussed later, but all are preceded with an underscore), but also a reference to every sheet that currently exists within the database. You then use the db:add() function to add data to the specified sheet.<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends, {name="Ixokai", city="Magnagora"})<br />
</syntaxhighlight><br />
<br />
If you would like to add multiple rows at once to the same table, you can do that by just passing in multiple tables:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends,<br />
{name="Ixokai", city="Magnagora"},<br />
{name="Vadi", city="New Celest"},<br />
{name="Heiko", city="Hallifax", notes="The Boss"}<br />
)<br />
</syntaxhighlight><br />
<br />
Notice that by default, all columns of every table are considered optional-- if you don’t include it in the add, then it will be set to its default value (which is nil by default)<br />
<br />
For those familiar with databases: with the DB package, you don’t have to worry about committing or rolling back any changes, it will commit after each action automatically. If you would like more control than this, see Transactions below.<br />
<br />
You also cannot control what is the primary key of any sheets managed with DB, nor do you have to create one. Each row will get a unique integer ID that automatically increments, and this field can be accessed as "_row_id".<br />
<br />
==Querying==<br />
<br />
Putting data in isn’t any fun if you can’t get it out. If you want every row from the sheet, you can do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends)<br />
</syntaxhighlight><br />
<br />
But rarely is that actually useful; usually you want to get only select data. For example, you only want to get people from the city of Magnagora. To do that you need to specify what criteria the system should use to determine what to return to you. It looks like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
So the basic command is - db:fetch(_sheet_, _what to filter by_)<br />
<br />
The following filter operations are defined:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:eq(field, value[, case_insensitive]) -- Defaults to case insensitive, pass true as the last arg to<br />
reverse this behavior.<br />
db:not_eq(field, value[, case_insensitive) -- Not Equal To<br />
db:lt(field, value) -- Less Than<br />
db:lte(field, value) -- Less Than or Equal to.<br />
db:gt(field, value) -- Greater Than<br />
db:gte(field, value) -- Greater Than or Equal To<br />
db:is_nil(field) -- If the column is nil<br />
db:is_not_nil(field) -- If the column is not nil<br />
db:like(field, pattern) -- A simple matching pattern. An underscore matches any single character,<br />
and a percent(%) matches zero or more characters. Case insensitive.<br />
db:not_like(field, pattern) -- As above, except it'll give you everything but what you ask for.<br />
db:between(field, lower_bound, upper_bound) -- Tests if the field is between the given bounds (numbers only).<br />
db:not_between(field, lower_bound, upper_bound) -- As above, only... not.<br />
db:in_(field, table) -- Tests if the field is in the values of the table. NOTE the trailing underscore!<br />
db:not_in(field, table) -- Tests if the field is NOT in the values of the table *<br />
</syntaxhighlight><br />
<br />
The db:in_ operator takes a little more explanation. Given a table, it tests if any of the values in the table are in the sheet. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:in_(mydb.friends.city, {"Magnagora", "New Celest"})<br />
</syntaxhighlight><br />
<br />
It tests if city == "Magnagora" OR city == "New Celest", but with a more concise syntax for longer lists of items.<br />
<br />
There are also two logical operators:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:AND(operation1, ..., operationN)<br />
db:OR(operation1, operation2)<br />
</syntaxhighlight><br />
<br />
You may pass multiple operations to db:fetch in a table array, and they will be joined together with an AND by default. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends,<br />
{db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "X%")}<br />
)<br />
</syntaxhighlight><br />
<br />
This will return every record in the sheet which is in the city of Magnagora, and has a name that starts with an X. Again note that in LIKE patterns, a percent is zero or more characters — this is the same effect as "X.*" in pcre patterns. Similarly, an underscore matches any single characters and so is the same as a dot in pcre.<br />
<br />
Passing multiple expressions in an array to db:fetch is just a convenience, as its exactly the same as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:AND(db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "I%")))<br />
</syntaxhighlight><br />
<br />
The db:OR operation only takes two arguments, and will check to see if either of the two is true. You can nest these logical operators as deeply as you need to.<br />
<br />
You can also just pass in a string directly to db:fetch, but you have to be very careful as this will be passed straight to the SQL layer. If you don’t know any SQL then you want to avoid this… for example, in SQL there’s a very big difference between double and single quotes. If you don’t know that, then stick to the db functions. But an example is:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, "city == 'Magnagora'")<br />
</syntaxhighlight><br />
<br />
Now, the return value of db:fetch() is always a table array that contains a table dictionary representing the full contents of all matching rows in the sheet. These are standard Lua tables, and you can perform all normal Lua operations on them. For example, to find out how many total items are contained in your results, you can simply do #results. If a request from the friends sheet were to return one row that you stored in the results variable, it would look like this if passed into the display() function:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'name': 'Bob',<br />
'city': 'Magnagora',<br />
'notes': 'Trademaster of Tailoring'<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
And if you were to echo(#results), it would show 1.<br />
<br />
The order of the returned rows from db:fetch is generally the same as the order in which you entered them into the database, but no actual guarantees are made to this. If you care about the order then you can pass one or two optional parameters after the query to db:fetch() to control this.<br />
<br />
The first table is an array of fields that indicate the column names to sort by; the second is a flag to switch from the default ascending(smallest to largest) sort, to a descending(largest to smallest) sort. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city})<br />
</syntaxhighlight><br />
<br />
This will return all your friends in Magnagora, sorted by their name, from smallest to largest. To reverse this, you would simply do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city}, true)<br />
</syntaxhighlight><br />
<br />
Including more then one field in the array will indicate that in the case that two rows have the same value, the second field should be used to sort them.<br />
<br />
If you would like to return ALL rows from a sheet, but still sort them, you can do that by passing nil into the query portion. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, nil, {mydb.friends.city, mydb.friends.name})<br />
</syntaxhighlight><br />
<br />
This will return every friend you have, sorted first by city and then their name.<br />
<br />
==Indexes and Types==<br />
<br />
The sheets we’ve defined thus far are very simple, but you can take more control over the process if you need to. For example, you may assign default values and types to columns, and the DB package will attempt to coerce them as appropriate. To do that, you change your db:create() call as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
This is almost the same as the original definition, but we’ve defined that our first four fields are strings with a default value of blank, and the new kills field which is an integer that starts off at 0. The only way to set a datatype is to set a default value at this time.<br />
<br />
Please note, beneath the DB package is SQLite, and SQLite is very data-type neutral. It doesn’t really care very much if you break those rules and put an integer in a string field or vice-versa, but the DB package will — to a limited degree — attempt to convert as appropriate, especially for the operations that work on numbers.<br />
<br />
You may also create both standard and unique indexes. A unique index enforces that a certain criteria can only happen once in the sheet. Now, before you go and make indexes, pause and consider. There is no right or wrong answer when it comes to what to index: it depends on what kind of queries you do regularly. If in doubt, don’t make an index. Indexes will speed up reading data from the sheet, but they will slow down writing data.<br />
<br />
To add an index, pass either the _index or _unique keys in the table definition. An example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" }<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Now, bear in mind: _index = { "name", "city"} creates two indexes in this sheet. One on the city field, one on the name field. But, _index = { {"name", "city"} } creates one index: on the combination of the two. Compound indexes help speed up queries which frequently scan two fields together, but don’t help if you scan one or the other.<br />
<br />
The admonition against making indexes willy-nilly holds double for compound indexes: do it only if you really need to!<br />
<br />
===Uniqueness===<br />
<br />
As was specified, the _unique key can be used to create a unique index. This will make it so a table can only have one record which fulfills that index. If you use an index such as _unique = { "name" } then names must be unique in the sheet. You can specify more than one key to be unique; in that case they will be checked in an OR condition.<br />
<br />
Now, if you use db:add() to insert a record which would violate the unique constraint, a hard error will be thrown which will stop your script. Sometimes that level of protection is too much, and in that case you can specify how the db layer handles violations.<br />
<br />
There are three possible ways in which the layer can handle such violations; the default is to FAIL and error out.<br />
<br />
You can also specify that the db layer should IGNORE any commands that would cause the unique constraint to be violated, or the new data should REPLACE the existing row.<br />
<br />
For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento"})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the name field being declared to be unique, these two commands can’t succeed normally. The first db:add() will create a record with the name of Bob, and the second would cause the uniqueness of the name field to be violated. With the default behavior (FAIL), the second db:add() call will raise an error and halt the script.<br />
<br />
If you want the IGNORE behavior, the second command will not cause any errors and it will simply fail silently. Bob’s city will still be Sacramento.<br />
<br />
With the REPLACE behavior, the second command will cause its data to completely overwrite and replace the first record. Bob’s city will now be San Francisco.<br />
<br />
A word of caution with REPLACE, given:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento", notes="This is something."})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the REPLACE behavior, the second record will overwrite the first-- but the second record does not have the notes field set. So Bob will now not have any notes. It doesn’t -just- replace existing fields with new ones, it replaces the entire record.<br />
<br />
To specify which behavior the db layer should use, add a _violations key to the table definition:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" },<br />
_violations = "IGNORE"<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Note that the _violations behavior is sheet-specific.<br />
<br />
===Timestamps===<br />
<br />
In addition to strings and floats, the db module also has basic support for timestamps. In the database itself this is recorded as an integer (seconds since 1970) called an epoch, but you can easily convert them to strings for display, or even time tables to use with Lua’s built-in time support.<br />
<br />
The most common use for the Timestamp type is where you want the database to automatically record the current time whenever you insert a new row into a sheet. The following example illustrates that:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:create("combat_log",<br />
{<br />
kills = {<br />
name = "",<br />
area = "",<br />
killed = db:Timestamp("CURRENT_TIMESTAMP"),<br />
_index = { {"name", "killed"} }<br />
}<br />
}<br />
)<br />
<br />
-- observe that we don't provide the killed field here - DB automatically fills it in for us.<br />
db:add(mydb.kills, {name="Drow", area="Undervault"})<br />
<br />
results = db:fetch(mydb.kills)<br />
display(results)<br />
</syntaxhighlight><br />
<br />
The result of that final display would show you this on a newly created sheet:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'_row_id': 1<br />
'area': 'Undervault'<br />
'name': 'Drow'<br />
'killed': table {<br />
'_timestamp': 1264317670<br />
}<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
As you can see from this output, the killed fields contains a timestamp-- and that timestamp is stored as an epoch value in the GMT timezone. For your convenience, the db.Timestamp type offers three functions to get the value of the timestamp in easy formats. They are <code>as_string</code>, <code>as_number</code> and <code>as_table</code>, and are called on the timestamp value itself.<br />
<br />
The as_number function returns the epoch number, and the as_table function returns a time table. The as_string function returns a string representation of the timestamp, with a default format of "%m-%d-%Y %H:%M:%S". You can override this format to anything you would like. Details of what you can do with epoch values, time tables, and what format codes you can use are specified in the Lua manual at: http://www.lua.org/pil/22.1.html for the Lua date/time functions.<br />
<br />
A quick example of the usage of these functions is:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.kills)<br />
for _, row in ipairs(results) do<br />
echo("You killed " .. row.name .. " at: " .. (row.killed and row.killed:as_string() or "no time") .."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==Deleting==<br />
<br />
The db:delete function is used to delete rows from the sheet. It takes two arguments, the first being the sheet you are deleting and the second a query string built using the same functions used to build db:fetch() queries.<br />
<br />
For example, to delete all your enemies in the city of Magnagora, you would do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these! You may inadvertantly wipe out huge chunks of your sheets if you don’t have the query parameters set just to what you need them to be. Its advised that you first run a db:fetch() with those parameters to test out the results they return.<br />
<br />
As a convenience, you may also pass in a result table that was previously retrieved via db:fetch and it will delete only that record from the table. For example, the following will get all of the enemies in Magnagora, and then delete the first one:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
db:delete(mydb.enemies, db:eq(mydb.enemies._row_id, results[1]._row_id))<br />
</syntaxhighlight><br />
<br />
That is equivalent to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
You can even pass a number directly to db:delete if you know what _row_id you want to purge.<br />
<br />
A final note of caution: if you want to delete all the records in a sheet, you can do so by only passing in the table reference. To try to protect you from doing this inadvertently, you must also pass true as the query after:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, true)<br />
</syntaxhighlight><br />
<br />
==Updating==<br />
<br />
If you make a change to a table that you have received via db:fetch(), you can save those changes back to the database by doing:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:update(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
A more powerful (and somewhat dangerous, be careful!) function to make changes to the database is db:set, which is capable of making sweeping changes to a column in every row of a sheet. Beware, if you have previously obtained a table from db:fetch, that table will NOT represent this change.<br />
<br />
The db:set() function takes two arguments: the field to change, the value to set it to, and the db:fetch() like query to indicate which rows should be affected. If you pass true as the last argument, ALL rows will be changed.<br />
<br />
To clear out the notes of all of our friends in Magnagora, we could do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:set(mydb.friends.notes, "", db:eq(mydb.friends.notes, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these!<br />
<br />
==Transactions==<br />
<br />
As was specified earlier, by default the db module commits everything immediately whenever you make a change. For power-users, if you would like to control transactions yourself, the following functions are provided on your database instance:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("my_database")<br />
mydb:_begin()<br />
mydb:_commit()<br />
mydb:_rollback()<br />
mydb:_end()<br />
</syntaxhighlight><br />
<br />
Once you issue a mydb._begin() command, autocommit mode will be turned off and stay off until you do a mydb._end(). Thus, if you want to always use transactions explicitly, just put a mydb._begin() right after your db:create() and that database will always be in manual commit mode.<br />
<br />
==Viewing and editing the database contents==<br />
<br />
A good tool to view and edit the database contents in raw form is [http://afoucal.free.fr/index.php/applications/sqlite-sorcerer/ SQlite Sorcerer] (free and available for Linux, Windows, Mac).<br />
<br />
==Debugging raw queries==<br />
<br />
If you'd like to see the queries that db: is running for you, you can enable debug mode with ''db.debug_sql = true''.<br />
<br />
=Discord Messenges=<br />
<br />
Can you send messenges from Mudlet to Discord? Totally. Here is an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
function sendToDiscord(data)<br />
local url = "https://discord.com/api/webhooks/1204151397977821184/Cu8ZQQo9R11AyIt3DxpOEeB8MtVMA6_AEfXoZaYxqEAOu_6hwhtA2cRLIw-VIs7py7p8"<br />
local headers = {["Content-Type"] = "application/json"}<br />
local json = yajl.to_string(data)<br />
postHTTP(json, url, headers)<br />
end<br />
<br />
local data = {<br />
content = "Hello, Discord!",<br />
embeds = {<br />
{<br />
title = "This is an embed",<br />
url = "https://example.com",<br />
image = {<br />
url = "https://example.com/image.jpg"<br />
}<br />
}<br />
}<br />
}<br />
<br />
sendToDiscord(data)<br />
<br />
</syntaxhighlight><br />
<br />
Sure enough, after starting this script, you can see a message in Discord:<br />
<br />
[[File:Message to Discord.png|border|center]]<br />
<br />
What you just need to do is create a webhook in a channel. Go to channel settings, then create this:<br />
<br />
[[File:Webhook in Discord.png|border|center]]<br />
<br />
Here you can find more documentation on which fields Discord allows: https://discord.com/developers/docs/resources/webhook#execute-webhook<br />
<br />
All this is one way though. Mudlet won't listen to messages from Discord. For that you'd probably have to make a Discord bot first.<br />
<br />
=Discord Rich Presence=<br />
[[File:Rich_Presence_Midmud.gif|frame]]<br />
<!-- [[File:Rich Presence Achaea.gif|frame]] --><br />
<br />
Discord Rich Presence in Mudlet allows you, the player, to show off the game you're playing and you, the game author, to get your game shown off! Advertise your game for free alongside AAA titles in server player lists :)<br />
<br />
To respect the players privacy, this option is disabled by default - enable it by ticking the Discord option for the profile:<br />
<br />
[[File:Enable Discord.png|border|center]]<br />
<br />
Once enabled, a Discord-capable game will show information in your Discord!<br />
<br />
To fine-tune the information you'd like to see displayed, go to Settings, Chat tab:<br />
<br />
[[File:Discord Privacy.png|center|400px]]<br />
<br />
== Implementing ==<br />
As a game author, you have two ways of adding Discord support to your game: via GMCP (easy) or via Lua.<br />
<br />
Adding support via GMCP means that your players don't have to install any Lua scripts which is a nicer experience. To do so, implement the [[Standards:Discord_GMCP|Discord over GMCP]] specification and [https://www.mudlet.org/contact/ get in touch] to let us know your game implements GMCP.<br />
<br />
=== GMCP ===<br />
Here's a quick cheatsheet to implement the [[Standards:Discord_GMCP|GMCP spec]]:<br />
<br />
# Create a discord [https://discordapp.com/developers/applications/me application]<br />
# Upload game logo for "rich presence invite image"<br />
# Upload same game logo in "Rich Presence Assets" with the name of <code>server-icon</code><br />
# Upon receiving "External.Discord.Hello" from the game client, reply with "External.Discord.Info" with <code>applicationid</code> ([[:File:Mudlet Discord ApplicationID.png|see screenshot]]) and "External.Discord.Status" <br />
# Send "External.Discord.Status" whenever you need to send data to the client, and fill it with the values have changed since the last status. Discord has [https://discordapp.com/developers/docs/rich-presence/best-practices#tips some ideas] for filling it in.<br />
# Done. Mudlet will enable the Discord checkbox upon receiving the <code>applicationid</code> from the game at least once.<br />
<br />
=== Lua ===<br />
An alternative way to add Discord support as a game author is [[Manual:Discord_Functions|via Lua]] - all of Discords functionality can be manipulated from it. Create a discord [https://discordapp.com/developers/applications/me application] and set it with [[Manual:Discord_Functions#setDiscordApplicationID|setDiscordApplicationID()]], then set the set the rest of the options as necessary:<br />
<br />
[[File:Discord fields.png|frame|center|Credit: Discord]]<br />
<br />
If you're a game player and your game doesn't support Discord, you can still use the functionality to set the detail, status, party and time information as desired.<br />
<br />
{{MudletVersion|3.14}}<br />
<br />
=MUD Client Media Protocol=<br />
<br />
==Client.Media==<br />
Want to add accessibility and excitement into your game? How about implementing sound and music via GMCP?<br />
<br />
The Client.Media family of GMCP packages provide a way for games to send sound and music events. GMCP media events are sent in one direction: from game server to to game client.<br />
<br />
===Client.Media in Mudlet===<br />
<br />
Media files may be downloaded manually or automatically if certain conditions are met.<br />
<br />
{{MudletVersion|4.4}}<br />
<br />
Mudlet accepts case-insensitive GMCP for the Client.Media namespace (for example, these are all acceptable: "Client.Media.Play", "client.media.play", "cLiEnT.MeDiA.Play").<br />
<br />
===Enabling Media===<br />
When a new profile opens, Mudlet adds to the Core.Supports.Set GMCP package "Client.Media 1" to signal to servers that it supports processing media files via GMCP:<br />
<br />
<syntaxhighlight lang="json"><br />
Core.Supports.Set ["Client.Media 1", ...]<br />
</syntaxhighlight><br />
<br />
To process Client.Media GMCP data in Mudlet, these boxes in the Settings window of Mudlet must be checked:<br />
<br />
# The "Enable GMCP" box in the Miscellaneous section.<br />
# The "Allow server to download and play media" box in the Game protocols section.<br />
<br />
These boxes are checked by default upon the start of a new profile in Mudlet.<br />
<br />
===Storing Media===<br />
<br />
Mudlet plays files cached in the "media" folder within a game's profile. To get files into the "media" folder you could perform either of these options:<br />
<br />
# Copy media files or extract them from an archive (zip)<br />
# Automatically download them from external resources such as your game's web server on the Internet.<br />
<br />
To enable the second option (Internet), use the "url" parameter made available in the "Client.Media.Default", "Client.Media.Load" and "Client.Media.Play" GMCP packages described below.<br />
<br />
===Loading Media===<br />
<br />
Send a '''Client.Media.Default''' GMCP event to setup the default URL directory to load sound or music files from external resources. This would typically be done once upon player login. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
|-<br />
|}<br />
<br />
For example, to setup the default URL directory for your game:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Default {<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
If downloading from external resources, it is recommended to use Client.Media.Default, set this default URL directory once, and let Mudlet download all of your media files automatically from this one resource location. Otherwise, explicitly set the "url" parameter on all of your Client.Media.Load GMCP and Client.Media.Play GMCP events to ensure that files are downloaded from the intended location(s).<br />
<br />
Send '''Client.Media.Load''' GMCP events to load sound or music files. This could be done when the player logs into your game or at the beginning of a zone that will need the media.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if a url was not set above with Client.Media.Default.<br />
|-<br />
|}<br />
<br />
For example, download the sound of a sword swooshing within the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Load {<br />
"name": "sword1.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
===Playing Media===<br />
<br />
Send '''Client.Media.Play''' GMCP events to play sound or music files.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely and a url was not set above with Client.Media.Default or Client.Media.Load.<br />
|-<br />
| style="text-align:center;"| No<br />
| "type"<br />
| "sound" or "music"<br />
| "sound"<br />
| style="text-align:left;"|<br />
* Identifies the type of media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "tag"<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "volume"<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| "fadein"<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"fadeout"<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| "start"<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
* 1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"loops"<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the sound or music to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a lower priority while this media plays.<br />
|-<br />
| style="text-align:center;" |No<br />
|"continue"<br />
| true or false<br />
|true<br />
| style="text-align:left;" |<br />
*Only valid for media files with a "type" of "music".<br />
*Continues playing matching new music files when true.<br />
*Restarts matching new music files when false.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
|}<br />
<br />
==== name====<br />
<br />
For example, to simply play the sound of a cow mooing already stored in the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Or some lightning stored in a "weather" sub-folder under the "media" folder.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "weather/lightning.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
The "name" parameter may be used for stopping media with the Client.Media.Stop GMCP event.<br />
<br />
====url====<br />
<br />
If you maintain your sound files on the Internet and don't set a default URL with Client.Media.Default, or preload them with Client.Media.Load, include the "url" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
====type: sound====<br />
<br />
Media files default to a "type" of "sound" when the "type" parameter is not specified, such as in the example above. It is good practice to specify the "type" parameter to best keep media organized within your implementation:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====tag====<br />
<br />
To play the sound of a sword swooshing and categorized as "combat":<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat"<br />
}<br />
</syntaxhighlight><br />
<br />
The "tag" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====type: music====<br />
<br />
Add background music to your environment through use of the "music" value set upon the "type" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====volume: 1 to 100====<br />
<br />
As the character draws nearer to or farther from the environmental feature, consider adjusting the "volume" parameter. Example values, followed by syntax examples:<br />
<br />
*Maximum: 100 (recommended to use rarely)<br />
*High: 75<br />
*Default: 50<br />
* Low: 25<br />
* Minimum: 1 (recommended to use rarely)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment",<br />
"volume": 75<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "volume" values of type string ("75") into integers (75) as needed.<br />
<br />
====fadein====<br />
<br />
Increase volume from the start of the media [start position, volume one] to the number in milliseconds specified with the "fadein" parameter [position start + milliseconds, volume specified with the "volume" parameter]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade in)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "monty_python.mp3",<br />
"type": "music",<br />
"volume": 100,<br />
"fadein": 1000<br />
}<br />
</syntaxhighlight><br />
+---------------------------+-----------------------+<br />
| Fade in 1000 milliseconds | Normal |<br />
+---------------------------+-----------------------+<br />
Volume 1|........::::::::::iiiiiiiii%%%%%%%%%%%%%%%%%%%%%%%%|Volume 100<br />
+---------------------------+-----------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadein" values of type string ("1000") into integers (1000) as needed.<br />
<br />
==== fadeout====<br />
<br />
Decrease volume from a position in milliseconds subtracted from the duration of the media [position duration - milliseconds, volume specified with the "volume" parameter] to the end of the media [position duration, volume one]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade out)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "the_matrix.mp3",<br />
"type": "music",<br />
"volume": 50,<br />
"fadeout": 333<br />
}<br />
</syntaxhighlight><br />
+-----------------------+---------------------------+<br />
| Normal | Fade out 333 milliseconds |<br />
+-----------------------+---------------------------+<br />
Volume 50|%%%%%%%%%%%%%%%%%%%%%%%%iiiiiiiii::::::::::........|Volume 1<br />
+-----------------------+---------------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadeout" values of type string ("333") into integers (333) as needed.<br />
<br />
==== start ====<br />
<br />
Start playing a media track at the number of milliseconds specified. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (start from beginning)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "mudlet_beatboxing.mp3",<br />
"type": "music",<br />
"volume": 75,<br />
"start": 1000<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "start" values of type string ("100") into integers (100) as needed.<br />
<br />
==== loops: -1, 1 or more ====<br />
<br />
The "loops" parameter controls how many times the sound repeats and defaults to 1 if not specified. A value of -1 will loop the file indefinitely.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "clock/hour_bell.wav",<br />
"type": "sound",<br />
"loops": 3<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "underdark.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "loops" values of type string ("-1") into integers (-1) as needed.<br />
<br />
==== priority: 1 to 100 ====<br />
<br />
The "priority" parameter sets precedence for Client.Media.Play GMCP events that include a "priority" setting. The values for the "priority" parameter range between 1 and 100. Given that two Client.Media.Play GMCP events have the same priority, the media already playing will continue playing. In Mudlet, media without priority set is not included comparisons based on priority.<br />
<br />
A common place to find priority implemented is with combat. In the following example, imagine a combat scenario where some sounds of sword thrusts were interrupted by a successful blocking maneuver.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3,<br />
"priority": 60<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "block1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"priority": 70<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "priority" values of type string ("25") into integers (25) as needed.<br />
<br />
The "priority" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====continue: true or false (for music)====<br />
<br />
Typically sent with the "type" of "music" is the parameter "continue", which presents the following values:<br />
<br />
*true: continues music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
*false: restarts music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "city.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"continue": true<br />
}<br />
</syntaxhighlight><br />
<br />
If the "continue" parameter is not specified, behavior will default to ''true'' for music.<br />
<br />
Although using the boolean type is recommended, Mudlet parses "continue" values of type string ("true" and "false") into boolean (''true'' and ''false'') as needed, as not all game drivers support a boolean type.<br />
<br />
==== key====<br />
<br />
The "key" parameter enables media categorization, similar to the "tag" parameter, however it adds a feature of uniqueness that halts media currently playing with the same key, replacing it with the media that arrived from a new Client.Media.Play GMCP event. This update will only occur if the "name" or "url" associated with the currently playing media does not match the new media, while the key is identical.<br />
<br />
In the example below, consider that a player moves from a sewer area to a village. The "key" parameter is used to stop the previously playing ''sewer.mp3'' and start playing ''village.mp3'' within the second Client.Media.Play GMCP event. <br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sewer.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "village.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
The "key" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
{{note}} Where music is bound to change, continue or stop as a player enters a new room, consider allowing for a slight pause of 1 heart beat or tick to send the Client.Media.Play or Client.Media.Stop GMCP events. This practice reduces the number of Client.Media.Play GMCP events sent when the player travels through several rooms quickly.<br />
<br />
==== randomization====<br />
<br />
Wildcards ''*'' (asterisk) and ''?'' (question mark) may be used within the name to randomize media file(s) selection.<br />
<br />
Given that media files underdark.wav, underdark.mp3 and underdark_dark_elven_moshpit.mp3 were all present in the media/environment directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play using the ''*'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "underdark*",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": false<br />
}<br />
</syntaxhighlight><br />
<br />
If media files sword1.wav, sword2.wav and sword3.wav were all present in the media/combat directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play per each loop using the ''?'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "combat/sword?.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3<br />
}<br />
</syntaxhighlight><br />
<br />
=== Stopping Media ===<br />
<br />
Send '''Client.Media.Stop''' GMCP events to stop sound or music media.<br />
<br />
{| class="wikitable"<br />
!Required<br />
!Key<br />
!Value<br />
! style="text-align:left;" |Purpose<br />
|-<br />
| style="text-align:center;" | No<br />
| "name"<br />
|<file name><br />
| style="text-align:left;" |<br />
*Stops playing media by name matching the value specified.<br />
|-<br />
| style="text-align:center;" | No<br />
|"type"<br />
|"sound" or "music"<br />
| style="text-align:left;" | <br />
*Stops playing media by type matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
| "tag"<br />
|<tag><br />
| style="text-align:left;" |<br />
*Stops playing media by tag matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
| style="text-align:left;" |<br />
*Stops playing media with priority less than or equal to the value.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
| style="text-align:left;" | <br />
*Stops playing media by key matching the value specified.<br />
|-<br />
|}<br />
<br />
====all====<br />
<br />
Send the Client.Media.Stop GMCP event with no parameters to stop all playing media within a given game profile.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {}<br />
</syntaxhighlight><br />
<br />
====parameters====<br />
<br />
Send any combination of the name, type, tag, priority or sound parameters and valid corresponding values to stop playing media that matches ''all'' combinations of the parameters.<br />
<br />
Stop the rain.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"name": "rain.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media using the "type" of "sound".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "tag" of "combat" ''and'' that has a "priority" less than or equal to 50.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"tag": "combat",<br />
"priority": 50<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "key" of "area-music".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
=GUI Scripting in Mudlet=<br />
Mudlet has extremely powerful GUI capabilities built into it, and with the inclusion of the Geyser and Vyzors layout managers in Mudlet's Lua API it is quicker and easier to get a basic UI created.<br />
<br />
==Geyser==<br />
Geyser is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
Geyser's manual is quite extensive - [[Manual:Geyser|follow here]] to read up on it.<br />
<br />
===UI template===<br />
Akaya has created a UI template based on Geyser that can serve as a quick start for customizing the Mudlet interface to your character:<br />
<br />
[[File:Geyser UI template.png|center|800px|border]]<br />
<br />
To get started with it, see the forum thread about [http://forums.mudlet.org/viewtopic.php?f=6&t=4098 Geyser UI Template].<br />
<br />
==Simple Window Manager==<br />
Simple Window Manager is a light-weight script designed to provide the GUI object placement and sizing functionality seen in Geyser and Vyzor without any of the extras. Any GUI object, once created normally, can be added to the SWM along with a corner to base its positioning info off of, the distance from that corner, and the size of the object in any combination of pixels and percentages of the screen. SWM does all the behind the scenes work to keep all objects it has been given to manage in their correct places and sizes as the screen changes size. All other interactions with GUI objects are handled using standard functions built into Mudlet.<br />
<br />
Simple Window Managers manual, and download, can be [http://forums.mudlet.org/viewtopic.php?f=6&t=3529 found here].<br />
<br />
==Useful Resources==<br />
There are several useful resources you can refer to when creating your GUI.<br />
<br /><br />
<br />
;Wiki Resources<br />
*[[Manual:Geyser|Geyser Tutorial]]:<br />
:Excellent for getting an initial feel of how to use the Geyser layout manager.<br />
*[[Manual:Lua_Functions#UI_Functions|GUI API]]:<br />
:The GUI section of the Lua API manual<br />
;External Resources<br />
*[http://forums.mudlet.org/viewforum.php?f=11 Geyser subforum]:<br />
:The Geyser Layout Manager subforum on Mudlet's forums.<br />
*[http://forums.mudlet.org/viewtopic.php?f=5&t=1376 GUI Screenshots]:<br />
:A pinned thread on Mudlet's forums for showing what your GUI looks like. Useful for ideas and to see what is possible.<br />
*[http://forums.mudlet.org/viewtopic.php?f=9&t=1974 Godwars II Mudlet UI]:<br />
:A forum thread which follows the evolution of the UI provided by [http://www.godwars2.org God Wars II]<br />
[[Category:Mudlet Manual]]<br />
<br />
==Resetting your UI==<br />
While scripting your UI, you can reset it completely and have your scripts be loaded from scratch with the [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] function - in the input line, type <code>lua resetProfile()</code>.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Scripting&diff=20904Manual:Scripting2024-02-05T20:55:45Z<p>Kebap: /* Discord Messenges */ use actual syntax highlighting code</p>
<hr />
<div>{{TOC right}}<br />
=Scripting with Mudlet=<br />
<br />
Lua tables can basically be considered multidimensional arrays and dictionaries at the same time. If we have the table matches, matches[2] is the first element, matches[n+1] the n-th element.<br />
<br />
<syntaxhighlight lang="lua"><br />
a = "Tom"<br />
matches[2] = "Betty"<br />
b = matches[2]<br />
c = a .. b and e will equal "TomBetty"<br />
</syntaxhighlight><br />
<br />
To output a table you can use a convenience function - ''display(mytable)'', which is built into Mudlet.<br />
<br />
==Lua interface functions - triggers, timers etc.==<br />
<br />
How to get data from regex capture groups? Regular expression capture groups (e.g. "(\d+)" ) are passed on to Lua scripts as a Lua table matches. To make use of this information inside Lua scripts, you need to specify the number of the capture group within the regex.<br />
<br />
<code>Example: You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
This regex contains 3 capture groups, but only the 2 green colored ones contain data as the red capture group is a non-capturing group. Consequently, your Lua script gets passed only 2 instead of 3 capture groups and matches[4] is undefined.<br />
<br />
In your Lua script you may write following program in order to print the number and status of your weapons on the screen:<br />
<br />
<code>You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
<syntaxhighlight lang="lua"><br />
number_of_weapons = matches[2]<br />
status_of_weapons = matches[3]<br />
notice = number_of_weapons .. status_of_weapons<br />
echo( notice )<br />
send( "put weapons in backpack" )<br />
<br />
-- the following 2 lines color the first capture<br />
-- group red and the second group blue<br />
-- see below for details<br />
<br />
selectCaptureGroup( 2 )<br />
setFgColor( 255,0,0 )<br />
<br />
selectCaptureGroup( 3 )<br />
setFgColor( 0,0,255 )</syntaxhighlight><br />
<br />
The best way is to use selectCaptureGroup( number ) to select the proper capture group and then perform your actions on it e.g. replace(), highlight etc. Note: Both selectCaptureGroup() and matches[n] start with group 1 (which is the whole match. The defined capture groups start with 2).<br />
<br />
How to select all occurrences of "Tom" and highlight them?<br />
<br />
You add a function like this to a script containing you main function definitions. Note that script items differ from all other "scripts" in triggers, timers, actions etc. because they require you to put your code in proper functions that can be called by your other trigger-scripts, timer-scripts etc. via normal function calls. Trigger-scripts, timer-scripts etc. cannot contain any function definitions because they are automatically generated functions themselves because this makes usage a lot easier.<br />
<br />
To come back to our question how to select all occurrences of "Tom" and highlight them:<br />
<br />
<syntaxhighlight lang="lua"><br />
function setBgColorAll( word, r, g, b )<br />
i = 0<br />
word_count = 1<br />
while i > -1 do<br />
i = selectString(word, word_count)<br />
if i == -1 then<br />
return<br />
end<br />
word_count = word_count +1<br />
setBgColor( r, g, b )<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
Then you simply define a substring matching trigger on the word "Tom" and in the trigger script you call above function:<br />
<br />
<syntaxhighlight lang="lua">setBgColorAll("Tom", 255,50,50)</syntaxhighlight><br />
<br />
Since Mudlet 4.11+ it is possible to use name capture groups. You can verify if feature availability by checking <code>mudlet.supports.namedPatterns</code> flag.<br />
Let's say you have multiple patterns that you want to handle with one code.<br />
<br />
<code>^My name is (?<name>\w+)\. My class is (?<class>\w+)\.</code><br />
<br />
<code>^I am (?<class\w+)\ and my name is (?<name>\w+)\.</code><br />
<br />
Notice that class and name come in different order, therefore in first case we will have name under <code>matches[2]</code> and in second case under <code>matches[3]</code>.<br />
With named capture groups in both cases we will have name available under <code>matches.name</code> and class under <code>matches.class</code>.<br />
<br />
Code example to handle named matches above:<br />
<syntaxhighlight lang="lua"><br />
echo("Name: " .. matches.name .. "\n")<br />
echo("Class: " .. matches.class .. "\n")<br />
</syntaxhighlight><br />
<br />
==Sending commands or printing information messages==<br />
<br />
To print information messages on the session screen you can use the echo( message ) function, or insertText( text ). Currently, it only takes one string as argument.<br />
<br />
To send a command to the MUD, you can use the send( command ) function. In Alias scripts the command that is being sent to the MUD is contained in the variable command that you can change in the context of Alias scripts. Alias take regular expressions, as well. As a result, you can use following regex and script to talk like Yoda: Perl regex:<br />
<br />
<code> say (\w+).*(\w*).*(.*) </code><br />
<br />
script:<br />
<br />
<syntaxhighlight lang="lua"><br />
send( "say " .. matches[4] .." " .. matches[2] .." ".. matches[3] )<br />
</syntaxhighlight><br />
<br />
Note: The variable "command" contains what was entered in the command line or issued via the expandAlias( ) function. If you use expandAlias( command ) inside an alias script the command would be doubled. You have to use send( ) inside an alias script to prevent recursion. This will send the data directly and bypass the alias expansion.<br />
<br />
===Changing and formatting text from the MUD===<br />
<br />
When sending commands to the MUD - from now on referred to as output stream - alias scripts find the command that was issued by the user stored in the variable "command".<br />
<br />
By manipulating the value, the command can easily be changed before it is being sent to the MUD.<br />
<br />
However, things get much more complicated with the data received from the MUD, from now on referred to as input stream. Before triggers can be run on the MUD data, Mudlet has to strip all format codes from the text and store it in data structures associated with the text. Consequently, the text that is being passed on to the trigger processing unit is a small subset of the data received from the MUD. If you want to edit, replace, delete or reformat text from within your trigger scripts you have to keep this in mind if you don’t want to lose all text format information such as colors etc.<br />
<br />
As the text is linked with data structures containing the format of the text, the cursor position inside the line is important if data is being changed. You select a word or a sequence of characters from the line and then issue commands to do actions on the selected data.<br />
<br />
Replacing the word "Tom" with "Betty" in the line: Jim, Tom and Lucy are learning a new spell. This could be done with following script:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Tom",1)<br />
replace("Betty")<br />
</syntaxhighlight><br />
<br />
Things get more complicated if there are two or more occurrences of "Tom" in the line e.g. Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
The above example code would select the first occurrence of "Tom" in this line and ignore the second. If you want to work on the the second occurrence of "Tom" you have to specify the occurrence number in the call to select().<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString( "Tom", 2 )<br />
replace( "Betty" )<br />
</syntaxhighlight><br />
<br />
This code would change the second "Tom" and leave the first "Tom" alone. The function call<br />
<br />
<syntaxhighlight lang="lua">replaceAll( "Betty" )</syntaxhighlight><br />
<br />
will replace all occurrences of "Tom" with "Betty" in the line if "Tom" has been selected before. replaceAll() is a convenience function defined in LuaGlobal.lua.<br />
<br />
Colorization example: You want to change to color of the words "ugly monster" to red on a white background.<br />
<br />
You add a new trigger and define the regex: ugly monster In the script you write:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("ugly monster", 1 )<br />
setFgColor(255,0,0)<br />
setBgColor(255,255,255)<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
Another means to select text is to select a range of characters by specifying cursor positions. If we have following line: Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
<syntaxhighlight lang="lua">selectSection( 28, 3 )</syntaxhighlight><br />
<br />
This example would select the second Tom. The first argument to selectSection is the cursor position within the line and the second argument is the length of the selection.<br />
<br />
<syntaxhighlight lang="lua">selectCaptureGroup( number )</syntaxhighlight><br />
<br />
This function selects the captureGroup number if you use Perl regular expressions containing capture groups. The first capture group starts with index 1.<br />
<br />
==Deleting Text - Gagging==<br />
<br />
<syntaxhighlight lang="lua">deleteLine()</syntaxhighlight><br />
<br />
This function deletes the current line - or any line where the cursor is currently placed. You can use repeated calls to this function to effectively erase the entire text buffer. If you want to delete or gag certain words only, you can select the text that you want to delete and then replace it with an empty string e.g:<br />
<br />
If you get this line form the MUD: "Mary and Tom walk to the diner."<br />
<br />
<syntaxhighlight lang="lua">selectString( "Tom", 1 )<br />
replace( "" )</syntaxhighlight><br />
<br />
Then the output will be changed to: "Mary and walk to the diner."<br />
<br />
==Cursor Movement and Cursor Placement==<br />
Mudlet allows you to insert text arbitrarily within the buffer - in the previous line, in the previous ten lines, or even the first line that you've ever saw. These are the tools to help you with the job:<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( windowName, x, y )]]</code> This will move the user cursor of window windowName to the absolute (x/y) coordinates in the text.<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( "main", 20, 3950 )]]</code> will move the cursor on the 20th character from the left on line number 3950. To determine the current cursor position you can use getLineNumber() and getColumnNumber() as well as [[Manual:UI_Functions#getLastLineNumber|getLastLineNumber()]] to get the number of the last line in the text buffer. moveCursorEnd("main") will move the cursor of the main display to end of the buffer. This is always a new line of size 1 containing the character \n.<br />
<br />
<code>number_of_last_line_in_text = [[Manual:UI_Functions#getLineCount|getLineCount()]]</code> returns the number of the last line of the text in the console buffer. This number will change as soon as a new \n is printed either by the user or when a new line arrives from the MUD. All lines from the MUD are terminated with \n which is called line feed or the new line character. This control character ends the current line and move the cursor to the beginning of the next line, thus creating a new, empty line below the line that contains the \n.<br />
<br />
<code>line_number_of_the_current_cursor_position = [[Manual:UI_Functions#getLineNumber|getLineNumber()]]</code><br />
<br />
<code>column_number_of_the_current_cursor_position = [[Manual:UI_Functions#getColumnNumber|getColumnNumber()]]</code><br />
<br />
<code>luaTable_containing_textlines = [[Manual:UI_Functions#getLines|getLines( absolute_line_number_from, absolute_line_number_to )]]</code> this will return a Lua table containing all lines between the absolute positions from and to.<br />
<br />
{{note}} This function uses absolute line numbers, not relative ones like in [[Manual:UI_Functions#moveCursor|moveCursor()]].<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor()]]</code> returns true or false depending on whether the move was possible and done.<br />
<br />
=== Inserting text in the middle of the line ===<br />
Here's an example where we'll append the text ''(one)'' right after the word ''exit'' in the line of <code>You see a single exit leading west.</code><br />
<br />
[[File:Inserting text.png|center|650px]]<br />
<br />
The pattern we used was an ''exact match'' for <code>You see a single exit leading west.</code> and the code is:<br />
<br />
<syntaxhighlight lang="lua"><br />
if moveCursor(string.find(line, "exit")+#("exit")-1, getLineNumber()) then<br />
insertText("(one)")<br />
end<br />
</syntaxhighlight><br />
<br />
What happened here:<br />
* we triggered on the desired line using our pattern above<br />
* we used [[Manual:UI_Functions#moveCursor|moveCursor()]] to place the cursor in the desired position within the line. [[Manual:UI_Functions#moveCursor|moveCursor()]] takes both the line number and the position within the line to place our virtual cursor on, so<br />
** we used [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] to find the position of the word "exit" within the line<br />
** but [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] returns us the position of the first character of the word we want, while we want to have the text be right after it - so we find out how long our word is with <code>#("exit")</code>, add that to the number returned by [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] which gets us the first character + the length of the word - which isn't quite at the end of the word, but the word plus the space (because of [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] and the first character) - so we substract 1 to move our cursor right at the end of the word<br />
** we then use [[Manual:UI_Functions#getLineNumber|getLineNumber()]] to get the current line number, so our cursor is placed on the current line, at our desired position<br />
* lastly we finally insert the text with [[Manual:UI_Functions#insertText|insertText()]], which puts the text exactly where our virtual cursor is<br />
<br />
Done! You can also use [[Manual:UI_Functions#cinsertText|cinsertText()]] for coloured inserts, and other functions [[Manual:Scripting#Cursor_Movement_and_Cursor_Placement|mentioned above]] and in the [[Manual:UI_Functions|API manual]] to help you do what you'd like.<br />
<br />
==User defined dockable windows==<br />
<br />
You may want to use dock windows to display information you gathered in your scripts, or you may want to use them as chat windows etc. Check out [[Manual:Geyser#Geyser.UserWindow|Geyser.UserWindow]] on how to add them!<br />
<br />
==Dynamic Triggers==<br />
<br />
<code>triggerID = tempTrigger( substring pattern, code ) creates a fast substring matching trigger</code> <br />
<br />
<code>triggerID = tempRegexTrigger( regex, code ) creates a regular expression matching trigger</code><br />
<br />
<code>triggerID = tempBeginOfLineTrigger( begin of line pattern, code ) creates a fast begin of line substring trigger</code><br />
<br />
=Scripting howtos=<br />
==How to convert a string to value?==<br />
Say you'd like to capture a number from a trigger, but the capture always ends up being a "string" (or, just text on which you can't do any maths on) even if it's a number. To convert it to a number, you'd want to use the ''tonumber()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
myage = tonumber(matches[2])<br />
</syntaxhighlight><br />
<br />
==How to highlight my current target?==<br />
<br />
You can put the following script into your targetting alias:<br />
<br />
<syntaxhighlight lang="lua">if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
Where target is your target variable. Note that you have to use the full name, capitalized. If you’d like the script to auto-capitalize for you, you can use this version:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = target:title()<br />
if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
{{note}} Ensure you're on Mudlet 3.5.0+ so you can put ''function()'' in a ''[[Manual:Lua_Functions#tempTrigger|tempTrigger()]]''.<br />
<br />
==How to format an echo to a miniConsole?==<br />
<br />
One of the ways you can create multi-line displays in a miniConsole with variable information is with string.format and the use of [[ ]] brackets for text, which allow for multiple line in text:<br />
<br />
<syntaxhighlight lang="lua"><br />
local WindowWidth, WindowHeight = getMainWindowSize();<br />
createMiniConsole("sys",WindowWidth-650,0,650,300)<br />
<br />
local name, age, sex = "Bob", 34, "male"<br />
<br />
cecho("sys", string.format([[<br />
<br />
/---------\<br />
%s<br />
%dyrs<br />
sex - %s <br />
\---------/<br />
]], name, age, sex))<br />
</syntaxhighlight><br />
<br />
==How to play a sound when I receive communication while afk?==<br />
<br />
[[File:Play_sound_when_afk_trigger.png]]<br />
<br />
For this to work, place the line you'd like to trigger on in the first pattern box and select the appropriate pattern type. Then add ''return not hasFocus()'' with the Lua function as the second pattern, enable the AND trigger, and set the line delta to zero. Then just enable ''play sound'', choose your sound and you're set!<br />
<br />
==How can I make a key that toggles between commands?==<br />
To make a key that toggles between two actions, for example - sleep/wake, you can use this as the script:<br />
<br />
<syntaxhighlight lang="lua"><br />
if not sleeping then<br />
send("sleep")<br />
sleeping = true<br />
else<br />
send("wake")<br />
sleeping = false<br />
end<br />
</syntaxhighlight><br />
<br />
<!-- Old Heading: How can I make a trigger that goes off only if the next line is not a particular one? --><br />
==How can I make a trigger with a next-line condition?==<br />
<br />
Here's how you can set it up - replace ''line1'' and ''line2'' with appropriate lines.<br />
<br />
[[File:Trigger_multiline_not_another_example.png|center]]<br />
<br />
Here's [[Media:Match only of next line is *not* line2.xml.zip|the Mudlet XML]] you can download for this!<br />
<br />
==How to target self or something else?==<br />
<br />
[[File:Buffselforother.png|border|350px]]<br />
<br />
Using regex and an 'or' statement allows us to consolidate multiple aliases, or an if statement, into a single more simple alias. <br />
When a regex is found it will use it, but if you don't specify one then the alternative will be used. The use of 'or' can be used with any function in Mudlet.<br />
In this example, one can type "buff" to buff themself, or "buff ally" to buff their ally instead.<br />
<br />
<syntaxhighlight lang="lua"><br />
^buff(?: (\w+))?$<br />
<br />
send("cast buff on "..(matches[2] or "myself"))<br />
</syntaxhighlight><br />
<br />
==How to delete everything between two lines?==<br />
When deleteLine() is called, every following line shifts back in numerical position. Thus if we know where we're starting and how many lines to expect, we can use a for loop to gag everything between line a and b by leaving the cursor in one spot. In the below example, line_a_number is the number of the line you want to start at, and line_b_number is the ending line. To gag x number of lines instead, use line_a_number + x in place of line_b_number.<br />
<br />
<syntaxhighlight lang="lua"><br />
for i = line_a_number, line_b_number, 1<br />
do<br />
moveCursor(0, line_a_number)<br />
selectCurrentLine()<br />
deleteLine()<br />
end<br />
</syntaxhighlight><br />
<br />
== How to capture foreground line color information? ==<br />
Here's an example that loops through each character in a line of text and prints the character and its foreground color to a miniconsole if the color has changed from the previous character:<br />
<br />
Trigger: <code>^</code> (regex)<br />
<br />
Code:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer =<br />
miniconsoleContainer or Adjustable.Container:new({name = "miniconsoleContainer"})<br />
myMiniconsole =<br />
Geyser.MiniConsole:new(<br />
{<br />
name = "myMiniconsole",<br />
x = 0,<br />
y = 0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width = "100%",<br />
height = "100%",<br />
},<br />
miniconsoleContainer<br />
)<br />
<br />
local index = 0<br />
local line = getCurrentLine()<br />
local linesize = #line<br />
local currentlinenumber = getLineNumber()<br />
local r, g, b = 0, 0, 0<br />
local cr, cg, cb -- last seen colors<br />
while index < linesize do<br />
index = index + 1<br />
moveCursor("main", index, currentlinenumber)<br />
selectString(line:sub(index), 1)<br />
r, g, b = getFgColor()<br />
if cr ~= r or cg ~= g or cb ~= b then<br />
cr, cg, cb = r, g, b<br />
myMiniconsole:echo(string.format("rgb(%d,%d,%d)%s", r, g, b, line:sub(index, index)))<br />
else<br />
myMiniconsole:echo(string.format("%s", line:sub(index, index)))<br />
end<br />
line:sub(index, index)<br />
end<br />
myMiniconsole:echo("\n")<br />
</syntaxhighlight><br />
<br />
==How to enter a carriage return / enter command?==<br />
Say you'd like to gag the following line, and just continue ... <br />
<br />
[ Press Enter to continue ]<br />
<br />
<syntaxhighlight lang="lua"><br />
Trigger: [ Press Enter to continue ] (set to exact match)<br />
Code: deleteLine()<br />
send("\n")<br />
</syntaxhighlight><br />
<br />
==How to repeat commands with #?==<br />
Install the [https://forums.mudlet.org/viewtopic.php?f=6&t=1275 following alias], and with it <code>#5 mycommand</code> will get repeated five times.<br />
<br />
== How to move the command line over? ==<br />
<br />
To move the command line over to the right, create a new script and add the following to it:<br />
<br />
<syntaxhighlight lang="css"><br />
setCmdLineStyleSheet("main", [[<br />
QPlainTextEdit {<br />
padding-left: 100px; /* change 100 to your number */<br />
background-color: black; /* change it to your background color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
== How to add a background for Mudlets buttons? ==<br />
You can give Mudlets buttons a background to have them blend in with your UI by doing this:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- replace the /home/vadi/Pictures/tile.png location below with the one of your picture!<br />
-- you can download the sample tile.png from https://opengameart.org/content/bevouliin-free-game-background-for-game-developers<br />
local backgroundpath = [[/home/vadi/Pictures/tile.png]]<br />
-- Windows:<br />
-- local backgroundpath = [[C:/Users/Vadim/Downloads/Free game background/transparent PNG/tile.png]]<br />
<br />
setAppStyleSheet([[<br />
QToolBar {<br />
border-image: url(]]..backgroundpath..[[);<br />
<br />
}<br />
<br />
QToolBar QToolButton:!hover {<br />
color: white;<br />
}<br />
QToolBar QToolButton:hover {<br />
color: black;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
Result:<br />
<br />
[[File:Mudlet tiled buttons.png|frame|left]]<br />
<br clear=all><br />
<br />
= Advanced scripting tips =<br />
== Do stuff after all triggers/aliases/scripts are run ==<br />
This little snippet will have your commands be executed right after, depending on the context you run it in, all triggers, aliases or scripts are completed:<br />
<br />
<syntaxhighlight lang="lua">tempTimer(0, [[mycode]])</syntaxhighlight><br />
<br />
== How to delete the previous and current lines ==<br />
<br />
This little snippet comes from [http://forums.mudlet.org/viewtopic.php?f=9&t=2411&p=10685#p10685 Iocun]:<br />
<br />
<syntaxhighlight lang="lua"><br />
moveCursor(0,getLineCount()-1)<br />
deleteLine()<br />
moveCursor(0,getLineCount())<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=db: Mudlet's database frontend=<br />
<br />
The DB package is meant to provide easier access to a database, so you don’t have to know SQL or use the luasql module to set and get at your data. However, it does require that the luasql module be compiled and included in Mudlet to function.<br />
<br />
==Creating a Database==<br />
<br />
Before you can store anything in a database, you need to create one. You may have as many independent databases as you wish, with each having as many unique tables-- what we will call sheets in this package, so as to avoid confusion with Lua tables - think spreadsheets.<br />
<br />
To create a database, you use the db:create() function, passing it the name of your database and a Lua table containing its schema configuration. A schema is a mold for your database - it defines what goes where. Using the spreadsheet example, this would mean that you’d define what goes into each column. A simple example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes"}})<br />
</syntaxhighlight><br />
<br />
This will create a database which contains two sheets: one named friends, the other named enemies. Each has three columns, name, city and notes-- and the datatype of each are strings, though the types are very flexible and can be changed basically whenever you would like. It’ll be stored in a file named Database_people.db in your Mudlet config directory on the hard drive should you want to share it.<br />
<br />
It’s okay to run this function repeatedly, or to place it at the top-level of a script so that it gets run each time the script is saved: the DB package will not wipe out or clear the existing data in this case. <br />
<br />
{{Note}} You may not create a column or field name which begins with an underscore. This is strictly reserved to the db package for special use.<br />
<br />
{{Note}} Adding new columns to an existing database did not work in Mudlet 2.1 - see [[Manual:Lua_Functions#db:create|db:create()]] on how to deal with this.<br />
<br />
<!--<br />
More importantly, this allows you to add columns to an existing sheet. If you change that line to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes", "enemied"}})<br />
</syntaxhighlight><br />
<br />
It will notice that there is a new column on enemies, and add it to the existing sheet-- though the value will end up as nil for any rows which are already present. Similarly, you can add whole new sheets this way. It is not presently possible to -remove- columns or sheets without deleting the database and starting over.<br />
--><br />
<br />
==Adding Data==<br />
<br />
To add data to your database, you must first obtain a reference (variable) for it. You do that with the db:get_database function, such as:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("people")<br />
</syntaxhighlight><br />
<br />
The database object contains certain convenience functions (discussed later, but all are preceded with an underscore), but also a reference to every sheet that currently exists within the database. You then use the db:add() function to add data to the specified sheet.<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends, {name="Ixokai", city="Magnagora"})<br />
</syntaxhighlight><br />
<br />
If you would like to add multiple rows at once to the same table, you can do that by just passing in multiple tables:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends,<br />
{name="Ixokai", city="Magnagora"},<br />
{name="Vadi", city="New Celest"},<br />
{name="Heiko", city="Hallifax", notes="The Boss"}<br />
)<br />
</syntaxhighlight><br />
<br />
Notice that by default, all columns of every table are considered optional-- if you don’t include it in the add, then it will be set to its default value (which is nil by default)<br />
<br />
For those familiar with databases: with the DB package, you don’t have to worry about committing or rolling back any changes, it will commit after each action automatically. If you would like more control than this, see Transactions below.<br />
<br />
You also cannot control what is the primary key of any sheets managed with DB, nor do you have to create one. Each row will get a unique integer ID that automatically increments, and this field can be accessed as "_row_id".<br />
<br />
==Querying==<br />
<br />
Putting data in isn’t any fun if you can’t get it out. If you want every row from the sheet, you can do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends)<br />
</syntaxhighlight><br />
<br />
But rarely is that actually useful; usually you want to get only select data. For example, you only want to get people from the city of Magnagora. To do that you need to specify what criteria the system should use to determine what to return to you. It looks like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
So the basic command is - db:fetch(_sheet_, _what to filter by_)<br />
<br />
The following filter operations are defined:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:eq(field, value[, case_insensitive]) -- Defaults to case insensitive, pass true as the last arg to<br />
reverse this behavior.<br />
db:not_eq(field, value[, case_insensitive) -- Not Equal To<br />
db:lt(field, value) -- Less Than<br />
db:lte(field, value) -- Less Than or Equal to.<br />
db:gt(field, value) -- Greater Than<br />
db:gte(field, value) -- Greater Than or Equal To<br />
db:is_nil(field) -- If the column is nil<br />
db:is_not_nil(field) -- If the column is not nil<br />
db:like(field, pattern) -- A simple matching pattern. An underscore matches any single character,<br />
and a percent(%) matches zero or more characters. Case insensitive.<br />
db:not_like(field, pattern) -- As above, except it'll give you everything but what you ask for.<br />
db:between(field, lower_bound, upper_bound) -- Tests if the field is between the given bounds (numbers only).<br />
db:not_between(field, lower_bound, upper_bound) -- As above, only... not.<br />
db:in_(field, table) -- Tests if the field is in the values of the table. NOTE the trailing underscore!<br />
db:not_in(field, table) -- Tests if the field is NOT in the values of the table *<br />
</syntaxhighlight><br />
<br />
The db:in_ operator takes a little more explanation. Given a table, it tests if any of the values in the table are in the sheet. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:in_(mydb.friends.city, {"Magnagora", "New Celest"})<br />
</syntaxhighlight><br />
<br />
It tests if city == "Magnagora" OR city == "New Celest", but with a more concise syntax for longer lists of items.<br />
<br />
There are also two logical operators:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:AND(operation1, ..., operationN)<br />
db:OR(operation1, operation2)<br />
</syntaxhighlight><br />
<br />
You may pass multiple operations to db:fetch in a table array, and they will be joined together with an AND by default. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends,<br />
{db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "X%")}<br />
)<br />
</syntaxhighlight><br />
<br />
This will return every record in the sheet which is in the city of Magnagora, and has a name that starts with an X. Again note that in LIKE patterns, a percent is zero or more characters — this is the same effect as "X.*" in pcre patterns. Similarly, an underscore matches any single characters and so is the same as a dot in pcre.<br />
<br />
Passing multiple expressions in an array to db:fetch is just a convenience, as its exactly the same as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:AND(db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "I%")))<br />
</syntaxhighlight><br />
<br />
The db:OR operation only takes two arguments, and will check to see if either of the two is true. You can nest these logical operators as deeply as you need to.<br />
<br />
You can also just pass in a string directly to db:fetch, but you have to be very careful as this will be passed straight to the SQL layer. If you don’t know any SQL then you want to avoid this… for example, in SQL there’s a very big difference between double and single quotes. If you don’t know that, then stick to the db functions. But an example is:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, "city == 'Magnagora'")<br />
</syntaxhighlight><br />
<br />
Now, the return value of db:fetch() is always a table array that contains a table dictionary representing the full contents of all matching rows in the sheet. These are standard Lua tables, and you can perform all normal Lua operations on them. For example, to find out how many total items are contained in your results, you can simply do #results. If a request from the friends sheet were to return one row that you stored in the results variable, it would look like this if passed into the display() function:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'name': 'Bob',<br />
'city': 'Magnagora',<br />
'notes': 'Trademaster of Tailoring'<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
And if you were to echo(#results), it would show 1.<br />
<br />
The order of the returned rows from db:fetch is generally the same as the order in which you entered them into the database, but no actual guarantees are made to this. If you care about the order then you can pass one or two optional parameters after the query to db:fetch() to control this.<br />
<br />
The first table is an array of fields that indicate the column names to sort by; the second is a flag to switch from the default ascending(smallest to largest) sort, to a descending(largest to smallest) sort. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city})<br />
</syntaxhighlight><br />
<br />
This will return all your friends in Magnagora, sorted by their name, from smallest to largest. To reverse this, you would simply do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city}, true)<br />
</syntaxhighlight><br />
<br />
Including more then one field in the array will indicate that in the case that two rows have the same value, the second field should be used to sort them.<br />
<br />
If you would like to return ALL rows from a sheet, but still sort them, you can do that by passing nil into the query portion. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, nil, {mydb.friends.city, mydb.friends.name})<br />
</syntaxhighlight><br />
<br />
This will return every friend you have, sorted first by city and then their name.<br />
<br />
==Indexes and Types==<br />
<br />
The sheets we’ve defined thus far are very simple, but you can take more control over the process if you need to. For example, you may assign default values and types to columns, and the DB package will attempt to coerce them as appropriate. To do that, you change your db:create() call as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
This is almost the same as the original definition, but we’ve defined that our first four fields are strings with a default value of blank, and the new kills field which is an integer that starts off at 0. The only way to set a datatype is to set a default value at this time.<br />
<br />
Please note, beneath the DB package is SQLite, and SQLite is very data-type neutral. It doesn’t really care very much if you break those rules and put an integer in a string field or vice-versa, but the DB package will — to a limited degree — attempt to convert as appropriate, especially for the operations that work on numbers.<br />
<br />
You may also create both standard and unique indexes. A unique index enforces that a certain criteria can only happen once in the sheet. Now, before you go and make indexes, pause and consider. There is no right or wrong answer when it comes to what to index: it depends on what kind of queries you do regularly. If in doubt, don’t make an index. Indexes will speed up reading data from the sheet, but they will slow down writing data.<br />
<br />
To add an index, pass either the _index or _unique keys in the table definition. An example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" }<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Now, bear in mind: _index = { "name", "city"} creates two indexes in this sheet. One on the city field, one on the name field. But, _index = { {"name", "city"} } creates one index: on the combination of the two. Compound indexes help speed up queries which frequently scan two fields together, but don’t help if you scan one or the other.<br />
<br />
The admonition against making indexes willy-nilly holds double for compound indexes: do it only if you really need to!<br />
<br />
===Uniqueness===<br />
<br />
As was specified, the _unique key can be used to create a unique index. This will make it so a table can only have one record which fulfills that index. If you use an index such as _unique = { "name" } then names must be unique in the sheet. You can specify more than one key to be unique; in that case they will be checked in an OR condition.<br />
<br />
Now, if you use db:add() to insert a record which would violate the unique constraint, a hard error will be thrown which will stop your script. Sometimes that level of protection is too much, and in that case you can specify how the db layer handles violations.<br />
<br />
There are three possible ways in which the layer can handle such violations; the default is to FAIL and error out.<br />
<br />
You can also specify that the db layer should IGNORE any commands that would cause the unique constraint to be violated, or the new data should REPLACE the existing row.<br />
<br />
For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento"})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the name field being declared to be unique, these two commands can’t succeed normally. The first db:add() will create a record with the name of Bob, and the second would cause the uniqueness of the name field to be violated. With the default behavior (FAIL), the second db:add() call will raise an error and halt the script.<br />
<br />
If you want the IGNORE behavior, the second command will not cause any errors and it will simply fail silently. Bob’s city will still be Sacramento.<br />
<br />
With the REPLACE behavior, the second command will cause its data to completely overwrite and replace the first record. Bob’s city will now be San Francisco.<br />
<br />
A word of caution with REPLACE, given:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento", notes="This is something."})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the REPLACE behavior, the second record will overwrite the first-- but the second record does not have the notes field set. So Bob will now not have any notes. It doesn’t -just- replace existing fields with new ones, it replaces the entire record.<br />
<br />
To specify which behavior the db layer should use, add a _violations key to the table definition:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" },<br />
_violations = "IGNORE"<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Note that the _violations behavior is sheet-specific.<br />
<br />
===Timestamps===<br />
<br />
In addition to strings and floats, the db module also has basic support for timestamps. In the database itself this is recorded as an integer (seconds since 1970) called an epoch, but you can easily convert them to strings for display, or even time tables to use with Lua’s built-in time support.<br />
<br />
The most common use for the Timestamp type is where you want the database to automatically record the current time whenever you insert a new row into a sheet. The following example illustrates that:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:create("combat_log",<br />
{<br />
kills = {<br />
name = "",<br />
area = "",<br />
killed = db:Timestamp("CURRENT_TIMESTAMP"),<br />
_index = { {"name", "killed"} }<br />
}<br />
}<br />
)<br />
<br />
-- observe that we don't provide the killed field here - DB automatically fills it in for us.<br />
db:add(mydb.kills, {name="Drow", area="Undervault"})<br />
<br />
results = db:fetch(mydb.kills)<br />
display(results)<br />
</syntaxhighlight><br />
<br />
The result of that final display would show you this on a newly created sheet:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'_row_id': 1<br />
'area': 'Undervault'<br />
'name': 'Drow'<br />
'killed': table {<br />
'_timestamp': 1264317670<br />
}<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
As you can see from this output, the killed fields contains a timestamp-- and that timestamp is stored as an epoch value in the GMT timezone. For your convenience, the db.Timestamp type offers three functions to get the value of the timestamp in easy formats. They are <code>as_string</code>, <code>as_number</code> and <code>as_table</code>, and are called on the timestamp value itself.<br />
<br />
The as_number function returns the epoch number, and the as_table function returns a time table. The as_string function returns a string representation of the timestamp, with a default format of "%m-%d-%Y %H:%M:%S". You can override this format to anything you would like. Details of what you can do with epoch values, time tables, and what format codes you can use are specified in the Lua manual at: http://www.lua.org/pil/22.1.html for the Lua date/time functions.<br />
<br />
A quick example of the usage of these functions is:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.kills)<br />
for _, row in ipairs(results) do<br />
echo("You killed " .. row.name .. " at: " .. (row.killed and row.killed:as_string() or "no time") .."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==Deleting==<br />
<br />
The db:delete function is used to delete rows from the sheet. It takes two arguments, the first being the sheet you are deleting and the second a query string built using the same functions used to build db:fetch() queries.<br />
<br />
For example, to delete all your enemies in the city of Magnagora, you would do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these! You may inadvertantly wipe out huge chunks of your sheets if you don’t have the query parameters set just to what you need them to be. Its advised that you first run a db:fetch() with those parameters to test out the results they return.<br />
<br />
As a convenience, you may also pass in a result table that was previously retrieved via db:fetch and it will delete only that record from the table. For example, the following will get all of the enemies in Magnagora, and then delete the first one:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
db:delete(mydb.enemies, db:eq(mydb.enemies._row_id, results[1]._row_id))<br />
</syntaxhighlight><br />
<br />
That is equivalent to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
You can even pass a number directly to db:delete if you know what _row_id you want to purge.<br />
<br />
A final note of caution: if you want to delete all the records in a sheet, you can do so by only passing in the table reference. To try to protect you from doing this inadvertently, you must also pass true as the query after:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, true)<br />
</syntaxhighlight><br />
<br />
==Updating==<br />
<br />
If you make a change to a table that you have received via db:fetch(), you can save those changes back to the database by doing:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:update(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
A more powerful (and somewhat dangerous, be careful!) function to make changes to the database is db:set, which is capable of making sweeping changes to a column in every row of a sheet. Beware, if you have previously obtained a table from db:fetch, that table will NOT represent this change.<br />
<br />
The db:set() function takes two arguments: the field to change, the value to set it to, and the db:fetch() like query to indicate which rows should be affected. If you pass true as the last argument, ALL rows will be changed.<br />
<br />
To clear out the notes of all of our friends in Magnagora, we could do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:set(mydb.friends.notes, "", db:eq(mydb.friends.notes, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these!<br />
<br />
==Transactions==<br />
<br />
As was specified earlier, by default the db module commits everything immediately whenever you make a change. For power-users, if you would like to control transactions yourself, the following functions are provided on your database instance:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("my_database")<br />
mydb:_begin()<br />
mydb:_commit()<br />
mydb:_rollback()<br />
mydb:_end()<br />
</syntaxhighlight><br />
<br />
Once you issue a mydb._begin() command, autocommit mode will be turned off and stay off until you do a mydb._end(). Thus, if you want to always use transactions explicitly, just put a mydb._begin() right after your db:create() and that database will always be in manual commit mode.<br />
<br />
==Viewing and editing the database contents==<br />
<br />
A good tool to view and edit the database contents in raw form is [http://afoucal.free.fr/index.php/applications/sqlite-sorcerer/ SQlite Sorcerer] (free and available for Linux, Windows, Mac).<br />
<br />
==Debugging raw queries==<br />
<br />
If you'd like to see the queries that db: is running for you, you can enable debug mode with ''db.debug_sql = true''.<br />
<br />
=Discord Messenges=<br />
<br />
Can you send messenges from Mudlet to Discord? Totally. Here is an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
function sendToDiscord(data)<br />
local url = "https://discord.com/api/webhooks/1204151397977821184/Cu8ZQQo9R11AyIt3DxpOEeB8MtVMA6_AEfXoZaYxqEAOu_6hwhtA2cRLIw-VIs7py7p8"<br />
local headers = {["Content-Type"] = "application/json"}<br />
local json = yajl.to_string(data)<br />
postHTTP(json, url, headers)<br />
end<br />
<br />
local data = {<br />
content = "Hello, Discord!",<br />
embeds = {<br />
{<br />
title = "This is an embed",<br />
url = "https://example.com",<br />
image = {<br />
url = "https://example.com/image.jpg"<br />
}<br />
}<br />
}<br />
}<br />
<br />
sendToDiscord(data)<br />
<br />
</syntaxhighlight><br />
<br />
Sure enough, after starting this script, you can see a message in Discord:<br />
<br />
(add pic to illustrate the result)<br />
<br />
What you just need to do is create a webhook in a channel. Go to channel settings, then create this:<br />
<br />
(pic displaying the setup webhook)<br />
<br />
Here you can find more documentation on which fields Discord allows: https://discord.com/developers/docs/resources/webhook#execute-webhook<br />
<br />
All this is one way though. Mudlet won't listen to messages from Discord. For that you'd probably have to make a Discord bot first.<br />
<br />
=Discord Rich Presence=<br />
[[File:Rich_Presence_Midmud.gif|frame]]<br />
<!-- [[File:Rich Presence Achaea.gif|frame]] --><br />
<br />
Discord Rich Presence in Mudlet allows you, the player, to show off the game you're playing and you, the game author, to get your game shown off! Advertise your game for free alongside AAA titles in server player lists :)<br />
<br />
To respect the players privacy, this option is disabled by default - enable it by ticking the Discord option for the profile:<br />
<br />
[[File:Enable Discord.png|border|center]]<br />
<br />
Once enabled, a Discord-capable game will show information in your Discord!<br />
<br />
To fine-tune the information you'd like to see displayed, go to Settings, Chat tab:<br />
<br />
[[File:Discord Privacy.png|center|400px]]<br />
<br />
== Implementing ==<br />
As a game author, you have two ways of adding Discord support to your game: via GMCP (easy) or via Lua.<br />
<br />
Adding support via GMCP means that your players don't have to install any Lua scripts which is a nicer experience. To do so, implement the [[Standards:Discord_GMCP|Discord over GMCP]] specification and [https://www.mudlet.org/contact/ get in touch] to let us know your game implements GMCP.<br />
<br />
=== GMCP ===<br />
Here's a quick cheatsheet to implement the [[Standards:Discord_GMCP|GMCP spec]]:<br />
<br />
# Create a discord [https://discordapp.com/developers/applications/me application]<br />
# Upload game logo for "rich presence invite image"<br />
# Upload same game logo in "Rich Presence Assets" with the name of <code>server-icon</code><br />
# Upon receiving "External.Discord.Hello" from the game client, reply with "External.Discord.Info" with <code>applicationid</code> ([[:File:Mudlet Discord ApplicationID.png|see screenshot]]) and "External.Discord.Status" <br />
# Send "External.Discord.Status" whenever you need to send data to the client, and fill it with the values have changed since the last status. Discord has [https://discordapp.com/developers/docs/rich-presence/best-practices#tips some ideas] for filling it in.<br />
# Done. Mudlet will enable the Discord checkbox upon receiving the <code>applicationid</code> from the game at least once.<br />
<br />
=== Lua ===<br />
An alternative way to add Discord support as a game author is [[Manual:Discord_Functions|via Lua]] - all of Discords functionality can be manipulated from it. Create a discord [https://discordapp.com/developers/applications/me application] and set it with [[Manual:Discord_Functions#setDiscordApplicationID|setDiscordApplicationID()]], then set the set the rest of the options as necessary:<br />
<br />
[[File:Discord fields.png|frame|center|Credit: Discord]]<br />
<br />
If you're a game player and your game doesn't support Discord, you can still use the functionality to set the detail, status, party and time information as desired.<br />
<br />
{{MudletVersion|3.14}}<br />
<br />
=MUD Client Media Protocol=<br />
<br />
==Client.Media==<br />
Want to add accessibility and excitement into your game? How about implementing sound and music via GMCP?<br />
<br />
The Client.Media family of GMCP packages provide a way for games to send sound and music events. GMCP media events are sent in one direction: from game server to to game client.<br />
<br />
===Client.Media in Mudlet===<br />
<br />
Media files may be downloaded manually or automatically if certain conditions are met.<br />
<br />
{{MudletVersion|4.4}}<br />
<br />
Mudlet accepts case-insensitive GMCP for the Client.Media namespace (for example, these are all acceptable: "Client.Media.Play", "client.media.play", "cLiEnT.MeDiA.Play").<br />
<br />
===Enabling Media===<br />
When a new profile opens, Mudlet adds to the Core.Supports.Set GMCP package "Client.Media 1" to signal to servers that it supports processing media files via GMCP:<br />
<br />
<syntaxhighlight lang="json"><br />
Core.Supports.Set ["Client.Media 1", ...]<br />
</syntaxhighlight><br />
<br />
To process Client.Media GMCP data in Mudlet, these boxes in the Settings window of Mudlet must be checked:<br />
<br />
# The "Enable GMCP" box in the Miscellaneous section.<br />
# The "Allow server to download and play media" box in the Game protocols section.<br />
<br />
These boxes are checked by default upon the start of a new profile in Mudlet.<br />
<br />
===Storing Media===<br />
<br />
Mudlet plays files cached in the "media" folder within a game's profile. To get files into the "media" folder you could perform either of these options:<br />
<br />
# Copy media files or extract them from an archive (zip)<br />
# Automatically download them from external resources such as your game's web server on the Internet.<br />
<br />
To enable the second option (Internet), use the "url" parameter made available in the "Client.Media.Default", "Client.Media.Load" and "Client.Media.Play" GMCP packages described below.<br />
<br />
===Loading Media===<br />
<br />
Send a '''Client.Media.Default''' GMCP event to setup the default URL directory to load sound or music files from external resources. This would typically be done once upon player login. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
|-<br />
|}<br />
<br />
For example, to setup the default URL directory for your game:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Default {<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
If downloading from external resources, it is recommended to use Client.Media.Default, set this default URL directory once, and let Mudlet download all of your media files automatically from this one resource location. Otherwise, explicitly set the "url" parameter on all of your Client.Media.Load GMCP and Client.Media.Play GMCP events to ensure that files are downloaded from the intended location(s).<br />
<br />
Send '''Client.Media.Load''' GMCP events to load sound or music files. This could be done when the player logs into your game or at the beginning of a zone that will need the media.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if a url was not set above with Client.Media.Default.<br />
|-<br />
|}<br />
<br />
For example, download the sound of a sword swooshing within the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Load {<br />
"name": "sword1.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
===Playing Media===<br />
<br />
Send '''Client.Media.Play''' GMCP events to play sound or music files.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely and a url was not set above with Client.Media.Default or Client.Media.Load.<br />
|-<br />
| style="text-align:center;"| No<br />
| "type"<br />
| "sound" or "music"<br />
| "sound"<br />
| style="text-align:left;"|<br />
* Identifies the type of media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "tag"<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "volume"<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| "fadein"<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"fadeout"<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| "start"<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
* 1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"loops"<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the sound or music to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a lower priority while this media plays.<br />
|-<br />
| style="text-align:center;" |No<br />
|"continue"<br />
| true or false<br />
|true<br />
| style="text-align:left;" |<br />
*Only valid for media files with a "type" of "music".<br />
*Continues playing matching new music files when true.<br />
*Restarts matching new music files when false.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
|}<br />
<br />
==== name====<br />
<br />
For example, to simply play the sound of a cow mooing already stored in the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Or some lightning stored in a "weather" sub-folder under the "media" folder.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "weather/lightning.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
The "name" parameter may be used for stopping media with the Client.Media.Stop GMCP event.<br />
<br />
====url====<br />
<br />
If you maintain your sound files on the Internet and don't set a default URL with Client.Media.Default, or preload them with Client.Media.Load, include the "url" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
====type: sound====<br />
<br />
Media files default to a "type" of "sound" when the "type" parameter is not specified, such as in the example above. It is good practice to specify the "type" parameter to best keep media organized within your implementation:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====tag====<br />
<br />
To play the sound of a sword swooshing and categorized as "combat":<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat"<br />
}<br />
</syntaxhighlight><br />
<br />
The "tag" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====type: music====<br />
<br />
Add background music to your environment through use of the "music" value set upon the "type" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====volume: 1 to 100====<br />
<br />
As the character draws nearer to or farther from the environmental feature, consider adjusting the "volume" parameter. Example values, followed by syntax examples:<br />
<br />
*Maximum: 100 (recommended to use rarely)<br />
*High: 75<br />
*Default: 50<br />
* Low: 25<br />
* Minimum: 1 (recommended to use rarely)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment",<br />
"volume": 75<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "volume" values of type string ("75") into integers (75) as needed.<br />
<br />
====fadein====<br />
<br />
Increase volume from the start of the media [start position, volume one] to the number in milliseconds specified with the "fadein" parameter [position start + milliseconds, volume specified with the "volume" parameter]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade in)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "monty_python.mp3",<br />
"type": "music",<br />
"volume": 100,<br />
"fadein": 1000<br />
}<br />
</syntaxhighlight><br />
+---------------------------+-----------------------+<br />
| Fade in 1000 milliseconds | Normal |<br />
+---------------------------+-----------------------+<br />
Volume 1|........::::::::::iiiiiiiii%%%%%%%%%%%%%%%%%%%%%%%%|Volume 100<br />
+---------------------------+-----------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadein" values of type string ("1000") into integers (1000) as needed.<br />
<br />
==== fadeout====<br />
<br />
Decrease volume from a position in milliseconds subtracted from the duration of the media [position duration - milliseconds, volume specified with the "volume" parameter] to the end of the media [position duration, volume one]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade out)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "the_matrix.mp3",<br />
"type": "music",<br />
"volume": 50,<br />
"fadeout": 333<br />
}<br />
</syntaxhighlight><br />
+-----------------------+---------------------------+<br />
| Normal | Fade out 333 milliseconds |<br />
+-----------------------+---------------------------+<br />
Volume 50|%%%%%%%%%%%%%%%%%%%%%%%%iiiiiiiii::::::::::........|Volume 1<br />
+-----------------------+---------------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadeout" values of type string ("333") into integers (333) as needed.<br />
<br />
==== start ====<br />
<br />
Start playing a media track at the number of milliseconds specified. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (start from beginning)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "mudlet_beatboxing.mp3",<br />
"type": "music",<br />
"volume": 75,<br />
"start": 1000<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "start" values of type string ("100") into integers (100) as needed.<br />
<br />
==== loops: -1, 1 or more ====<br />
<br />
The "loops" parameter controls how many times the sound repeats and defaults to 1 if not specified. A value of -1 will loop the file indefinitely.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "clock/hour_bell.wav",<br />
"type": "sound",<br />
"loops": 3<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "underdark.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "loops" values of type string ("-1") into integers (-1) as needed.<br />
<br />
==== priority: 1 to 100 ====<br />
<br />
The "priority" parameter sets precedence for Client.Media.Play GMCP events that include a "priority" setting. The values for the "priority" parameter range between 1 and 100. Given that two Client.Media.Play GMCP events have the same priority, the media already playing will continue playing. In Mudlet, media without priority set is not included comparisons based on priority.<br />
<br />
A common place to find priority implemented is with combat. In the following example, imagine a combat scenario where some sounds of sword thrusts were interrupted by a successful blocking maneuver.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3,<br />
"priority": 60<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "block1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"priority": 70<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "priority" values of type string ("25") into integers (25) as needed.<br />
<br />
The "priority" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====continue: true or false (for music)====<br />
<br />
Typically sent with the "type" of "music" is the parameter "continue", which presents the following values:<br />
<br />
*true: continues music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
*false: restarts music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "city.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"continue": true<br />
}<br />
</syntaxhighlight><br />
<br />
If the "continue" parameter is not specified, behavior will default to ''true'' for music.<br />
<br />
Although using the boolean type is recommended, Mudlet parses "continue" values of type string ("true" and "false") into boolean (''true'' and ''false'') as needed, as not all game drivers support a boolean type.<br />
<br />
==== key====<br />
<br />
The "key" parameter enables media categorization, similar to the "tag" parameter, however it adds a feature of uniqueness that halts media currently playing with the same key, replacing it with the media that arrived from a new Client.Media.Play GMCP event. This update will only occur if the "name" or "url" associated with the currently playing media does not match the new media, while the key is identical.<br />
<br />
In the example below, consider that a player moves from a sewer area to a village. The "key" parameter is used to stop the previously playing ''sewer.mp3'' and start playing ''village.mp3'' within the second Client.Media.Play GMCP event. <br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sewer.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "village.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
The "key" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
{{note}} Where music is bound to change, continue or stop as a player enters a new room, consider allowing for a slight pause of 1 heart beat or tick to send the Client.Media.Play or Client.Media.Stop GMCP events. This practice reduces the number of Client.Media.Play GMCP events sent when the player travels through several rooms quickly.<br />
<br />
==== randomization====<br />
<br />
Wildcards ''*'' (asterisk) and ''?'' (question mark) may be used within the name to randomize media file(s) selection.<br />
<br />
Given that media files underdark.wav, underdark.mp3 and underdark_dark_elven_moshpit.mp3 were all present in the media/environment directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play using the ''*'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "underdark*",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": false<br />
}<br />
</syntaxhighlight><br />
<br />
If media files sword1.wav, sword2.wav and sword3.wav were all present in the media/combat directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play per each loop using the ''?'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "combat/sword?.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3<br />
}<br />
</syntaxhighlight><br />
<br />
=== Stopping Media ===<br />
<br />
Send '''Client.Media.Stop''' GMCP events to stop sound or music media.<br />
<br />
{| class="wikitable"<br />
!Required<br />
!Key<br />
!Value<br />
! style="text-align:left;" |Purpose<br />
|-<br />
| style="text-align:center;" | No<br />
| "name"<br />
|<file name><br />
| style="text-align:left;" |<br />
*Stops playing media by name matching the value specified.<br />
|-<br />
| style="text-align:center;" | No<br />
|"type"<br />
|"sound" or "music"<br />
| style="text-align:left;" | <br />
*Stops playing media by type matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
| "tag"<br />
|<tag><br />
| style="text-align:left;" |<br />
*Stops playing media by tag matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
| style="text-align:left;" |<br />
*Stops playing media with priority less than or equal to the value.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
| style="text-align:left;" | <br />
*Stops playing media by key matching the value specified.<br />
|-<br />
|}<br />
<br />
====all====<br />
<br />
Send the Client.Media.Stop GMCP event with no parameters to stop all playing media within a given game profile.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {}<br />
</syntaxhighlight><br />
<br />
====parameters====<br />
<br />
Send any combination of the name, type, tag, priority or sound parameters and valid corresponding values to stop playing media that matches ''all'' combinations of the parameters.<br />
<br />
Stop the rain.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"name": "rain.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media using the "type" of "sound".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "tag" of "combat" ''and'' that has a "priority" less than or equal to 50.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"tag": "combat",<br />
"priority": 50<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "key" of "area-music".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
=GUI Scripting in Mudlet=<br />
Mudlet has extremely powerful GUI capabilities built into it, and with the inclusion of the Geyser and Vyzors layout managers in Mudlet's Lua API it is quicker and easier to get a basic UI created.<br />
<br />
==Geyser==<br />
Geyser is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
Geyser's manual is quite extensive - [[Manual:Geyser|follow here]] to read up on it.<br />
<br />
===UI template===<br />
Akaya has created a UI template based on Geyser that can serve as a quick start for customizing the Mudlet interface to your character:<br />
<br />
[[File:Geyser UI template.png|center|800px|border]]<br />
<br />
To get started with it, see the forum thread about [http://forums.mudlet.org/viewtopic.php?f=6&t=4098 Geyser UI Template].<br />
<br />
==Simple Window Manager==<br />
Simple Window Manager is a light-weight script designed to provide the GUI object placement and sizing functionality seen in Geyser and Vyzor without any of the extras. Any GUI object, once created normally, can be added to the SWM along with a corner to base its positioning info off of, the distance from that corner, and the size of the object in any combination of pixels and percentages of the screen. SWM does all the behind the scenes work to keep all objects it has been given to manage in their correct places and sizes as the screen changes size. All other interactions with GUI objects are handled using standard functions built into Mudlet.<br />
<br />
Simple Window Managers manual, and download, can be [http://forums.mudlet.org/viewtopic.php?f=6&t=3529 found here].<br />
<br />
==Useful Resources==<br />
There are several useful resources you can refer to when creating your GUI.<br />
<br /><br />
<br />
;Wiki Resources<br />
*[[Manual:Geyser|Geyser Tutorial]]:<br />
:Excellent for getting an initial feel of how to use the Geyser layout manager.<br />
*[[Manual:Lua_Functions#UI_Functions|GUI API]]:<br />
:The GUI section of the Lua API manual<br />
;External Resources<br />
*[http://forums.mudlet.org/viewforum.php?f=11 Geyser subforum]:<br />
:The Geyser Layout Manager subforum on Mudlet's forums.<br />
*[http://forums.mudlet.org/viewtopic.php?f=5&t=1376 GUI Screenshots]:<br />
:A pinned thread on Mudlet's forums for showing what your GUI looks like. Useful for ideas and to see what is possible.<br />
*[http://forums.mudlet.org/viewtopic.php?f=9&t=1974 Godwars II Mudlet UI]:<br />
:A forum thread which follows the evolution of the UI provided by [http://www.godwars2.org God Wars II]<br />
[[Category:Mudlet Manual]]<br />
<br />
==Resetting your UI==<br />
While scripting your UI, you can reset it completely and have your scripts be loaded from scratch with the [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] function - in the input line, type <code>lua resetProfile()</code>.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Scripting&diff=20903Manual:Scripting2024-02-05T20:54:57Z<p>Kebap: /* Discord Messenges */ adding new section</p>
<hr />
<div>{{TOC right}}<br />
=Scripting with Mudlet=<br />
<br />
Lua tables can basically be considered multidimensional arrays and dictionaries at the same time. If we have the table matches, matches[2] is the first element, matches[n+1] the n-th element.<br />
<br />
<syntaxhighlight lang="lua"><br />
a = "Tom"<br />
matches[2] = "Betty"<br />
b = matches[2]<br />
c = a .. b and e will equal "TomBetty"<br />
</syntaxhighlight><br />
<br />
To output a table you can use a convenience function - ''display(mytable)'', which is built into Mudlet.<br />
<br />
==Lua interface functions - triggers, timers etc.==<br />
<br />
How to get data from regex capture groups? Regular expression capture groups (e.g. "(\d+)" ) are passed on to Lua scripts as a Lua table matches. To make use of this information inside Lua scripts, you need to specify the number of the capture group within the regex.<br />
<br />
<code>Example: You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
This regex contains 3 capture groups, but only the 2 green colored ones contain data as the red capture group is a non-capturing group. Consequently, your Lua script gets passed only 2 instead of 3 capture groups and matches[4] is undefined.<br />
<br />
In your Lua script you may write following program in order to print the number and status of your weapons on the screen:<br />
<br />
<code>You have (\d+) weapons and they are (?:(\b\w+\W+)+)</code><br />
<br />
<syntaxhighlight lang="lua"><br />
number_of_weapons = matches[2]<br />
status_of_weapons = matches[3]<br />
notice = number_of_weapons .. status_of_weapons<br />
echo( notice )<br />
send( "put weapons in backpack" )<br />
<br />
-- the following 2 lines color the first capture<br />
-- group red and the second group blue<br />
-- see below for details<br />
<br />
selectCaptureGroup( 2 )<br />
setFgColor( 255,0,0 )<br />
<br />
selectCaptureGroup( 3 )<br />
setFgColor( 0,0,255 )</syntaxhighlight><br />
<br />
The best way is to use selectCaptureGroup( number ) to select the proper capture group and then perform your actions on it e.g. replace(), highlight etc. Note: Both selectCaptureGroup() and matches[n] start with group 1 (which is the whole match. The defined capture groups start with 2).<br />
<br />
How to select all occurrences of "Tom" and highlight them?<br />
<br />
You add a function like this to a script containing you main function definitions. Note that script items differ from all other "scripts" in triggers, timers, actions etc. because they require you to put your code in proper functions that can be called by your other trigger-scripts, timer-scripts etc. via normal function calls. Trigger-scripts, timer-scripts etc. cannot contain any function definitions because they are automatically generated functions themselves because this makes usage a lot easier.<br />
<br />
To come back to our question how to select all occurrences of "Tom" and highlight them:<br />
<br />
<syntaxhighlight lang="lua"><br />
function setBgColorAll( word, r, g, b )<br />
i = 0<br />
word_count = 1<br />
while i > -1 do<br />
i = selectString(word, word_count)<br />
if i == -1 then<br />
return<br />
end<br />
word_count = word_count +1<br />
setBgColor( r, g, b )<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
Then you simply define a substring matching trigger on the word "Tom" and in the trigger script you call above function:<br />
<br />
<syntaxhighlight lang="lua">setBgColorAll("Tom", 255,50,50)</syntaxhighlight><br />
<br />
Since Mudlet 4.11+ it is possible to use name capture groups. You can verify if feature availability by checking <code>mudlet.supports.namedPatterns</code> flag.<br />
Let's say you have multiple patterns that you want to handle with one code.<br />
<br />
<code>^My name is (?<name>\w+)\. My class is (?<class>\w+)\.</code><br />
<br />
<code>^I am (?<class\w+)\ and my name is (?<name>\w+)\.</code><br />
<br />
Notice that class and name come in different order, therefore in first case we will have name under <code>matches[2]</code> and in second case under <code>matches[3]</code>.<br />
With named capture groups in both cases we will have name available under <code>matches.name</code> and class under <code>matches.class</code>.<br />
<br />
Code example to handle named matches above:<br />
<syntaxhighlight lang="lua"><br />
echo("Name: " .. matches.name .. "\n")<br />
echo("Class: " .. matches.class .. "\n")<br />
</syntaxhighlight><br />
<br />
==Sending commands or printing information messages==<br />
<br />
To print information messages on the session screen you can use the echo( message ) function, or insertText( text ). Currently, it only takes one string as argument.<br />
<br />
To send a command to the MUD, you can use the send( command ) function. In Alias scripts the command that is being sent to the MUD is contained in the variable command that you can change in the context of Alias scripts. Alias take regular expressions, as well. As a result, you can use following regex and script to talk like Yoda: Perl regex:<br />
<br />
<code> say (\w+).*(\w*).*(.*) </code><br />
<br />
script:<br />
<br />
<syntaxhighlight lang="lua"><br />
send( "say " .. matches[4] .." " .. matches[2] .." ".. matches[3] )<br />
</syntaxhighlight><br />
<br />
Note: The variable "command" contains what was entered in the command line or issued via the expandAlias( ) function. If you use expandAlias( command ) inside an alias script the command would be doubled. You have to use send( ) inside an alias script to prevent recursion. This will send the data directly and bypass the alias expansion.<br />
<br />
===Changing and formatting text from the MUD===<br />
<br />
When sending commands to the MUD - from now on referred to as output stream - alias scripts find the command that was issued by the user stored in the variable "command".<br />
<br />
By manipulating the value, the command can easily be changed before it is being sent to the MUD.<br />
<br />
However, things get much more complicated with the data received from the MUD, from now on referred to as input stream. Before triggers can be run on the MUD data, Mudlet has to strip all format codes from the text and store it in data structures associated with the text. Consequently, the text that is being passed on to the trigger processing unit is a small subset of the data received from the MUD. If you want to edit, replace, delete or reformat text from within your trigger scripts you have to keep this in mind if you don’t want to lose all text format information such as colors etc.<br />
<br />
As the text is linked with data structures containing the format of the text, the cursor position inside the line is important if data is being changed. You select a word or a sequence of characters from the line and then issue commands to do actions on the selected data.<br />
<br />
Replacing the word "Tom" with "Betty" in the line: Jim, Tom and Lucy are learning a new spell. This could be done with following script:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Tom",1)<br />
replace("Betty")<br />
</syntaxhighlight><br />
<br />
Things get more complicated if there are two or more occurrences of "Tom" in the line e.g. Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
The above example code would select the first occurrence of "Tom" in this line and ignore the second. If you want to work on the the second occurrence of "Tom" you have to specify the occurrence number in the call to select().<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString( "Tom", 2 )<br />
replace( "Betty" )<br />
</syntaxhighlight><br />
<br />
This code would change the second "Tom" and leave the first "Tom" alone. The function call<br />
<br />
<syntaxhighlight lang="lua">replaceAll( "Betty" )</syntaxhighlight><br />
<br />
will replace all occurrences of "Tom" with "Betty" in the line if "Tom" has been selected before. replaceAll() is a convenience function defined in LuaGlobal.lua.<br />
<br />
Colorization example: You want to change to color of the words "ugly monster" to red on a white background.<br />
<br />
You add a new trigger and define the regex: ugly monster In the script you write:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("ugly monster", 1 )<br />
setFgColor(255,0,0)<br />
setBgColor(255,255,255)<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
Another means to select text is to select a range of characters by specifying cursor positions. If we have following line: Jim and Tom like magic. Jim, Tom and Lucy are learning a new spell.<br />
<br />
<syntaxhighlight lang="lua">selectSection( 28, 3 )</syntaxhighlight><br />
<br />
This example would select the second Tom. The first argument to selectSection is the cursor position within the line and the second argument is the length of the selection.<br />
<br />
<syntaxhighlight lang="lua">selectCaptureGroup( number )</syntaxhighlight><br />
<br />
This function selects the captureGroup number if you use Perl regular expressions containing capture groups. The first capture group starts with index 1.<br />
<br />
==Deleting Text - Gagging==<br />
<br />
<syntaxhighlight lang="lua">deleteLine()</syntaxhighlight><br />
<br />
This function deletes the current line - or any line where the cursor is currently placed. You can use repeated calls to this function to effectively erase the entire text buffer. If you want to delete or gag certain words only, you can select the text that you want to delete and then replace it with an empty string e.g:<br />
<br />
If you get this line form the MUD: "Mary and Tom walk to the diner."<br />
<br />
<syntaxhighlight lang="lua">selectString( "Tom", 1 )<br />
replace( "" )</syntaxhighlight><br />
<br />
Then the output will be changed to: "Mary and walk to the diner."<br />
<br />
==Cursor Movement and Cursor Placement==<br />
Mudlet allows you to insert text arbitrarily within the buffer - in the previous line, in the previous ten lines, or even the first line that you've ever saw. These are the tools to help you with the job:<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( windowName, x, y )]]</code> This will move the user cursor of window windowName to the absolute (x/y) coordinates in the text.<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor( "main", 20, 3950 )]]</code> will move the cursor on the 20th character from the left on line number 3950. To determine the current cursor position you can use getLineNumber() and getColumnNumber() as well as [[Manual:UI_Functions#getLastLineNumber|getLastLineNumber()]] to get the number of the last line in the text buffer. moveCursorEnd("main") will move the cursor of the main display to end of the buffer. This is always a new line of size 1 containing the character \n.<br />
<br />
<code>number_of_last_line_in_text = [[Manual:UI_Functions#getLineCount|getLineCount()]]</code> returns the number of the last line of the text in the console buffer. This number will change as soon as a new \n is printed either by the user or when a new line arrives from the MUD. All lines from the MUD are terminated with \n which is called line feed or the new line character. This control character ends the current line and move the cursor to the beginning of the next line, thus creating a new, empty line below the line that contains the \n.<br />
<br />
<code>line_number_of_the_current_cursor_position = [[Manual:UI_Functions#getLineNumber|getLineNumber()]]</code><br />
<br />
<code>column_number_of_the_current_cursor_position = [[Manual:UI_Functions#getColumnNumber|getColumnNumber()]]</code><br />
<br />
<code>luaTable_containing_textlines = [[Manual:UI_Functions#getLines|getLines( absolute_line_number_from, absolute_line_number_to )]]</code> this will return a Lua table containing all lines between the absolute positions from and to.<br />
<br />
{{note}} This function uses absolute line numbers, not relative ones like in [[Manual:UI_Functions#moveCursor|moveCursor()]].<br />
<br />
<code>[[Manual:UI_Functions#moveCursor|moveCursor()]]</code> returns true or false depending on whether the move was possible and done.<br />
<br />
=== Inserting text in the middle of the line ===<br />
Here's an example where we'll append the text ''(one)'' right after the word ''exit'' in the line of <code>You see a single exit leading west.</code><br />
<br />
[[File:Inserting text.png|center|650px]]<br />
<br />
The pattern we used was an ''exact match'' for <code>You see a single exit leading west.</code> and the code is:<br />
<br />
<syntaxhighlight lang="lua"><br />
if moveCursor(string.find(line, "exit")+#("exit")-1, getLineNumber()) then<br />
insertText("(one)")<br />
end<br />
</syntaxhighlight><br />
<br />
What happened here:<br />
* we triggered on the desired line using our pattern above<br />
* we used [[Manual:UI_Functions#moveCursor|moveCursor()]] to place the cursor in the desired position within the line. [[Manual:UI_Functions#moveCursor|moveCursor()]] takes both the line number and the position within the line to place our virtual cursor on, so<br />
** we used [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] to find the position of the word "exit" within the line<br />
** but [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] returns us the position of the first character of the word we want, while we want to have the text be right after it - so we find out how long our word is with <code>#("exit")</code>, add that to the number returned by [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] which gets us the first character + the length of the word - which isn't quite at the end of the word, but the word plus the space (because of [http://www.lua.org/manual/5.1/manual.html#pdf-string.find string.find()] and the first character) - so we substract 1 to move our cursor right at the end of the word<br />
** we then use [[Manual:UI_Functions#getLineNumber|getLineNumber()]] to get the current line number, so our cursor is placed on the current line, at our desired position<br />
* lastly we finally insert the text with [[Manual:UI_Functions#insertText|insertText()]], which puts the text exactly where our virtual cursor is<br />
<br />
Done! You can also use [[Manual:UI_Functions#cinsertText|cinsertText()]] for coloured inserts, and other functions [[Manual:Scripting#Cursor_Movement_and_Cursor_Placement|mentioned above]] and in the [[Manual:UI_Functions|API manual]] to help you do what you'd like.<br />
<br />
==User defined dockable windows==<br />
<br />
You may want to use dock windows to display information you gathered in your scripts, or you may want to use them as chat windows etc. Check out [[Manual:Geyser#Geyser.UserWindow|Geyser.UserWindow]] on how to add them!<br />
<br />
==Dynamic Triggers==<br />
<br />
<code>triggerID = tempTrigger( substring pattern, code ) creates a fast substring matching trigger</code> <br />
<br />
<code>triggerID = tempRegexTrigger( regex, code ) creates a regular expression matching trigger</code><br />
<br />
<code>triggerID = tempBeginOfLineTrigger( begin of line pattern, code ) creates a fast begin of line substring trigger</code><br />
<br />
=Scripting howtos=<br />
==How to convert a string to value?==<br />
Say you'd like to capture a number from a trigger, but the capture always ends up being a "string" (or, just text on which you can't do any maths on) even if it's a number. To convert it to a number, you'd want to use the ''tonumber()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
myage = tonumber(matches[2])<br />
</syntaxhighlight><br />
<br />
==How to highlight my current target?==<br />
<br />
You can put the following script into your targetting alias:<br />
<br />
<syntaxhighlight lang="lua">if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
Where target is your target variable. Note that you have to use the full name, capitalized. If you’d like the script to auto-capitalize for you, you can use this version:<br />
<br />
<syntaxhighlight lang="lua"><br />
target = target:title()<br />
if id then killTrigger(id) end<br />
id = tempTrigger(target, function() selectString(target, 1) fg("gold") deselect() resetFormat() end)</syntaxhighlight><br />
<br />
{{note}} Ensure you're on Mudlet 3.5.0+ so you can put ''function()'' in a ''[[Manual:Lua_Functions#tempTrigger|tempTrigger()]]''.<br />
<br />
==How to format an echo to a miniConsole?==<br />
<br />
One of the ways you can create multi-line displays in a miniConsole with variable information is with string.format and the use of [[ ]] brackets for text, which allow for multiple line in text:<br />
<br />
<syntaxhighlight lang="lua"><br />
local WindowWidth, WindowHeight = getMainWindowSize();<br />
createMiniConsole("sys",WindowWidth-650,0,650,300)<br />
<br />
local name, age, sex = "Bob", 34, "male"<br />
<br />
cecho("sys", string.format([[<br />
<br />
/---------\<br />
%s<br />
%dyrs<br />
sex - %s <br />
\---------/<br />
]], name, age, sex))<br />
</syntaxhighlight><br />
<br />
==How to play a sound when I receive communication while afk?==<br />
<br />
[[File:Play_sound_when_afk_trigger.png]]<br />
<br />
For this to work, place the line you'd like to trigger on in the first pattern box and select the appropriate pattern type. Then add ''return not hasFocus()'' with the Lua function as the second pattern, enable the AND trigger, and set the line delta to zero. Then just enable ''play sound'', choose your sound and you're set!<br />
<br />
==How can I make a key that toggles between commands?==<br />
To make a key that toggles between two actions, for example - sleep/wake, you can use this as the script:<br />
<br />
<syntaxhighlight lang="lua"><br />
if not sleeping then<br />
send("sleep")<br />
sleeping = true<br />
else<br />
send("wake")<br />
sleeping = false<br />
end<br />
</syntaxhighlight><br />
<br />
<!-- Old Heading: How can I make a trigger that goes off only if the next line is not a particular one? --><br />
==How can I make a trigger with a next-line condition?==<br />
<br />
Here's how you can set it up - replace ''line1'' and ''line2'' with appropriate lines.<br />
<br />
[[File:Trigger_multiline_not_another_example.png|center]]<br />
<br />
Here's [[Media:Match only of next line is *not* line2.xml.zip|the Mudlet XML]] you can download for this!<br />
<br />
==How to target self or something else?==<br />
<br />
[[File:Buffselforother.png|border|350px]]<br />
<br />
Using regex and an 'or' statement allows us to consolidate multiple aliases, or an if statement, into a single more simple alias. <br />
When a regex is found it will use it, but if you don't specify one then the alternative will be used. The use of 'or' can be used with any function in Mudlet.<br />
In this example, one can type "buff" to buff themself, or "buff ally" to buff their ally instead.<br />
<br />
<syntaxhighlight lang="lua"><br />
^buff(?: (\w+))?$<br />
<br />
send("cast buff on "..(matches[2] or "myself"))<br />
</syntaxhighlight><br />
<br />
==How to delete everything between two lines?==<br />
When deleteLine() is called, every following line shifts back in numerical position. Thus if we know where we're starting and how many lines to expect, we can use a for loop to gag everything between line a and b by leaving the cursor in one spot. In the below example, line_a_number is the number of the line you want to start at, and line_b_number is the ending line. To gag x number of lines instead, use line_a_number + x in place of line_b_number.<br />
<br />
<syntaxhighlight lang="lua"><br />
for i = line_a_number, line_b_number, 1<br />
do<br />
moveCursor(0, line_a_number)<br />
selectCurrentLine()<br />
deleteLine()<br />
end<br />
</syntaxhighlight><br />
<br />
== How to capture foreground line color information? ==<br />
Here's an example that loops through each character in a line of text and prints the character and its foreground color to a miniconsole if the color has changed from the previous character:<br />
<br />
Trigger: <code>^</code> (regex)<br />
<br />
Code:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer =<br />
miniconsoleContainer or Adjustable.Container:new({name = "miniconsoleContainer"})<br />
myMiniconsole =<br />
Geyser.MiniConsole:new(<br />
{<br />
name = "myMiniconsole",<br />
x = 0,<br />
y = 0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width = "100%",<br />
height = "100%",<br />
},<br />
miniconsoleContainer<br />
)<br />
<br />
local index = 0<br />
local line = getCurrentLine()<br />
local linesize = #line<br />
local currentlinenumber = getLineNumber()<br />
local r, g, b = 0, 0, 0<br />
local cr, cg, cb -- last seen colors<br />
while index < linesize do<br />
index = index + 1<br />
moveCursor("main", index, currentlinenumber)<br />
selectString(line:sub(index), 1)<br />
r, g, b = getFgColor()<br />
if cr ~= r or cg ~= g or cb ~= b then<br />
cr, cg, cb = r, g, b<br />
myMiniconsole:echo(string.format("rgb(%d,%d,%d)%s", r, g, b, line:sub(index, index)))<br />
else<br />
myMiniconsole:echo(string.format("%s", line:sub(index, index)))<br />
end<br />
line:sub(index, index)<br />
end<br />
myMiniconsole:echo("\n")<br />
</syntaxhighlight><br />
<br />
==How to enter a carriage return / enter command?==<br />
Say you'd like to gag the following line, and just continue ... <br />
<br />
[ Press Enter to continue ]<br />
<br />
<syntaxhighlight lang="lua"><br />
Trigger: [ Press Enter to continue ] (set to exact match)<br />
Code: deleteLine()<br />
send("\n")<br />
</syntaxhighlight><br />
<br />
==How to repeat commands with #?==<br />
Install the [https://forums.mudlet.org/viewtopic.php?f=6&t=1275 following alias], and with it <code>#5 mycommand</code> will get repeated five times.<br />
<br />
== How to move the command line over? ==<br />
<br />
To move the command line over to the right, create a new script and add the following to it:<br />
<br />
<syntaxhighlight lang="css"><br />
setCmdLineStyleSheet("main", [[<br />
QPlainTextEdit {<br />
padding-left: 100px; /* change 100 to your number */<br />
background-color: black; /* change it to your background color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
== How to add a background for Mudlets buttons? ==<br />
You can give Mudlets buttons a background to have them blend in with your UI by doing this:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- replace the /home/vadi/Pictures/tile.png location below with the one of your picture!<br />
-- you can download the sample tile.png from https://opengameart.org/content/bevouliin-free-game-background-for-game-developers<br />
local backgroundpath = [[/home/vadi/Pictures/tile.png]]<br />
-- Windows:<br />
-- local backgroundpath = [[C:/Users/Vadim/Downloads/Free game background/transparent PNG/tile.png]]<br />
<br />
setAppStyleSheet([[<br />
QToolBar {<br />
border-image: url(]]..backgroundpath..[[);<br />
<br />
}<br />
<br />
QToolBar QToolButton:!hover {<br />
color: white;<br />
}<br />
QToolBar QToolButton:hover {<br />
color: black;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
Result:<br />
<br />
[[File:Mudlet tiled buttons.png|frame|left]]<br />
<br clear=all><br />
<br />
= Advanced scripting tips =<br />
== Do stuff after all triggers/aliases/scripts are run ==<br />
This little snippet will have your commands be executed right after, depending on the context you run it in, all triggers, aliases or scripts are completed:<br />
<br />
<syntaxhighlight lang="lua">tempTimer(0, [[mycode]])</syntaxhighlight><br />
<br />
== How to delete the previous and current lines ==<br />
<br />
This little snippet comes from [http://forums.mudlet.org/viewtopic.php?f=9&t=2411&p=10685#p10685 Iocun]:<br />
<br />
<syntaxhighlight lang="lua"><br />
moveCursor(0,getLineCount()-1)<br />
deleteLine()<br />
moveCursor(0,getLineCount())<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=db: Mudlet's database frontend=<br />
<br />
The DB package is meant to provide easier access to a database, so you don’t have to know SQL or use the luasql module to set and get at your data. However, it does require that the luasql module be compiled and included in Mudlet to function.<br />
<br />
==Creating a Database==<br />
<br />
Before you can store anything in a database, you need to create one. You may have as many independent databases as you wish, with each having as many unique tables-- what we will call sheets in this package, so as to avoid confusion with Lua tables - think spreadsheets.<br />
<br />
To create a database, you use the db:create() function, passing it the name of your database and a Lua table containing its schema configuration. A schema is a mold for your database - it defines what goes where. Using the spreadsheet example, this would mean that you’d define what goes into each column. A simple example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes"}})<br />
</syntaxhighlight><br />
<br />
This will create a database which contains two sheets: one named friends, the other named enemies. Each has three columns, name, city and notes-- and the datatype of each are strings, though the types are very flexible and can be changed basically whenever you would like. It’ll be stored in a file named Database_people.db in your Mudlet config directory on the hard drive should you want to share it.<br />
<br />
It’s okay to run this function repeatedly, or to place it at the top-level of a script so that it gets run each time the script is saved: the DB package will not wipe out or clear the existing data in this case. <br />
<br />
{{Note}} You may not create a column or field name which begins with an underscore. This is strictly reserved to the db package for special use.<br />
<br />
{{Note}} Adding new columns to an existing database did not work in Mudlet 2.1 - see [[Manual:Lua_Functions#db:create|db:create()]] on how to deal with this.<br />
<br />
<!--<br />
More importantly, this allows you to add columns to an existing sheet. If you change that line to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {friends={"name", "city", "notes"}, enemies={"name", "city", "notes", "enemied"}})<br />
</syntaxhighlight><br />
<br />
It will notice that there is a new column on enemies, and add it to the existing sheet-- though the value will end up as nil for any rows which are already present. Similarly, you can add whole new sheets this way. It is not presently possible to -remove- columns or sheets without deleting the database and starting over.<br />
--><br />
<br />
==Adding Data==<br />
<br />
To add data to your database, you must first obtain a reference (variable) for it. You do that with the db:get_database function, such as:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("people")<br />
</syntaxhighlight><br />
<br />
The database object contains certain convenience functions (discussed later, but all are preceded with an underscore), but also a reference to every sheet that currently exists within the database. You then use the db:add() function to add data to the specified sheet.<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends, {name="Ixokai", city="Magnagora"})<br />
</syntaxhighlight><br />
<br />
If you would like to add multiple rows at once to the same table, you can do that by just passing in multiple tables:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.friends,<br />
{name="Ixokai", city="Magnagora"},<br />
{name="Vadi", city="New Celest"},<br />
{name="Heiko", city="Hallifax", notes="The Boss"}<br />
)<br />
</syntaxhighlight><br />
<br />
Notice that by default, all columns of every table are considered optional-- if you don’t include it in the add, then it will be set to its default value (which is nil by default)<br />
<br />
For those familiar with databases: with the DB package, you don’t have to worry about committing or rolling back any changes, it will commit after each action automatically. If you would like more control than this, see Transactions below.<br />
<br />
You also cannot control what is the primary key of any sheets managed with DB, nor do you have to create one. Each row will get a unique integer ID that automatically increments, and this field can be accessed as "_row_id".<br />
<br />
==Querying==<br />
<br />
Putting data in isn’t any fun if you can’t get it out. If you want every row from the sheet, you can do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends)<br />
</syntaxhighlight><br />
<br />
But rarely is that actually useful; usually you want to get only select data. For example, you only want to get people from the city of Magnagora. To do that you need to specify what criteria the system should use to determine what to return to you. It looks like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
So the basic command is - db:fetch(_sheet_, _what to filter by_)<br />
<br />
The following filter operations are defined:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:eq(field, value[, case_insensitive]) -- Defaults to case insensitive, pass true as the last arg to<br />
reverse this behavior.<br />
db:not_eq(field, value[, case_insensitive) -- Not Equal To<br />
db:lt(field, value) -- Less Than<br />
db:lte(field, value) -- Less Than or Equal to.<br />
db:gt(field, value) -- Greater Than<br />
db:gte(field, value) -- Greater Than or Equal To<br />
db:is_nil(field) -- If the column is nil<br />
db:is_not_nil(field) -- If the column is not nil<br />
db:like(field, pattern) -- A simple matching pattern. An underscore matches any single character,<br />
and a percent(%) matches zero or more characters. Case insensitive.<br />
db:not_like(field, pattern) -- As above, except it'll give you everything but what you ask for.<br />
db:between(field, lower_bound, upper_bound) -- Tests if the field is between the given bounds (numbers only).<br />
db:not_between(field, lower_bound, upper_bound) -- As above, only... not.<br />
db:in_(field, table) -- Tests if the field is in the values of the table. NOTE the trailing underscore!<br />
db:not_in(field, table) -- Tests if the field is NOT in the values of the table *<br />
</syntaxhighlight><br />
<br />
The db:in_ operator takes a little more explanation. Given a table, it tests if any of the values in the table are in the sheet. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:in_(mydb.friends.city, {"Magnagora", "New Celest"})<br />
</syntaxhighlight><br />
<br />
It tests if city == "Magnagora" OR city == "New Celest", but with a more concise syntax for longer lists of items.<br />
<br />
There are also two logical operators:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:AND(operation1, ..., operationN)<br />
db:OR(operation1, operation2)<br />
</syntaxhighlight><br />
<br />
You may pass multiple operations to db:fetch in a table array, and they will be joined together with an AND by default. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends,<br />
{db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "X%")}<br />
)<br />
</syntaxhighlight><br />
<br />
This will return every record in the sheet which is in the city of Magnagora, and has a name that starts with an X. Again note that in LIKE patterns, a percent is zero or more characters — this is the same effect as "X.*" in pcre patterns. Similarly, an underscore matches any single characters and so is the same as a dot in pcre.<br />
<br />
Passing multiple expressions in an array to db:fetch is just a convenience, as its exactly the same as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:AND(db:eq(mydb.friends.city, "Magnagora"), db:like(mydb.friends.name, "I%")))<br />
</syntaxhighlight><br />
<br />
The db:OR operation only takes two arguments, and will check to see if either of the two is true. You can nest these logical operators as deeply as you need to.<br />
<br />
You can also just pass in a string directly to db:fetch, but you have to be very careful as this will be passed straight to the SQL layer. If you don’t know any SQL then you want to avoid this… for example, in SQL there’s a very big difference between double and single quotes. If you don’t know that, then stick to the db functions. But an example is:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, "city == 'Magnagora'")<br />
</syntaxhighlight><br />
<br />
Now, the return value of db:fetch() is always a table array that contains a table dictionary representing the full contents of all matching rows in the sheet. These are standard Lua tables, and you can perform all normal Lua operations on them. For example, to find out how many total items are contained in your results, you can simply do #results. If a request from the friends sheet were to return one row that you stored in the results variable, it would look like this if passed into the display() function:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'name': 'Bob',<br />
'city': 'Magnagora',<br />
'notes': 'Trademaster of Tailoring'<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
And if you were to echo(#results), it would show 1.<br />
<br />
The order of the returned rows from db:fetch is generally the same as the order in which you entered them into the database, but no actual guarantees are made to this. If you care about the order then you can pass one or two optional parameters after the query to db:fetch() to control this.<br />
<br />
The first table is an array of fields that indicate the column names to sort by; the second is a flag to switch from the default ascending(smallest to largest) sort, to a descending(largest to smallest) sort. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city})<br />
</syntaxhighlight><br />
<br />
This will return all your friends in Magnagora, sorted by their name, from smallest to largest. To reverse this, you would simply do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, db:eq(mydb.friends.city, "Magnagora"), {mydb.friends.city}, true)<br />
</syntaxhighlight><br />
<br />
Including more then one field in the array will indicate that in the case that two rows have the same value, the second field should be used to sort them.<br />
<br />
If you would like to return ALL rows from a sheet, but still sort them, you can do that by passing nil into the query portion. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:fetch(mydb.friends, nil, {mydb.friends.city, mydb.friends.name})<br />
</syntaxhighlight><br />
<br />
This will return every friend you have, sorted first by city and then their name.<br />
<br />
==Indexes and Types==<br />
<br />
The sheets we’ve defined thus far are very simple, but you can take more control over the process if you need to. For example, you may assign default values and types to columns, and the DB package will attempt to coerce them as appropriate. To do that, you change your db:create() call as:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
This is almost the same as the original definition, but we’ve defined that our first four fields are strings with a default value of blank, and the new kills field which is an integer that starts off at 0. The only way to set a datatype is to set a default value at this time.<br />
<br />
Please note, beneath the DB package is SQLite, and SQLite is very data-type neutral. It doesn’t really care very much if you break those rules and put an integer in a string field or vice-versa, but the DB package will — to a limited degree — attempt to convert as appropriate, especially for the operations that work on numbers.<br />
<br />
You may also create both standard and unique indexes. A unique index enforces that a certain criteria can only happen once in the sheet. Now, before you go and make indexes, pause and consider. There is no right or wrong answer when it comes to what to index: it depends on what kind of queries you do regularly. If in doubt, don’t make an index. Indexes will speed up reading data from the sheet, but they will slow down writing data.<br />
<br />
To add an index, pass either the _index or _unique keys in the table definition. An example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" }<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Now, bear in mind: _index = { "name", "city"} creates two indexes in this sheet. One on the city field, one on the name field. But, _index = { {"name", "city"} } creates one index: on the combination of the two. Compound indexes help speed up queries which frequently scan two fields together, but don’t help if you scan one or the other.<br />
<br />
The admonition against making indexes willy-nilly holds double for compound indexes: do it only if you really need to!<br />
<br />
===Uniqueness===<br />
<br />
As was specified, the _unique key can be used to create a unique index. This will make it so a table can only have one record which fulfills that index. If you use an index such as _unique = { "name" } then names must be unique in the sheet. You can specify more than one key to be unique; in that case they will be checked in an OR condition.<br />
<br />
Now, if you use db:add() to insert a record which would violate the unique constraint, a hard error will be thrown which will stop your script. Sometimes that level of protection is too much, and in that case you can specify how the db layer handles violations.<br />
<br />
There are three possible ways in which the layer can handle such violations; the default is to FAIL and error out.<br />
<br />
You can also specify that the db layer should IGNORE any commands that would cause the unique constraint to be violated, or the new data should REPLACE the existing row.<br />
<br />
For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento"})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the name field being declared to be unique, these two commands can’t succeed normally. The first db:add() will create a record with the name of Bob, and the second would cause the uniqueness of the name field to be violated. With the default behavior (FAIL), the second db:add() call will raise an error and halt the script.<br />
<br />
If you want the IGNORE behavior, the second command will not cause any errors and it will simply fail silently. Bob’s city will still be Sacramento.<br />
<br />
With the REPLACE behavior, the second command will cause its data to completely overwrite and replace the first record. Bob’s city will now be San Francisco.<br />
<br />
A word of caution with REPLACE, given:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:add(mydb.enemies, {name="Bob", city="Sacramento", notes="This is something."})<br />
db:add(mydb.enemies, {name="Bob", city="San Francisco"})<br />
</syntaxhighlight><br />
<br />
With the REPLACE behavior, the second record will overwrite the first-- but the second record does not have the notes field set. So Bob will now not have any notes. It doesn’t -just- replace existing fields with new ones, it replaces the entire record.<br />
<br />
To specify which behavior the db layer should use, add a _violations key to the table definition:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:create("people", {<br />
friends={"name", "city", "notes"},<br />
enemies={<br />
name="",<br />
city="",<br />
notes="",<br />
enemied="",<br />
kills=0,<br />
_index = { "city" },<br />
_unique = { "name" },<br />
_violations = "IGNORE"<br />
}<br />
})<br />
</syntaxhighlight><br />
<br />
Note that the _violations behavior is sheet-specific.<br />
<br />
===Timestamps===<br />
<br />
In addition to strings and floats, the db module also has basic support for timestamps. In the database itself this is recorded as an integer (seconds since 1970) called an epoch, but you can easily convert them to strings for display, or even time tables to use with Lua’s built-in time support.<br />
<br />
The most common use for the Timestamp type is where you want the database to automatically record the current time whenever you insert a new row into a sheet. The following example illustrates that:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:create("combat_log",<br />
{<br />
kills = {<br />
name = "",<br />
area = "",<br />
killed = db:Timestamp("CURRENT_TIMESTAMP"),<br />
_index = { {"name", "killed"} }<br />
}<br />
}<br />
)<br />
<br />
-- observe that we don't provide the killed field here - DB automatically fills it in for us.<br />
db:add(mydb.kills, {name="Drow", area="Undervault"})<br />
<br />
results = db:fetch(mydb.kills)<br />
display(results)<br />
</syntaxhighlight><br />
<br />
The result of that final display would show you this on a newly created sheet:<br />
<br />
<syntaxhighlight lang="lua"><br />
table {<br />
1: table {<br />
'_row_id': 1<br />
'area': 'Undervault'<br />
'name': 'Drow'<br />
'killed': table {<br />
'_timestamp': 1264317670<br />
}<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
As you can see from this output, the killed fields contains a timestamp-- and that timestamp is stored as an epoch value in the GMT timezone. For your convenience, the db.Timestamp type offers three functions to get the value of the timestamp in easy formats. They are <code>as_string</code>, <code>as_number</code> and <code>as_table</code>, and are called on the timestamp value itself.<br />
<br />
The as_number function returns the epoch number, and the as_table function returns a time table. The as_string function returns a string representation of the timestamp, with a default format of "%m-%d-%Y %H:%M:%S". You can override this format to anything you would like. Details of what you can do with epoch values, time tables, and what format codes you can use are specified in the Lua manual at: http://www.lua.org/pil/22.1.html for the Lua date/time functions.<br />
<br />
A quick example of the usage of these functions is:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.kills)<br />
for _, row in ipairs(results) do<br />
echo("You killed " .. row.name .. " at: " .. (row.killed and row.killed:as_string() or "no time") .."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==Deleting==<br />
<br />
The db:delete function is used to delete rows from the sheet. It takes two arguments, the first being the sheet you are deleting and the second a query string built using the same functions used to build db:fetch() queries.<br />
<br />
For example, to delete all your enemies in the city of Magnagora, you would do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these! You may inadvertantly wipe out huge chunks of your sheets if you don’t have the query parameters set just to what you need them to be. Its advised that you first run a db:fetch() with those parameters to test out the results they return.<br />
<br />
As a convenience, you may also pass in a result table that was previously retrieved via db:fetch and it will delete only that record from the table. For example, the following will get all of the enemies in Magnagora, and then delete the first one:<br />
<br />
<syntaxhighlight lang="lua"><br />
results = db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "Magnagora"))<br />
db:delete(mydb.enemies, db:eq(mydb.enemies._row_id, results[1]._row_id))<br />
</syntaxhighlight><br />
<br />
That is equivalent to:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
You can even pass a number directly to db:delete if you know what _row_id you want to purge.<br />
<br />
A final note of caution: if you want to delete all the records in a sheet, you can do so by only passing in the table reference. To try to protect you from doing this inadvertently, you must also pass true as the query after:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:delete(mydb.enemies, true)<br />
</syntaxhighlight><br />
<br />
==Updating==<br />
<br />
If you make a change to a table that you have received via db:fetch(), you can save those changes back to the database by doing:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:update(mydb.enemies, results[1])<br />
</syntaxhighlight><br />
<br />
A more powerful (and somewhat dangerous, be careful!) function to make changes to the database is db:set, which is capable of making sweeping changes to a column in every row of a sheet. Beware, if you have previously obtained a table from db:fetch, that table will NOT represent this change.<br />
<br />
The db:set() function takes two arguments: the field to change, the value to set it to, and the db:fetch() like query to indicate which rows should be affected. If you pass true as the last argument, ALL rows will be changed.<br />
<br />
To clear out the notes of all of our friends in Magnagora, we could do:<br />
<br />
<syntaxhighlight lang="lua"><br />
db:set(mydb.friends.notes, "", db:eq(mydb.friends.notes, "Magnagora"))<br />
</syntaxhighlight><br />
<br />
Be careful in writing these!<br />
<br />
==Transactions==<br />
<br />
As was specified earlier, by default the db module commits everything immediately whenever you make a change. For power-users, if you would like to control transactions yourself, the following functions are provided on your database instance:<br />
<br />
<syntaxhighlight lang="lua"><br />
local mydb = db:get_database("my_database")<br />
mydb:_begin()<br />
mydb:_commit()<br />
mydb:_rollback()<br />
mydb:_end()<br />
</syntaxhighlight><br />
<br />
Once you issue a mydb._begin() command, autocommit mode will be turned off and stay off until you do a mydb._end(). Thus, if you want to always use transactions explicitly, just put a mydb._begin() right after your db:create() and that database will always be in manual commit mode.<br />
<br />
==Viewing and editing the database contents==<br />
<br />
A good tool to view and edit the database contents in raw form is [http://afoucal.free.fr/index.php/applications/sqlite-sorcerer/ SQlite Sorcerer] (free and available for Linux, Windows, Mac).<br />
<br />
==Debugging raw queries==<br />
<br />
If you'd like to see the queries that db: is running for you, you can enable debug mode with ''db.debug_sql = true''.<br />
<br />
=Discord Messenges=<br />
<br />
Can you send messenges from Mudlet to Discord? Totally. Here is an example:<br />
<br />
(start of code)<br />
<br />
function sendToDiscord(data)<br />
local url = "https://discord.com/api/webhooks/1204151397977821184/Cu8ZQQo9R11AyIt3DxpOEeB8MtVMA6_AEfXoZaYxqEAOu_6hwhtA2cRLIw-VIs7py7p8"<br />
local headers = {["Content-Type"] = "application/json"}<br />
local json = yajl.to_string(data)<br />
postHTTP(json, url, headers)<br />
end<br />
<br />
local data = {<br />
content = "Hello, Discord!",<br />
embeds = {<br />
{<br />
title = "This is an embed",<br />
url = "https://example.com",<br />
image = {<br />
url = "https://example.com/image.jpg"<br />
}<br />
}<br />
}<br />
}<br />
<br />
sendToDiscord(data)<br />
<br />
(end of code)<br />
<br />
Sure enough, after starting this script, you can see a message in Discord:<br />
<br />
(add pic to illustrate the result)<br />
<br />
What you just need to do is create a webhook in a channel. Go to channel settings, then create this:<br />
<br />
(pic displaying the setup webhook)<br />
<br />
Here you can find more documentation on which fields Discord allows: https://discord.com/developers/docs/resources/webhook#execute-webhook<br />
<br />
All this is one way though. Mudlet won't listen to messages from Discord. For that you'd probably have to make a Discord bot first.<br />
<br />
<br />
<br />
=Discord Rich Presence=<br />
[[File:Rich_Presence_Midmud.gif|frame]]<br />
<!-- [[File:Rich Presence Achaea.gif|frame]] --><br />
<br />
Discord Rich Presence in Mudlet allows you, the player, to show off the game you're playing and you, the game author, to get your game shown off! Advertise your game for free alongside AAA titles in server player lists :)<br />
<br />
To respect the players privacy, this option is disabled by default - enable it by ticking the Discord option for the profile:<br />
<br />
[[File:Enable Discord.png|border|center]]<br />
<br />
Once enabled, a Discord-capable game will show information in your Discord!<br />
<br />
To fine-tune the information you'd like to see displayed, go to Settings, Chat tab:<br />
<br />
[[File:Discord Privacy.png|center|400px]]<br />
<br />
== Implementing ==<br />
As a game author, you have two ways of adding Discord support to your game: via GMCP (easy) or via Lua.<br />
<br />
Adding support via GMCP means that your players don't have to install any Lua scripts which is a nicer experience. To do so, implement the [[Standards:Discord_GMCP|Discord over GMCP]] specification and [https://www.mudlet.org/contact/ get in touch] to let us know your game implements GMCP.<br />
<br />
=== GMCP ===<br />
Here's a quick cheatsheet to implement the [[Standards:Discord_GMCP|GMCP spec]]:<br />
<br />
# Create a discord [https://discordapp.com/developers/applications/me application]<br />
# Upload game logo for "rich presence invite image"<br />
# Upload same game logo in "Rich Presence Assets" with the name of <code>server-icon</code><br />
# Upon receiving "External.Discord.Hello" from the game client, reply with "External.Discord.Info" with <code>applicationid</code> ([[:File:Mudlet Discord ApplicationID.png|see screenshot]]) and "External.Discord.Status" <br />
# Send "External.Discord.Status" whenever you need to send data to the client, and fill it with the values have changed since the last status. Discord has [https://discordapp.com/developers/docs/rich-presence/best-practices#tips some ideas] for filling it in.<br />
# Done. Mudlet will enable the Discord checkbox upon receiving the <code>applicationid</code> from the game at least once.<br />
<br />
=== Lua ===<br />
An alternative way to add Discord support as a game author is [[Manual:Discord_Functions|via Lua]] - all of Discords functionality can be manipulated from it. Create a discord [https://discordapp.com/developers/applications/me application] and set it with [[Manual:Discord_Functions#setDiscordApplicationID|setDiscordApplicationID()]], then set the set the rest of the options as necessary:<br />
<br />
[[File:Discord fields.png|frame|center|Credit: Discord]]<br />
<br />
If you're a game player and your game doesn't support Discord, you can still use the functionality to set the detail, status, party and time information as desired.<br />
<br />
{{MudletVersion|3.14}}<br />
<br />
=MUD Client Media Protocol=<br />
<br />
==Client.Media==<br />
Want to add accessibility and excitement into your game? How about implementing sound and music via GMCP?<br />
<br />
The Client.Media family of GMCP packages provide a way for games to send sound and music events. GMCP media events are sent in one direction: from game server to to game client.<br />
<br />
===Client.Media in Mudlet===<br />
<br />
Media files may be downloaded manually or automatically if certain conditions are met.<br />
<br />
{{MudletVersion|4.4}}<br />
<br />
Mudlet accepts case-insensitive GMCP for the Client.Media namespace (for example, these are all acceptable: "Client.Media.Play", "client.media.play", "cLiEnT.MeDiA.Play").<br />
<br />
===Enabling Media===<br />
When a new profile opens, Mudlet adds to the Core.Supports.Set GMCP package "Client.Media 1" to signal to servers that it supports processing media files via GMCP:<br />
<br />
<syntaxhighlight lang="json"><br />
Core.Supports.Set ["Client.Media 1", ...]<br />
</syntaxhighlight><br />
<br />
To process Client.Media GMCP data in Mudlet, these boxes in the Settings window of Mudlet must be checked:<br />
<br />
# The "Enable GMCP" box in the Miscellaneous section.<br />
# The "Allow server to download and play media" box in the Game protocols section.<br />
<br />
These boxes are checked by default upon the start of a new profile in Mudlet.<br />
<br />
===Storing Media===<br />
<br />
Mudlet plays files cached in the "media" folder within a game's profile. To get files into the "media" folder you could perform either of these options:<br />
<br />
# Copy media files or extract them from an archive (zip)<br />
# Automatically download them from external resources such as your game's web server on the Internet.<br />
<br />
To enable the second option (Internet), use the "url" parameter made available in the "Client.Media.Default", "Client.Media.Load" and "Client.Media.Play" GMCP packages described below.<br />
<br />
===Loading Media===<br />
<br />
Send a '''Client.Media.Default''' GMCP event to setup the default URL directory to load sound or music files from external resources. This would typically be done once upon player login. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
|-<br />
|}<br />
<br />
For example, to setup the default URL directory for your game:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Default {<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
If downloading from external resources, it is recommended to use Client.Media.Default, set this default URL directory once, and let Mudlet download all of your media files automatically from this one resource location. Otherwise, explicitly set the "url" parameter on all of your Client.Media.Load GMCP and Client.Media.Play GMCP events to ensure that files are downloaded from the intended location(s).<br />
<br />
Send '''Client.Media.Load''' GMCP events to load sound or music files. This could be done when the player logs into your game or at the beginning of a zone that will need the media.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if a url was not set above with Client.Media.Default.<br />
|-<br />
|}<br />
<br />
For example, download the sound of a sword swooshing within the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Load {<br />
"name": "sword1.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
===Playing Media===<br />
<br />
Send '''Client.Media.Play''' GMCP events to play sound or music files.<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| "name"<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| "url"<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely and a url was not set above with Client.Media.Default or Client.Media.Load.<br />
|-<br />
| style="text-align:center;"| No<br />
| "type"<br />
| "sound" or "music"<br />
| "sound"<br />
| style="text-align:left;"|<br />
* Identifies the type of media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "tag"<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;"| No<br />
| "volume"<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| "fadein"<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"fadeout"<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| "start"<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
* 1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
|"loops"<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the sound or music to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a lower priority while this media plays.<br />
|-<br />
| style="text-align:center;" |No<br />
|"continue"<br />
| true or false<br />
|true<br />
| style="text-align:left;" |<br />
*Only valid for media files with a "type" of "music".<br />
*Continues playing matching new music files when true.<br />
*Restarts matching new music files when false.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
|}<br />
<br />
==== name====<br />
<br />
For example, to simply play the sound of a cow mooing already stored in the "media" folder:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Or some lightning stored in a "weather" sub-folder under the "media" folder.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "weather/lightning.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
The "name" parameter may be used for stopping media with the Client.Media.Stop GMCP event.<br />
<br />
====url====<br />
<br />
If you maintain your sound files on the Internet and don't set a default URL with Client.Media.Default, or preload them with Client.Media.Load, include the "url" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"url": "https://www.example.com/sounds/"<br />
}<br />
</syntaxhighlight><br />
<br />
====type: sound====<br />
<br />
Media files default to a "type" of "sound" when the "type" parameter is not specified, such as in the example above. It is good practice to specify the "type" parameter to best keep media organized within your implementation:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "cow.wav",<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====tag====<br />
<br />
To play the sound of a sword swooshing and categorized as "combat":<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat"<br />
}<br />
</syntaxhighlight><br />
<br />
The "tag" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====type: music====<br />
<br />
Add background music to your environment through use of the "music" value set upon the "type" parameter:<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment"<br />
}<br />
</syntaxhighlight><br />
<br />
The "type" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====volume: 1 to 100====<br />
<br />
As the character draws nearer to or farther from the environmental feature, consider adjusting the "volume" parameter. Example values, followed by syntax examples:<br />
<br />
*Maximum: 100 (recommended to use rarely)<br />
*High: 75<br />
*Default: 50<br />
* Low: 25<br />
* Minimum: 1 (recommended to use rarely)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "river.wav",<br />
"type": "music",<br />
"tag": "environment",<br />
"volume": 75<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "volume" values of type string ("75") into integers (75) as needed.<br />
<br />
====fadein====<br />
<br />
Increase volume from the start of the media [start position, volume one] to the number in milliseconds specified with the "fadein" parameter [position start + milliseconds, volume specified with the "volume" parameter]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade in)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "monty_python.mp3",<br />
"type": "music",<br />
"volume": 100,<br />
"fadein": 1000<br />
}<br />
</syntaxhighlight><br />
+---------------------------+-----------------------+<br />
| Fade in 1000 milliseconds | Normal |<br />
+---------------------------+-----------------------+<br />
Volume 1|........::::::::::iiiiiiiii%%%%%%%%%%%%%%%%%%%%%%%%|Volume 100<br />
+---------------------------+-----------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadein" values of type string ("1000") into integers (1000) as needed.<br />
<br />
==== fadeout====<br />
<br />
Decrease volume from a position in milliseconds subtracted from the duration of the media [position duration - milliseconds, volume specified with the "volume" parameter] to the end of the media [position duration, volume one]. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (no fade out)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "the_matrix.mp3",<br />
"type": "music",<br />
"volume": 50,<br />
"fadeout": 333<br />
}<br />
</syntaxhighlight><br />
+-----------------------+---------------------------+<br />
| Normal | Fade out 333 milliseconds |<br />
+-----------------------+---------------------------+<br />
Volume 50|%%%%%%%%%%%%%%%%%%%%%%%%iiiiiiiii::::::::::........|Volume 1<br />
+-----------------------+---------------------------+<br />
Although using the integer type is recommended, Mudlet parses "fadeout" values of type string ("333") into integers (333) as needed.<br />
<br />
==== start ====<br />
<br />
Start playing a media track at the number of milliseconds specified. Example values, followed by syntax examples:<br />
<br />
*1000 milliseconds (1 second)<br />
*60000 milliseconds (1 minute)<br />
*0 milliseconds (start from beginning)<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "mudlet_beatboxing.mp3",<br />
"type": "music",<br />
"volume": 75,<br />
"start": 1000<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "start" values of type string ("100") into integers (100) as needed.<br />
<br />
==== loops: -1, 1 or more ====<br />
<br />
The "loops" parameter controls how many times the sound repeats and defaults to 1 if not specified. A value of -1 will loop the file indefinitely.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "clock/hour_bell.wav",<br />
"type": "sound",<br />
"loops": 3<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "underdark.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "loops" values of type string ("-1") into integers (-1) as needed.<br />
<br />
==== priority: 1 to 100 ====<br />
<br />
The "priority" parameter sets precedence for Client.Media.Play GMCP events that include a "priority" setting. The values for the "priority" parameter range between 1 and 100. Given that two Client.Media.Play GMCP events have the same priority, the media already playing will continue playing. In Mudlet, media without priority set is not included comparisons based on priority.<br />
<br />
A common place to find priority implemented is with combat. In the following example, imagine a combat scenario where some sounds of sword thrusts were interrupted by a successful blocking maneuver.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sword1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3,<br />
"priority": 60<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "block1.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"priority": 70<br />
}<br />
</syntaxhighlight><br />
<br />
Although using the integer type is recommended, Mudlet parses "priority" values of type string ("25") into integers (25) as needed.<br />
<br />
The "priority" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
====continue: true or false (for music)====<br />
<br />
Typically sent with the "type" of "music" is the parameter "continue", which presents the following values:<br />
<br />
*true: continues music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
*false: restarts music that is already playing if it is requested again through a new Client.Media.Play GMCP event<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "city.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"continue": true<br />
}<br />
</syntaxhighlight><br />
<br />
If the "continue" parameter is not specified, behavior will default to ''true'' for music.<br />
<br />
Although using the boolean type is recommended, Mudlet parses "continue" values of type string ("true" and "false") into boolean (''true'' and ''false'') as needed, as not all game drivers support a boolean type.<br />
<br />
==== key====<br />
<br />
The "key" parameter enables media categorization, similar to the "tag" parameter, however it adds a feature of uniqueness that halts media currently playing with the same key, replacing it with the media that arrived from a new Client.Media.Play GMCP event. This update will only occur if the "name" or "url" associated with the currently playing media does not match the new media, while the key is identical.<br />
<br />
In the example below, consider that a player moves from a sewer area to a village. The "key" parameter is used to stop the previously playing ''sewer.mp3'' and start playing ''village.mp3'' within the second Client.Media.Play GMCP event. <br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "sewer.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
<br />
Client.Media.Play {<br />
"name": "village.mp3",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": true,<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
The "key" parameter may be used for stopping matching media with the Client.Media.Stop GMCP event.<br />
<br />
{{note}} Where music is bound to change, continue or stop as a player enters a new room, consider allowing for a slight pause of 1 heart beat or tick to send the Client.Media.Play or Client.Media.Stop GMCP events. This practice reduces the number of Client.Media.Play GMCP events sent when the player travels through several rooms quickly.<br />
<br />
==== randomization====<br />
<br />
Wildcards ''*'' (asterisk) and ''?'' (question mark) may be used within the name to randomize media file(s) selection.<br />
<br />
Given that media files underdark.wav, underdark.mp3 and underdark_dark_elven_moshpit.mp3 were all present in the media/environment directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play using the ''*'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "underdark*",<br />
"type": "music",<br />
"tag": "environment",<br />
"loops": -1,<br />
"continue": false<br />
}<br />
</syntaxhighlight><br />
<br />
If media files sword1.wav, sword2.wav and sword3.wav were all present in the media/combat directory under the current game profile, the following Client.Media.Play GMCP event would randomly choose one of those files to play per each loop using the ''?'' wildcard.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Play {<br />
"name": "combat/sword?.wav",<br />
"type": "sound",<br />
"tag": "combat",<br />
"loops": 3<br />
}<br />
</syntaxhighlight><br />
<br />
=== Stopping Media ===<br />
<br />
Send '''Client.Media.Stop''' GMCP events to stop sound or music media.<br />
<br />
{| class="wikitable"<br />
!Required<br />
!Key<br />
!Value<br />
! style="text-align:left;" |Purpose<br />
|-<br />
| style="text-align:center;" | No<br />
| "name"<br />
|<file name><br />
| style="text-align:left;" |<br />
*Stops playing media by name matching the value specified.<br />
|-<br />
| style="text-align:center;" | No<br />
|"type"<br />
|"sound" or "music"<br />
| style="text-align:left;" | <br />
*Stops playing media by type matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
| "tag"<br />
|<tag><br />
| style="text-align:left;" |<br />
*Stops playing media by tag matching the value specified.<br />
|-<br />
| style="text-align:center;" |No<br />
|"priority"<br />
|1 to 100<br />
| style="text-align:left;" |<br />
*Stops playing media with priority less than or equal to the value.<br />
|-<br />
| style="text-align:center;" |No<br />
|"key"<br />
|<key><br />
| style="text-align:left;" | <br />
*Stops playing media by key matching the value specified.<br />
|-<br />
|}<br />
<br />
====all====<br />
<br />
Send the Client.Media.Stop GMCP event with no parameters to stop all playing media within a given game profile.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {}<br />
</syntaxhighlight><br />
<br />
====parameters====<br />
<br />
Send any combination of the name, type, tag, priority or sound parameters and valid corresponding values to stop playing media that matches ''all'' combinations of the parameters.<br />
<br />
Stop the rain.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"name": "rain.wav"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media using the "type" of "sound".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"type": "sound"<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "tag" of "combat" ''and'' that has a "priority" less than or equal to 50.<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"tag": "combat",<br />
"priority": 50<br />
}<br />
</syntaxhighlight><br />
<br />
Stop all media categorized with the "key" of "area-music".<br />
<br />
<syntaxhighlight lang="json"><br />
Client.Media.Stop {<br />
"key": "area-music"<br />
}<br />
</syntaxhighlight><br />
<br />
=GUI Scripting in Mudlet=<br />
Mudlet has extremely powerful GUI capabilities built into it, and with the inclusion of the Geyser and Vyzors layout managers in Mudlet's Lua API it is quicker and easier to get a basic UI created.<br />
<br />
==Geyser==<br />
Geyser is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
Geyser's manual is quite extensive - [[Manual:Geyser|follow here]] to read up on it.<br />
<br />
===UI template===<br />
Akaya has created a UI template based on Geyser that can serve as a quick start for customizing the Mudlet interface to your character:<br />
<br />
[[File:Geyser UI template.png|center|800px|border]]<br />
<br />
To get started with it, see the forum thread about [http://forums.mudlet.org/viewtopic.php?f=6&t=4098 Geyser UI Template].<br />
<br />
==Simple Window Manager==<br />
Simple Window Manager is a light-weight script designed to provide the GUI object placement and sizing functionality seen in Geyser and Vyzor without any of the extras. Any GUI object, once created normally, can be added to the SWM along with a corner to base its positioning info off of, the distance from that corner, and the size of the object in any combination of pixels and percentages of the screen. SWM does all the behind the scenes work to keep all objects it has been given to manage in their correct places and sizes as the screen changes size. All other interactions with GUI objects are handled using standard functions built into Mudlet.<br />
<br />
Simple Window Managers manual, and download, can be [http://forums.mudlet.org/viewtopic.php?f=6&t=3529 found here].<br />
<br />
==Useful Resources==<br />
There are several useful resources you can refer to when creating your GUI.<br />
<br /><br />
<br />
;Wiki Resources<br />
*[[Manual:Geyser|Geyser Tutorial]]:<br />
:Excellent for getting an initial feel of how to use the Geyser layout manager.<br />
*[[Manual:Lua_Functions#UI_Functions|GUI API]]:<br />
:The GUI section of the Lua API manual<br />
;External Resources<br />
*[http://forums.mudlet.org/viewforum.php?f=11 Geyser subforum]:<br />
:The Geyser Layout Manager subforum on Mudlet's forums.<br />
*[http://forums.mudlet.org/viewtopic.php?f=5&t=1376 GUI Screenshots]:<br />
:A pinned thread on Mudlet's forums for showing what your GUI looks like. Useful for ideas and to see what is possible.<br />
*[http://forums.mudlet.org/viewtopic.php?f=9&t=1974 Godwars II Mudlet UI]:<br />
:A forum thread which follows the evolution of the UI provided by [http://www.godwars2.org God Wars II]<br />
[[Category:Mudlet Manual]]<br />
<br />
==Resetting your UI==<br />
While scripting your UI, you can reset it completely and have your scripts be loaded from scratch with the [[Manual:Miscellaneous_Functions#resetProfile|resetProfile()]] function - in the input line, type <code>lua resetProfile()</code>.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Networking_Functions&diff=20902Manual:Networking Functions2024-02-05T20:43:41Z<p>Kebap: sendIrc < sendMSDP</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Mudlet API documentation for functions for managing networking.}}<br />
= Networking Functions =<br />
A collection of functions for managing networking.<br />
<br />
==connectToServer==<br />
;connectToServer(host, port, [save])<br />
: Connects to a given game.<br />
<br />
;Parameters:<br />
* ''host:''<br />
: Server domain or IP address.<br />
* ''port:''<br />
: Servers port.<br />
* ''save:''<br />
: (optional, boolean) if provided, saves the new connection parameters in the profile so they'll be used next time you open it.<br />
<br />
{{note}} ''save'' is available in Mudlet 3.2+.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
connectToServer("midnightsun2.org", 3000)<br />
<br />
-- save to disk so these parameters are used next time when opening the profile<br />
connectToServer("midnightsun2.org", 3000, true)<br />
</syntaxhighlight><br />
<br />
==disconnect==<br />
;disconnect()<br />
: Disconnects you from the game right away. Note that this will ''not'' properly log you out of the game - use an ingame command for that. Such commands vary, but typically QUIT will work.<br />
<br />
: See also: [[Manual:Networking_Functions#reconnect|reconnect()]]<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
disconnect()<br />
</syntaxhighlight><br />
<br />
==downloadFile==<br />
;downloadFile(saveto, url)<br />
: Downloads the resource at the given url into the saveto location on disk. This does not pause the script until the file is downloaded - instead, it lets it continue right away and downloads in the background. When a download is finished, the [[Manual:Event_Engine#sysDownloadDone|sysDownloadDone]] event is raised (with the saveto location as the argument), or when a download fails, the [[Manual:Event_Engine#sysDownloadError|sysDownloadError]] event is raised with the reason for failure. You may call downloadFile multiple times and have multiple downloads going on at once - but they aren’t guaranteed to be downloaded in the same order that you started them in.<br />
<br />
:See also: [[#getHTTP|getHTTP()]], [[#postHTTP|postHTTP()]], [[#putHTTP|putHTTP()]], [[#deleteHTTP|deleteHTTP()]]<br />
<br />
[[File:Downloadfile privacy logging.png|frame|For privacy transparency, URLs accessed are logged in the Central Debug Console]]<br />
<br />
{{note}} Since Mudlet 3.0, https downloads are supported and the actual url that was used for the download is returned - useful in case of redirects.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- just download a file and save it in our profile folder<br />
local saveto = getMudletHomeDir().."/dark-theme-mudlet.zip"<br />
local url = "http://www.mudlet.org/wp-content/files/dark-theme-mudlet.zip"<br />
downloadFile(saveto, url)<br />
cecho("<white>Downloading <green>"..url.."<white> to <green>"..saveto.."\n")<br />
</syntaxhighlight><br />
<br />
<br />
<br />
<br />
A more advanced example that downloads a webpage, reads it, and prints a result from it:<br />
<syntaxhighlight lang="lua"><br />
-- create a function to parse the downloaded webpage and display a result<br />
function downloaded_file(_, filename)<br />
-- is the file that downloaded ours?<br />
if not filename:find("achaea-who-count.html", 1, true) then return end<br />
<br />
-- read the contents of the webpage in<br />
local f, s, webpage = io.open(filename)<br />
if f then webpage = f:read("*a"); io.close(f) end<br />
-- delete the file on disk, don't clutter<br />
os.remove(filename)<br />
<br />
-- parse our downloaded file for the player count<br />
local pc = webpage:match([[Total: (%d+) players online]])<br />
display("Achaea has "..tostring(pc).." players on right now.")<br />
end<br />
<br />
-- register our function to run on the event that something was downloaded<br />
registerAnonymousEventHandler("sysDownloadDone", "downloaded_file")<br />
<br />
-- download a list of fake users for a demo<br />
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")<br />
</syntaxhighlight><br />
<br />
Result should look like this:<br />
<br />
[[File:DownloadFile_demo.png|alt=|1000x1000px]].<br />
<br />
==getConnectionInfo==<br />
;getConnectionInfo()<br />
:Returns the server address and port that you're currently connected to, and (in Mudlet 4.12+) <code>true</code> or <code>false</code> indicating if you're currently connected to a game.<br />
:See also: [[Manual:Networking_Functions#connectToServer|connectToServer()]]<br />
<br />
{{MudletVersion|4.2}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local host, port, connected = getConnectionInfo()<br />
cecho(string.format("<light_grey>Playing on <forest_green>%s:%s<light_grey>, currently connected? <forest_green>%s\n", host, port, tostring(connected)))<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- echo the new connection parameters whenever we connect to a different host with connectToServer()<br />
function echoInfo()<br />
local host, port = getConnectionInfo()<br />
cecho(string.format("<light_grey>Now connected to <forest_green>%s:%s\n", host, port))<br />
end<br />
<br />
registerAnonymousEventHandler("sysConnectionEvent", "echoInfo")<br />
</syntaxhighlight><br />
<br />
==getIrcChannels==<br />
;getIrcChannels()<br />
:Returns a list of channels the IRC client is joined to as a lua table. If the client is not yet started the value returned is loaded from disk and represents channels the client will auto-join when started.<br />
:See also: [[Manual:Networking_Functions#setIrcChannels|setIrcChannels()]]<br />
<br />
{{MudletVersion|3.3}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getIrcChannels())<br />
-- Prints: {"#mudlet", "#lua"}<br />
</syntaxhighlight><br />
<br />
==getIrcConnectedHost==<br />
;getIrcConnectedHost()<br />
:Returns true+host where host is a string containing the host name of the IRC server, as given to the client by the server while starting the IRC connection. If the client has not yet started or finished connecting this will return false and an empty string. <br />
<br />
:This function can be particularly useful for testing if the IRC client has connected to a server prior to sending data, and it will not auto-start the IRC client.<br /> <br />
:The ''hostname'' value this function returns can be used to test if [[Manual:Event_Engine#sysIrcMessage|sysIrcMessage]] events are sent from the server or a user on the network.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local status, hostname = getIrcConnectedHost()<br />
<br />
if status == true then<br />
-- do something with connected IRC, send IRC commands, store 'hostname' elsewhere.<br />
-- if sysIrcMessage sender = hostname from above, message is likely a status, command response, or an error from the Server.<br />
else <br />
-- print a status, change connection settings, or just continue waiting to send IRC data.<br />
end<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.3}}<br />
<br />
==getIrcNick==<br />
;getIrcNick()<br />
:Returns a string containing the IRC client nickname. If the client is not yet started, your default nickname is loaded from IRC client configuration.<br />
:See also: [[Manual:Networking_Functions#setIrcNick|setIrcNick()]]<br />
<br />
{{MudletVersion|3.3}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local nick = getIrcNick()<br />
echo(nick)<br />
-- Prints: "Sheldor"<br />
</syntaxhighlight><br />
<br />
==getIrcServer==<br />
;getIrcServer()<br />
:Returns the IRC client server name and port as a string and a number respectively. If the client is not yet started your default server is loaded from IRC client configuration.<br />
:See also: [[Manual:Networking_Functions#setIrcServer|setIrcServer()]]<br />
<br />
{{MudletVersion|3.3}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local server, port = getIrcServer()<br />
echo("server: "..server..", port: "..port.."\n")<br />
</syntaxhighlight><br />
<br />
==getNetworkLatency==<br />
; getNetworkLatency()<br />
: Returns the last measured response time between the sent command and the server reply in seconds - e.g. 0.058 (=58 milliseconds lag) or 0.309 (=309 milliseconds). This is the ''N:'' number you see bottom-right of Mudlet.<br />
<br />
Also known as server lag.<br />
<br />
;Example<br />
''Need example''<br />
<br />
==openUrl==<br />
;openUrl (url)<br />
:Opens the default OS browser for the given URL.<br />
<br />
;Example:<br />
<syntaxhighlight lang="lua"><br />
openUrl("http://google.com")<br />
openUrl("www.mudlet.org")<br />
</syntaxhighlight><br />
<br />
==reconnect==<br />
;reconnect()<br />
: Force-reconnects (so if you're connected, it'll disconnect) you to the game.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- you could trigger this on a log out message to reconnect, if you'd like<br />
reconnect()<br />
</syntaxhighlight><br />
<br />
==restartIrc==<br />
;restartIrc()<br />
:Restarts the IRC client connection, reloading configurations from disk before reconnecting the IRC client.<br />
<br />
{{MudletVersion|3.3}}<br />
<br />
==sendAll==<br />
; sendAll(list of things to send, [echo back or not])<br />
: sends multiple things to the game. If you'd like the commands not to be shown, include ''false'' at the end.<br />
<br />
:See also: [[Manual:Basic_Essentials#send|send()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- instead of using many send() calls, you can use one sendAll<br />
sendAll("outr paint", "outr canvas", "paint canvas")<br />
-- can also have the commands not be echoed<br />
sendAll("hi", "bye", false)<br />
</syntaxhighlight><br />
<br />
==sendATCP==<br />
;sendATCP(message, what)<br />
: ''Need description''<br />
<br />
: See also: [[Manual:Supported_Protocols#ATCP|ATCP Protocol]], [[Manual:ATCP_Extensions|ATCP Extensions]], [http://www.ironrealms.com/rapture/manual/files/FeatATCP-txt.html Achaea Telnet Client Protocol specification], [https://forums.mudlet.org/viewtopic.php?p=19502#p19502 Description by forum user KaVir (2013)], [https://forums.mudlet.org/viewtopic.php?p=2015#p2015 Description by forum user Iocun (2009)]<br />
<br />
;Parameters:<br />
* ''message:''<br />
: The message that you want to send.<br />
* ''what:''<br />
: ''Need description''<br />
<br />
;Example<br />
''Need example''<br />
<br />
==sendGMCP==<br />
;sendGMCP(command)<br />
: Sends a GMCP message to the server. The [http://www.ironrealms.com/gmcp-doc IRE document on GMCP] has information about what can be sent, and what tables it will use, etcetera.<br />
: Note that this function is rarely used in practice. For most GMCP modules, the messages are automatically sent by the server when a relevant event happens in the game. For example, LOOKing in your room prompts the server to send the room description and contents, as well as the GMCP message gmcp.Room. A call to sendGMCP would not be required in this case.<br />
<br />
: When playing an IRE game, a call to <code>send(" ")</code> afterwards is necessary due to a bug in the game with compression (MCCP) is enabled.<br />
<br />
: See also: [[Manual:Scripting#GMCP|GMCP Scripting for Discord status]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--This would send "Core.KeepAlive" to the server, which resets the timeout<br />
sendGMCP("Core.KeepAlive")<br />
<br />
--This would send a request for the server to send an update to the gmcp.Char.Skills.Groups table.<br />
sendGMCP("Char.Skills.Get {}")<br />
<br />
--This would send a request for the server to send a list of the skills in the <br />
--vision group to the gmcp.Char.Skills.List table.<br />
<br />
sendGMCP("Char.Skills.Get " .. yajl.to_string{group = "vision"})<br />
<br />
--And finally, this would send a request for the server to send the info for <br />
--hide in the woodlore group to the gmcp.Char.Skills.Info table<br />
<br />
sendGMCP("Char.Skills.Get " .. yajl.to_string{group="MWP", name="block"})<br />
</syntaxhighlight><br />
<br />
==sendIrc==<br />
;sendIrc(target, message)<br />
: Sends a message to an IRC channel or person. Returns ''true''+''status'' if message could be sent or was successfully processed by the client, or ''nil''+''error'' if the client is not ready for sending, and ''false''+''status'' if the client filtered the message or failed to send it for some reason. If the IRC client hasn't started yet, this function will initiate the IRC client and begin a connection.<br />
<br />
To receive an IRC message, check out the [[Manual:Event_Engine#sysIrcMessage|sysIrcMessage event]].<br />
<br />
{{note}} Since Mudlet 3.3, auto-opens the IRC window and returns the success status.<br />
<br />
;Parameters:<br />
* ''target:''<br />
: nick or channel name and if omitted will default to the first available channel in the list of joined channels.<br />
* ''message:''<br />
: The message to send, may contain IRC client commands which start with <code>/</code> and can use all commands which are available through the client window.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- this would send "hello from Mudlet!" to the channel #mudlet on freenode.net<br />
sendIrc("#mudlet", "hello from Mudlet!")<br />
-- this would send "identify password" in a private message to Nickserv on freenode.net<br />
sendIrc("Nickserv", "identify password")<br />
<br />
-- use an in-built IRC command<br />
sendIrc("#mudlet", "/topic")<br />
</syntaxhighlight><br />
<br />
{{note}} The following IRC commands are available since Mudlet 3.3:<br />
* /ACTION <target> <message...><br />
* /ADMIN (<server>)<br />
* /AWAY (<reason...>)<br />
* /CLEAR (<buffer>) -- Clears the text log for the given buffer name. Uses the current active buffer if none are given.<br />
* /CLOSE (<buffer>) -- Closes the buffer and removes it from the Buffer list. Uses the current active buffer if none are given.<br />
* /HELP (<command>) -- Displays some help information about a given command or lists all available commands.<br />
* /INFO (<server>)<br />
* /INVITE <user> (<#channel>)<br />
* /JOIN <#channel> (<key>)<br />
* /KICK (<#channel>) <user> (<reason...>)<br />
* /KNOCK <#channel> (<message...>)<br />
* /LIST (<channels>) (<server>)<br />
* /ME [target] <message...><br />
* /MODE (<channel/user>) (<mode>) (<arg>)<br />
* /MOTD (<server>)<br />
* /MSG <target> <message...> -- Sends a message to target, can be used to send Private messages.<br />
* /NAMES (<#channel>)<br />
* /NICK <nick><br />
* /NOTICE <#channel/user> <message...><br />
* /PART (<#channel>) (<message...>)<br />
* /PING (<user>)<br />
* /RECONNECT -- Issues a Quit command to the IRC Server and closes the IRC connection then reconnects to the IRC server. The same as calling ircRestart() in Lua.<br />
* /QUIT (<message...>)<br />
* /QUOTE <command> (<parameters...>)<br />
* /STATS <query> (<server>)<br />
* /TIME (<user>)<br />
* /TOPIC (<#channel>) (<topic...>)<br />
* /TRACE (<target>)<br />
* /USERS (<server>)<br />
* /VERSION (<user>)<br />
* /WHO <mask><br />
* /WHOIS <user><br />
* /WHOWAS <user><br />
<br />
{{note}} The following IRC commands are available since Mudlet 3.15:<br />
* /MSGLIMIT <limit> (<buffer>) -- Sets the limit for messages to keep in the IRC client message buffers and saves this setting. If a specific buffer/channel name is given the limit is not saved and applies to the given buffer until the application is closed or the limit is changed again. For this reason, global settings should be applied first, before settings for specific channels/PM buffers.<br />
<br />
==sendMSDP==<br />
;sendMSDP(variable[, value][, value...])<br />
: Sends a MSDP message to the server.<br />
<br />
;Parameters:<br />
* ''variable:''<br />
: The variable, in MSDP terms, that you want to request from the server.<br />
* ''value:''<br />
: The variables value that you want to request. You can request more than one value at a time.<br />
<br />
: See Also: [[Manual:Supported_Protocols#MSDP|MSDP support in Mudlet]], [http://tintin.sourceforge.net/msdp/ Mud Server Data Protocol specification]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- ask for a list of commands, lists, and reportable variables that the server supports<br />
sendMSDP("LIST", "COMMANDS", "LISTS", "REPORTABLE_VARIABLES")<br />
<br />
-- ask the server to start keeping you up to date on your health<br />
sendMSDP("REPORT", "HEALTH")<br />
<br />
-- or on your health and location<br />
sendMSDP("REPORT", "HEALTH", "ROOM_VNUM", "ROOM_NAME")<br />
</syntaxhighlight><br />
<br />
==sendTelnetChannel102==<br />
; sendTelnetChannel102(msg)<br />
: Sends a message via the 102 subchannel back to the game (that's used in Aardwolf). The msg is in a two byte format; see the link below to the Aardwolf Wiki for how that works.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- turn prompt flags on:<br />
sendTelnetChannel102("\52\1")<br />
<br />
-- turn prompt flags off:<br />
sendTelnetChannel102("\52\2")<br />
</syntaxhighlight><br />
<br />
To see the list of options that Aardwolf supports go to: [http://www.aardwolf.com/blog/2008/07/10/telnet-negotiation-control-mud-client-interaction/ Using Telnet negotiation to control MUD client interaction].<br />
<br />
==setIrcChannels==<br />
;setIrcChannels(channels)<br />
:Saves the given channels to disk as the new IRC client channel auto-join configuration. This value is not applied to the current active IRC client until it is restarted with [[Manual:Networking_Functions#restartIrc|restartIrc()]]<br />
:See also: [[Manual:Networking_Functions#getIrcChannels|getIrcChannels()]], [[Manual:Networking_Functions#restartIrc|restartIrc()]]<br />
<br />
;Parameters:<br />
* ''channels:''<br />
: A table containing strings which are valid channel names. Any channels in the list which aren't valid are removed from the list. <br />
<br />
{{MudletVersion|3.3}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setIrcChannels( {"#mudlet", "#lua", "irc"} )<br />
-- Only the first two will be accepted, as "irc" is not a valid channel name.<br />
</syntaxhighlight><br />
<br />
==setIrcNick==<br />
;setIrcNick(nickname)<br />
:Saves the given nickname to disk as the new IRC client configuration. This value is not applied to the current active IRC client until it is restarted with restartIrc()<br />
:See also: [[Manual:Networking_Functions#getIrcNick|getIrcNick()]], [[Manual:Networking_Functions#restartIrc|restartIrc()]]<br />
<br />
;Parameters:<br />
* ''nickname:''<br />
: A string with your new desired name in IRC.<br />
<br />
{{MudletVersion|3.3}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setIrcNick( "Sheldor" )<br />
</syntaxhighlight><br />
<br />
==setIrcServer==<br />
;setIrcServer(hostname, port[, secure])<br />
:Saves the given server's address to disk as the new IRC client connection configuration. These values are not applied to the current active IRC client until it is restarted with restartIrc()<br />
:See also: [[Manual:Networking_Functions#getIrcServer|getIrcServer()]], [[Manual:Networking_Functions#restartIrc|restartIrc()]]<br />
<br />
;Parameters:<br />
* ''hostname:''<br />
: A string containing the hostname of the IRC server.<br />
* ''port:''<br />
: (optional) A number indicating the port of the IRC server. Defaults to 6667, if not provided.<br />
* ''secure:''<br />
: (optional) Boolean, true if server uses Transport Layer Security. Defaults to false.<br />
<br />
{{MudletVersion|3.3}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setIrcServer("irc.libera.chat", 6667)<br />
</syntaxhighlight><br />
<br />
==getHTTP==<br />
;getHTTP(url, headersTable)<br />
: Sends an [https://en.wikipedia.org/wiki/GET_(HTTP) HTTP GET] request to the given URL. Raises [[Manual:Event_Engine#sysGetHttpDone|sysGetHttpDone]] on success or [[Manual:Event_Engine#sysGetHttpError|sysGetHttpError]] on failure.<br />
:See also: [[#downloadFile|downloadFile()]].<br />
<br />
[[File:Posthttp privacy logging.png.png|frame|For privacy transparency, URLs accessed are logged in the Central Debug Console]]<br />
<br />
;Parameters:<br />
* ''url:''<br />
: Location to send the request to.<br />
* ''headersTable:''<br />
: (optional) table of headers to send with your request.<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
function onHttpGetDone(_, url, body)<br />
cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s", url, body))<br />
end<br />
<br />
registerAnonymousEventHandler("sysGetHttpDone", onHttpGetDone)<br />
<br />
getHTTP("https://httpbin.org/info")<br />
getHTTP("https://httpbin.org/are_you_awesome", {["X-am-I-awesome"] = "yep I am"})<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- Status requests typically use GET requests<br />
local url = "http://postman-echo.com/status"<br />
local header = {["Content-Type"] = "application/json"}<br />
<br />
-- first we create something to handle the success, and tell us what we got<br />
registerAnonymousEventHandler('sysGetHttpDone', function(event, rurl, response)<br />
if rurl == url then display(r) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler<br />
end, true) -- this sets it to delete itself after it fires<br />
-- then we create something to handle the error message, and tell us what went wrong<br />
registerAnonymousEventHandler('sysGetHttpError', function(event, response, rurl)<br />
if rurl == url then display(r) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler<br />
end, true) -- this sets it to delete itself after it fires<br />
<br />
-- Lastly, we make the request:<br />
getHTTP(url, header)<br />
<br />
-- Pop this into an alias and try it yourself!<br />
</syntaxhighlight><br />
<br />
==postHTTP==<br />
;postHTTP(dataToSend, url, headersTable, file)<br />
: Sends an [https://en.wikipedia.org/wiki/POST_(HTTP) HTTP POST] request to the given URL, either as text or with a specific file you'd like to upload. Raises [[Manual:Event_Engine#sysPostHttpDone|sysPostHttpDone]] on success or [[Manual:Event_Engine#sysPostHttpError|sysPostHttpError]] on failure.<br />
:See also: [[#downloadFile|downloadFile()]], [[#getHTTP|getHTTP()]], [[#putHTTP|putHTTP()]], [[#deleteHTTP|deleteHTTP()]].<br />
<br />
[[File:Posthttp privacy logging.png.png|frame|For privacy transparency, URLs accessed are logged in the Central Debug Console]]<br />
<br />
;Parameters:<br />
* ''dataToSend:''<br />
: Text to send in the request (unless you provide a file to upload).<br />
* ''url:''<br />
: Location to send the request to.<br />
* ''headersTable:''<br />
: (optional) table of headers to send with your request.<br />
* ''file:''<br />
: (optional) file to upload as part of the POST request. If provided, this will replace 'dataToSend'.<br />
: If you use a scripting language (ex. PHP) to handle this post, remember that the file is sent as raw data. Expecially no field name is provided, dispite it works in common html post.<br />
<br />
{{MudletVersion|4.1}}<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
function onHttpPostDone(_, url, body)<br />
cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s", url, body))<br />
end<br />
<br />
registerAnonymousEventHandler("sysPostHttpDone", onHttpPostDone)<br />
<br />
postHTTP("why hello there!", "https://httpbin.org/post")<br />
postHTTP("this us a request with custom headers", "https://httpbin.org/post", {["X-am-I-awesome"] = "yep I am"})<br />
postHTTP(nil, "https://httpbin.org/post", {}, "<fill in file location to upload here, maybe get from invokeDialog>")<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- This will create a JSON message body. Many modern REST APIs expect a JSON body. <br />
local url = "http://postman-echo.com/post"<br />
local data = {message = "I am the banana", user = "admin"}<br />
local header = {["Content-Type"] = "application/json"}<br />
<br />
-- first we create something to handle the success, and tell us what we got<br />
registerAnonymousEventHandler('sysPostHttpDone', function(event, rurl, response)<br />
if rurl == url then display(response) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler<br />
end, true) -- this sets it to delete itself after it fires<br />
<br />
-- then we create something to handle the error message, and tell us what went wrong<br />
registerAnonymousEventHandler('sysPostHttpError', function(event, response, rurl)<br />
if rurl == url then display(response) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler<br />
end, true) -- this sets it to delete itself after it fires<br />
<br />
-- Lastly, we make the request:<br />
postHTTP(yajl.to_string(data), url, header) -- yajl.to_string converts our Lua table into a JSON-like string so the server can understand it<br />
<br />
-- Pop this into an alias and try it yourself!<br />
</syntaxhighlight><br />
<br />
;HTTP Basic Authentication Example:<br />
If your HTTP endpoint requires authentication to post data, HTTP Basic Authentication is a common method for doing so. There are two ways to do so.<br />
<br />
OPTION 1: URL encoding:<br />
Many HTTP servers allow you to enter a HTTP Basic Authentication username and password at the beginning of the URL itself, in format:<br />
https://username:password@domain.com/path/to/endpoint<br />
<br />
OPTION 2: Authorization Header:<br />
Some HTTP servers may require you to put your Basic Authentication into the 'Authorization' HTTP header value.<br />
<br />
This requires encoding the username:password into base64.<br />
For example, if your username is 'user' and your password is '12345', you'd need to run the string "user:12345" through a base64 encoder, which would result in the string:<br />
dXNlcjoxMjM0NQ==<br />
<br />
Then, you'd need to set the HTTP header 'Authorization' field value to indicate it is using Basic auth and inserting the base64 string as:<br />
['Authorization'] = "Basic dXNlcjoxMjM0NQ=="<br />
<br />
As you're encoding your username and password, you probably want to do this encoding locally for security reasons. You also probably want to only use https:// and not http:// when sending usernames and passwords over the internet.<br />
<br />
In the HTTP Basic Authentication example below, there is an inline base64Encode() function included:<br />
<br />
<syntaxhighlight lang="lua"><br />
function base64Encode(data)<br />
-- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de><br />
-- licensed under the terms of the LGPL2<br />
local b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'<br />
return ((data:gsub('.', function(x) <br />
local r,b='',x:byte()<br />
for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end<br />
return r;<br />
end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)<br />
if (#x < 6) then return '' end<br />
local c=0<br />
for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end<br />
return b:sub(c+1,c+1)<br />
end)..({ '', '==', '=' })[#data%3+1])<br />
end<br />
-- Example: base64Encode("user:12345") -> dXNlcjoxMjM0NQ== <br />
<br />
function postJSON(url,dataTable,headerTable)<br />
-- This will create a JSON message body. Many modern REST APIs expect a JSON body. <br />
local data = dataTable or {text = "hello world"}<br />
local header = headerTable or {["Content-Type"] = "application/json"}<br />
-- first we create something to handle the success, and tell us what we got<br />
registerAnonymousEventHandler('sysPostHttpDone', function(event, rurl, response)<br />
if rurl == url then sL("HTTP response success"); echo(response) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler<br />
end, true) -- this sets it to delete itself after it fires<br />
-- then we create something to handle the error message, and tell us what went wrong<br />
registerAnonymousEventHandler('sysPostHttpError', function(event, response, rurl)<br />
if rurl == url then sL("HTTP response error",3); echo(response) else return true end -- this will show us the response body, or if it's not the right url, then do not delete the handler<br />
end, true) -- this sets it to delete itself after it fires<br />
-- Lastly, we make the request:<br />
postHTTP(yajl.to_string(data), url, header) -- yajl.to_string converts our Lua table into a JSON-like string so the server can understand it<br />
end<br />
<br />
data = {<br />
message = "I am the banana",<br />
user = "admin"<br />
}<br />
header = {<br />
["Content-Type"] = "application/json",<br />
["Authorization"] = "Basic " .. base64Encode("user:12345")<br />
}<br />
postJSON("http://postman-echo.com/post",data,header)<br />
</syntaxhighlight><br />
<br />
;URL Encoding vs JSON encoding<br />
Some HTTP endpoints may not support JSON encoding, and instead may require URL encoding. Here's an example function to convert your lua data table into a URL encoded string::<br />
<syntaxhighlight lang="lua"><br />
-- Example: URLEncodeTable({message="hello",person="world"}) -> "message=hello&person=world"<br />
<br />
function URLEncodeTable(Args)<br />
-- From: https://help.interfaceware.com/code/details/urlcode-lua<br />
----------------------------------------------------------------------------<br />
-- URL-encode the elements of a table creating a string to be used in a<br />
-- URL for passing data/parameters to another script<br />
-- @param args Table where to extract the pairs (name=value).<br />
-- @return String with the resulting encoding.<br />
----------------------------------------------------------------------------<br />
--<br />
local ipairs, next, pairs, tonumber, type = ipairs, next, pairs, tonumber, type<br />
local string = string<br />
local table = table<br />
<br />
--helper functions: <br />
----------------------------------------------------------------------------<br />
-- Decode an URL-encoded string (see RFC 2396)<br />
----------------------------------------------------------------------------<br />
local unescape = function (str)<br />
str = string.gsub (str, "+", " ")<br />
str = string.gsub (str, "%%(%x%x)", function(h) return string.char(tonumber(h,16)) end)<br />
return str<br />
end<br />
<br />
----------------------------------------------------------------------------<br />
-- URL-encode a string (see RFC 2396)<br />
----------------------------------------------------------------------------<br />
local escape = function (str)<br />
str = string.gsub (str, "([^0-9a-zA-Z !'()*._~-])", -- locale independent<br />
function (c) return string.format ("%%%02X", string.byte(c)) end)<br />
str = string.gsub (str, " ", "+")<br />
return str<br />
end<br />
<br />
----------------------------------------------------------------------------<br />
-- Insert a (name=value) pair into table [[args]]<br />
-- @param args Table to receive the result.<br />
-- @param name Key for the table.<br />
-- @param value Value for the key.<br />
-- Multi-valued names will be represented as tables with numerical indexes<br />
-- (in the order they came).<br />
----------------------------------------------------------------------------<br />
local insertfield = function (args, name, value)<br />
if not args[name] then<br />
args[name] = value<br />
else<br />
local t = type (args[name])<br />
if t == "string" then<br />
args[name] = {args[name],value,}<br />
elseif t == "table" then<br />
table.insert (args[name], value)<br />
else<br />
error ("CGILua fatal error (invalid args table)!")<br />
end<br />
end<br />
end<br />
-- end helper functions <br />
<br />
if Args == nil or next(Args) == nil then -- no args or empty args?<br />
return ""<br />
end<br />
local strp = ""<br />
for key, vals in pairs(Args) do<br />
if type(vals) ~= "table" then<br />
vals = {vals}<br />
end<br />
for i,val in ipairs(vals) do<br />
strp = strp.."&"..key.."="..escape(val)<br />
end<br />
end<br />
-- remove first &<br />
return string.sub(strp,2)<br />
end<br />
</syntaxhighlight><br />
<br />
==putHTTP==<br />
;putHTTP(dataToSend, url, [headersTable], [file])<br />
: Sends an [https://en.wikipedia.org/wiki/PUT_(HTTP) HTTP PUT] request to the given URL, either as text or with a specific file you'd like to upload. Raises [[Manual:Event_Engine#sysPutHttpDone|sysPutHttpDone]] on success or [[Manual:Event_Engine#sysPutHttpError|sysPutHttpError]] on failure.<br />
:See also: [[#downloadFile|downloadFile()]], [[#getHTTP|getHTTP()]], [[#postHTTP|postHTTP()]], [[#deleteHTTP|deleteHTTP()]].<br />
<br />
[[File:PutHTTP privacy logging.png|frame|For privacy transparency, URLs accessed are logged in the Central Debug Console]]<br />
<br />
;Parameters:<br />
* ''dataToSend:''<br />
: Text to send in the request (unless you provide a file to upload).<br />
* ''url:''<br />
: Location to send the request to.<br />
* ''headersTable:''<br />
: (optional) table of headers to send with your request.<br />
* ''file:''<br />
: (optional) file to upload as part of the PUT request. If provided, this will replace 'dataToSend'.<br />
<br />
{{MudletVersion|4.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function onHttpPutDone(_, url, body)<br />
cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s", url, body))<br />
end<br />
<br />
registerAnonymousEventHandler("sysPutHttpDone", onHttpPutDone)<br />
putHTTP("this us a request with custom headers", "https://httpbin.org/put", {["X-am-I-awesome"] = "yep I am"})<br />
putHTTP("https://httpbin.org/put", "<fill in file location to upload here>")<br />
</syntaxhighlight><br />
<br />
==deleteHTTP==<br />
;deleteHTTP(url, headersTable)<br />
: Sends an [https://en.wikipedia.org/wiki/DELETE_(HTTP) HTTP DELETE] request to the given URL. Raises [[Manual:Event_Engine#sysDeleteHttpDone|sysDeleteHttpDone]] on success or [[Manual:Event_Engine#sysDeleteHttpError|sysDeleteHttpError]] on failure.<br />
:See also: [[#downloadFile|downloadFile()]], [[#getHTTP|getHTTP()]], [[#postHTTP|postHTTP()]], [[#putHTTP|putHTTP()]].<br />
<br />
[[File:PutHTTP privacy logging.png|frame|For privacy transparency, URLs accessed are logged in the Central Debug Console]]<br />
<br />
;Parameters:<br />
* ''url:''<br />
: Location to send the request to.<br />
* ''headersTable:''<br />
: (optional) table of headers to send with your request.<br />
<br />
{{MudletVersion|4.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function onHttpDeleteDone(_, url, body)<br />
cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s", url, body))<br />
end<br />
<br />
registerAnonymousEventHandler("sysDeleteHttpDone", onHttpDeleteDone)<br />
<br />
deleteHTTP("https://httpbin.org/delete")<br />
deleteHTTP("https://httpbin.org/delete", {["X-am-I-awesome"] = "yep I am"})<br />
</syntaxhighlight><br />
<br />
==customHTTP==<br />
;customHTTP(method, url, headersTable)<br />
: Sends an custom method request to the given URL. Raises [[Manual:Event_Engine#sysCustomHttpDone|sysCustomHttpDone]] on success or [[Manual:Event_Engine#sysCustomHttpError|sysCustomHttpError]] on failure.<br />
:See also: [[#downloadFile|downloadFile()]], [[#getHTTP|getHTTP()]], [[#postHTTP|postHTTP()]], [[#putHTTP|putHTTP()]], [[#deleteHTTP|deleteHTTP()]].<br />
<br />
;Parameters:<br />
* ''method:''<br />
: Http method to use (eg. PATCH, HEAD etc.)<br />
* ''dataToSend:''<br />
: Text to send in the request (unless you provide a file to upload).<br />
* ''url:''<br />
: Location to send the request to.<br />
* ''headersTable:''<br />
: (optional) table of headers to send with your request.<br />
* ''file:''<br />
: (optional) file to upload as part of the PUT request. If provided, this will replace 'dataToSend'.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function onCustomHttpDone(_, url, body, method)<br />
cecho(string.format("<white>url: <dark_green>%s<white>, body: <dark_green>%s<white>, method: <dark_green>%s", url, body, method))<br />
end<br />
<br />
registerAnonymousEventHandler("sysCustomHttpDone", sysCustomHttpDone)<br />
<br />
customHTTP("PATCH", "this us a request with custom headers", "https://httpbin.org/put", {["X-am-I-awesome"] = "yep I am"})<br />
customHTTP("PATCH", "https://httpbin.org/put", "<fill in file location to upload here>")<br />
</syntaxhighlight><br />
<br />
[[Category:Mudlet API]]<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Release_Checklist&diff=20894Release Checklist2024-01-31T20:57:46Z<p>Kebap: Move release day step 13 after step 10</p>
<hr />
<div>= Mudlet release checklist =<br />
# 5 days before the release (14 if it's a long one)<br />
## ☐ [automated] update <code>mudlet.ts</code> with the latest translations strings for translators to translate<br />
## ☐ [automated] update <code>mudlet_en_US.ts</code> with the latest translation strings, translate/update the few plural forms it contains as necessary and then generate the binary translation <code>mudlet_en_US.qm</code> file and merge it into the repo (see [https://wiki.mudlet.org/w/Translating_Mudlet#English_.28American.29_translation Translating Mudlet - English (American) translation]).<br />
## ☐ [automated] update [http://www.mudlet.org/geyser/files/index.html Geyser docs]<br />
## ☐ [automated] update built-in packages and scripts (IRE mapping script, ...)<br />
## ☐ [automated] update edbee to latest in our fork, and the subsequent submodule<br />
## ☐ merge outstanding approved pull requests<br />
## ☐ update Patreon supporters in About tab<br />
## ☐ create a new <code>release-<version></code> branch off <code>development</code><br />
### everything above this step can be done concurrently.<br />
## ☐ create the next milestone in github if it doesn't exist already<br />
## ☐ go through every single commit (in main repo and installers) and ensure all new functionality is documented<br />
## ☐ check all [https://github.com/Mudlet/Mudlet/issues?q=is%3Aissue+is%3Aopen+label%3Aregression regressions] to see if any must be fixed before the release<br />
## ☐ go through every single commit and write up a relese post with the latest highlights - and save it as a github milestone draft<br />
### everything above this step can be done concurrently, while 13, 14, and 15 below must be done sequentially.<br />
## ☐ wait a day for PTBs to get built<br />
## ☐ after the PTBs have been built, announce start of testing in Discord channel #mudlet-testing with the list of additions/improvements/fixes (but not infrastructure), and add link to latest download builds (from [https://make.mudlet.org/snapshots Latest Branch Snapshots], but double check that sha matches [https://github.com/Mudlet/Mudlet/commits/development the latest commit]).<br />
## ☐ get testers to sign off (via Discord reaction) that they tested the release and it is fine with them<br />
### if a tester doesn't sign off for 2 releases, notify them, if they don't do it on the next one, remove them from the testers team<br />
# on release day<br />
## ☐ merge latest translations from Crowdin<br />
## ☐ merge all Area 51 functions into main wiki<br />
## ☐ [https://wiki.mudlet.org/w/Manual:Lua_Functions?action=purge purge] Lua_Functions cache to ensure the latest functions are visible<br />
## ☐ merge [[Update_lua_function_list|latest autocomplete json]]<br />
### everything above this step can be done concurrently, while everything below this step must be done sequentially.<br />
## ☐ create a new release in the 'release' channel in [https://www.dblsqd.com/user/apps/30a30c47-b1cd-48fe-b93e-ab9041b88323 dblsqd]. Make sure to enter the changelog right away, as it cannot be edited after. Include the full version number and a link to the release post ([[Media:Creating a new Mudlet release.png|example]]). A [https://www.npmjs.com/package/dblsqd-cli command-line variant] of this is: <code>dblsqd release -a mudlet -c release -m "<message>. <a href="https://mudlet.org/4-##">See the changelog</a>." <version, ie 4.11.0></code><br />
## ☐ update mudlet.pro and CMakeLists.txt to new version and strip out BUILD to be empty in release branch (release process starts here)<br />
## ☐ tag release in git and push<br />
## ☐ manually create source code package [https://github.com/Mudlet/Mudlet/blob/33ad832253d6b6411d7c1132e68455742157d60d/CI/travis.linux.after_success.sh#L144 following this]<br />
## ☐ reset BUILD in release branch to be -dev<br />
## ☐ wait for the builds to complete...<br />
## ☐ test that all binaries launch and work<br />
## ☐ manually upload artifacts to https://www.mudlet.org/wp-content/files/?C=M;O=D through webmin. Linux and macOS ones will be available as artifacts on the Github job, while Windows is an artifact on the Appveyor job.<br />
## ☐ manually link uploaded artifacts to dblsqd (see [1])<br />
## ☐ update [https://github.com/Mudlet/Mudlet/blob/development/.github/repo-metadata.yml repo-metadata.yml] to the next release version<br />
## ☐ close current github milestone<br />
## ☐ [[Howto:Update Downloads|update downloads on mudlet.org]]<br />
## ☐ [automated] create changelog with [https://github.com/Mudlet/Mudlet/actions/workflows/generate-changelog.yml a github action]<br />
## ☐ create a proper github release using the draft created earlier<br />
## ☐ [automated] insert list of translators into the release post ([https://www.mudlet.org/thank-translators/crowdin.php tool])<br />
## ☐ [automated] insert list of coders into the release post ([https://github.com/Mudlet/Mudlet/actions/workflows/generate-coder-attribution.yml tool])<br />
## ☐ publish release post and it will be automatically posted to mudlet.org on save<br />
## ☐ delay rest of announcements until 3-4 days past the release; post when there are no verified issues in update<br />
### everything above the step must be done sequentially, while everything below this step can be done concurrently.<br />
## ☐ post to #announcements in Discord. Publish the post, then add a follow-up @everyone tag as a separate post. This will notify folks in the Mudlet server without showing the @everyone tag in all other syncronised servers<br />
## ☐ post news to https://launchpad.net/mudlet<br />
## ☐ post thread on forums.mudlet.org<br />
## ☐ post update on achaea, starmourn, imperian, lusternia, pkuxkx.net, [http://linux.softpedia.com/get/GAMES-ENTERTAINMENT/MUD/Mudlet-45973.shtml softpedia]<br />
## ☐ post update on twitter, reddit, http://arkadia.rpg.pl, muder.ru<br />
## ☐ email to releaseradar@github.com about the update<br />
## ☐ submit mudlet windows installer to avg and avast whitelisting<br />
## ☐ update Linux distro maintainers, [https://chocolatey.org/packages/mudlet/ContactOwners Chocolatey maintainer], flag package outdated on arch<br />
## ☐ merge <code>development</code> into <code>master</code> branch<br />
## ☐ merge, don't squash or rebase, the release branch into development (but don't delete right away, keep it around for a potential hotfix if needed. Delete after the next release is done). Do it right away so next day's PTB's versions is the new release.<br />
## ☐ [https://www.mudlet.org/2021/10/trial-pay-out-to-popular-prs/ create polls] for most popular changes<br />
<br />
<br />
[1]:<br />
<br />
dblsqd push -a mudlet -c release -r "<release>" -s mudlet --type "standalone" --attach linux:x86_64 "https://www.mudlet.org/wp-content/files/Mudlet-<release>-linux-x64.AppImage.tar"<br />
dblsqd push -a mudlet -c release -r "<release>" -s mudlet --type "standalone" --attach mac:x86_64 "https://www.mudlet.org/wp-content/files/Mudlet-<release>.dmg"<br />
dblsqd push -a mudlet -c release -r "<release>" -s mudlet --type "standalone" --attach win:x86 "https://www.mudlet.org/wp-content/files/Mudlet-<release>-windows-installer.exe"<br />
<br />
<br />
= Individual contributor TODOs =<br />
* keneanung: https://github.com/users/keneanung/projects/1<br />
* vadi2: https://gist.github.com/vadi2/c4dd137010c1b969c011293eddfcee73<br />
<br />
[[Category: Mudlet Admin Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Mapper&diff=20877Manual:Mapper2024-01-23T18:45:44Z<p>Kebap: /* Making your own mapping script */</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Manual on creating maps, areas, rooms, and advanced features like autowalking, creating lables, custom exit lines, etc.}}<br />
<br />
= Mapper =<br />
Mudlet's mapper is split into two parts for the best compatibility on all games: <br />
# The display of the map itself and functions to modify the map in Mudlet, and <br />
# A very game-specific Lua script to track where you are, and provide aliases for using the mapper, automatic mapping, etc.<br />
<br />
If your game does not provide a mapping script for you, then you may not see a map at first. <br />
<br />
Fear not! Pre-made mapping scripts for many games are available from [https://forums.mudlet.org/search.php?keywords=mapping+script&terms=all&author=&sc=1&sf=titleonly&sr=topics&sk=t&sd=d&st=0&ch=400&t=0&submit=Search Mudlet forums] - all topics that have the "mapping script"-prefix on them. <br />
<br />
If you still don't find any, or if you want to create your own mapping script, see [[#Making your own mapping script]] further down below. Remember, you can always find help in Mudlet forums or Discord, etc. <br />
<br />
==Visual Map Editor==<br />
Maps can be comfortably edited by using the visual map editor or by scripts. The editor behaves like the usual WYSIWYG editors. Select objects with a left click and then right click to open a context menus and do actions on the selected objects.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
The mapper starts in "view-only" mode to prevent accidental edits. The editing mode can be toggled in the map's right-click menu.<br />
<br />
===Object selection===<br />
<br />
* left click = select element<br />
* left click + drag = sizing group selection box choosing all rooms in the box on the current z-level<br />
* left click + shift + drag = sizing group selection box choosing all rooms in the box on all z-levels<br />
* left click + alt (or the mapper menu move map buttons) = move map<br />
* left click + control = add a room to current group selection or remove it<br />
<br />
If multiple rooms are being selected, a room id selection list box is being shown where you can fine tune the current room selection via the usual ''left click + control'' or ''left click + shift''. The box disappears if the number of rooms in group selection is zero.<br />
<br />
===Moving Objects===<br />
Move selected objects either by right click and select "move" or with following handy short cut:<br />
<br />
* left button down on custom line point + drag = move custom line point<br />
* left button down + drag usually moves the item directly (as a handy shortcut) if only one element has been selected<br />
* '''or''' hold left button down + control + drag if multiple rooms have been selected<br />
<br />
== Maps and Autowalking ==<br />
Maps are implemented as directed graphs of connected nodes (rooms). Nodes are connected by edges (exits). Nodes are referenced by unique integer IDs. Edges fall into 2 categories: Standard exits with a visual representation on the map (e. g. north, south) and "special exits" without a calculated visual representation on the map e. g. the command "jump cliff" is a special exit that connects to a room without a clear spatial orientation. However, special exits can be visually represented if the user provides custom exit line strips. Standard exits are referenced by their respective node and a directional integer value. Special exits are referenced by their respective nodes and strings that hold the exit commands. Both nodes and individual exits can seperately be locked and thus excluded from speed walk path finding graphs. Path finding uses the fast A* search algorithm. Mudlet choses a path with the fastest travel time (-> room weights) as opposed to the shortest path.<br />
<br />
Maps are divided into areas or zones where the area/room relationship is unique, i. e. rooms cannot be in more than 1 area. <br />
<br />
{{note}}Areas help make do with the typical geographical irregularities of game maps where an entire city with hundrets of rooms makes up a single room on a wilderness map. In other words, if you can't make a place look geographically correctly, create (sub) areas to deal with the problem.<br />
<br />
There are 2 forms of visual representations of maps. Standard mode shows exits and custom exit lines whereas "grid mode" hides exit details and sizes rooms to form a perfect grid without any empty space in between rooms. Grid maps can be made to look exactly like ASCII color text maps with character symbols to keep the look and feel of the game. Technically, grid maps are a special optimized representation of the typically very large LPC MUD style wilderness maps where every room has 8 direct neighbors in a n*m grid of rooms with relatively few holes. The grid map implementation uses pre image caching and fast gfx hardware render support and can thus render very large grid maps in less than 1ms that would take much longer if the map were to be displayed in regular mode. Changing the zoom level of maps in grid mode can take a significant amount of time if the maps are very large, because the pre cached images of the map need to be recreated at the new zoom level. Areas remember their particular zoom level so this is no hindering issue in actual gameplay.<br />
<br />
Any map can be displayed in both modes, though the visual map editor only works in regular mode. To enable area mode, use the [[Manual:Lua Functions#setGridMode|setGridMode()]] function.<br />
<br />
Regular mode:<br />
<br />
[[File:Mapper-regular-mode.png|frameless|716x716px]]<br />
<br />
Grid mode:<br />
<br />
[[File:Mapper-grid-mode.png|frameless|713x713px]]<br />
=== Areas ===<br />
Areas are defined by a unique integer number ID and a unique area name. Mudlet builds an internal numerical area ID table on the basis of the rooms that belong to the respective areas. Mudlet keeps a seperate lookup table to retrieve the area name on the basis of the area IDs. This name lookup table is not guaranteed to be correct because it may be imported invalid information if the map has been downloaded by the game server as an xml map description file on the basis of the MMP protocol. <ref>MMP allows for an area ID/area names table to be defined, but Mudlet has no means to verify which definition is the correct one if 2 different area names relate to the same area ID.</ref> However, if the map has been created with Mudlet directly, there will be no such problems as the area name lookup table API is made to enforce uniqueness.<br />
<br />
==== Area Properties ====<br />
* area map display mode (-> regular map display mode or grid mode)<br />
* area name<br />
<br />
=== Rooms ===<br />
Rooms are invisible on the map unless the required properties have been set.<br />
==== Room Properties ====<br />
*Room object need following required properties in order to be shown on the respective area map:<br />
** unique room ID in form of an integer value <br />
** area ID in form of an integer value (To which area does this room belong - or in other words, which area map displays this room)<br />
** x, y and z coordinates as integer values which relate to its paricular area map coordinate system<br />
<br />
*Optional room properties:<br />
** regular exits with or without respective exit locks<br />
** special exits with or without respecitve special exit locks<br />
** room lock<br />
** exit stubs (draw exit directions even though the exit rooms have not yet been defined)<br />
** custom exit lines (user defined line strips of various formats to visualize special exits or redefine regular exit lines)<br />
** searchable room name that can be used for bookmarks, annotations etc. <br />
** room weight (How long does it travel through this node. A high room weight makes it less likely that this room will be chosen for pathfinding e. g. a safe road should have a low weight, whereas a dangerous place should have a high weight<br />
** room color<br />
** room character e. g. the symbol $ to symbolize a bank or H for a hotel.<br />
<br />
== Advanced map features ==<br />
=== Map labels ===<br />
Maps can be embellished with images and text labels. Map labels can be either used as background (default) or as the top most foreground e. g. for player name location scripts. Labels are defined by position and size according to the map coordinate system and keep their position and size relative to the rest of the map when the map is zoomed or moved.<br />
Contrary to rooms which work on the basis of integer (natural numbers) coordinates, labels are described (with respect to both position & size) by real numbers in order to allow for more advanced placement and label sizes within the map coordinate system. Map labels are stored in form of png images directly in the map file and are thus a direct part of the map. As these images are being scaled to fit the label creation size, the image quality will depend on the initial size of the label (the large the better the quality, but the more memory will be used).<br />
<br />
[[File:MapTextLabelDemo.PNG|250px|frameless|misc label types]]<br />
[[File:MalLabelsScaled.PNG|250px|frameless|zoomed]]<br />
[[File:MapBackgroundImageLabel.PNG|250px|frameless|label as background image]]<br />
<br />
(The desert and dragon images used in this example are licensed under the Creative Commons Attribution 2.0 Generic license and can be found here: http://en.wikipedia.org/wiki/File:Ninedragonwallpic1.jpg and http://en.wikipedia.org/wiki/File:Siwa_sand_dunes2009a.jpg)<br />
<br />
=== Custom exit line definitions ===<br />
The mapper supports user defined visual exit lines on the basis of a sequence of line points in the map coordinate system. Custom lines as well as labels work on real numbers to allow for fine grained placement. User defined lines can be solid, dotted, dashed etc. line types with or without ending arrows. The line color can be freely selected. By default the regular exit color is being used.<br />
<br />
[[File:CustomExitSelection.PNG|400px|frameless|custom exit line demo]] [[File:DifficultGeography.PNG|500px|frameless|custom exit line demo]]<br />
<br />
The above example shows 3 different types of user defined exit lines, where the orange one on the left has been selected by the user in order to be edited.<br />
<br />
Custom exit lines are purely visual tools and have no effect on the pathfinding, but each custom line must be linked to a valid room exit - either standard or special exit.<br />
<br />
=== Map formats ===<br />
Whenever a mapping feature is added to Mudlet that requires storing something in the map, the map format version needs to be increased - so older Mudlets can know that a map is too new and they can't load it. To this end, every map has a version number embedded inside it, which you can see by going to mapper settings:<br />
<br />
[[File:Map formats setting.png]]<br />
<br />
You'll also notice that you have the ability to downgrade a map's version for compatibility with older Mudlets. Be careful when you do so though - features available in the new map won't be available in the older map when you downgrade. Here's a table of all the versions and features:<br />
<br />
{| class="wikitable"<br />
! style="font-weight: bold;" | version<br />
! style="font-weight: bold;" | Mudlet version<br />
! style="font-weight: bold;" | features<br />
|-<br />
| 20<br />
| 3.16.0<br />
| - Improved way that custom exit line data was held internally, to make coding Mudlet mapper's easier and safer ([https://github.com/Mudlet/Mudlet/pull/2999 details]). Code is in place to support a workaround to work within map formats back to include version 17.<br />
|- <br />
| 19<br />
| 3.8.0<br />
| - added support for more than one of any grapheme (symbol) for the 2D map room symbol. Code is in place to support a workaround to work within map formats back to including version 17.<br />
|-<br />
| 18<br />
| 3.0.0<br />
| - keeps player's position when copying to a new profile<br />
- faster map loading<br />
|-<br />
| 17<br />
| 3.0.0<br />
| - allows use of setAreaUserData(), setMapUserData(), and related functions<br />
|-<br />
| 16<br />
| 2.1<br />
| - doors (visual effect on the mapper that a locked/closed/open door is there)<br />
- exit weights (in addition to existing room weights)<br />
|}<br />
<br />
== Mapper tips ==<br />
<br />
=== General ===<br />
<br />
* Don't move the room you're currently in, you'll go haywire<br />
* The number when spreading/shrinking room selections it the ''multiplication'' factor - 2 is a good number to try<br />
<br />
=== Merging areas ===<br />
<br />
To merge two areas together, see [https://forums.mudlet.org/viewtopic.php?f=8&t=2273&view=unread#unread this how-to by Heiko]. In short:<br />
<br />
# Zoom out ''really'' far away on the area you'd like to move, and select everything (the selection affects all z-levels as well). <br />
# Right-click, select ''move to area'', and move them to another area. Your selection will still be selected - do '''not''' unselect <br />
# Right-click again, select ''move to position'', and move all of your still selected rooms in the new area so it fits.<br />
<br />
=== Zooming the mapper ===<br />
<br />
You can zoom in/out in the mapper using your (vertical) mousewheel. If you'd like to zoom quicker, hold down <code>Ctrl</code> while doing so!<br />
<br />
To set the zoom level via script, use [[Manual:Mapper_Functions#setMapZoom|setMapZoom()]].<br />
<br />
<br />
=== Add a right-click menu to your mapper ===<br />
<br />
It is easy to add your own options to the menu you see when you right-click on your map. To do so, use [[Manual:Mapper_Functions#addMapMenu|addMapMenu]], [[Manual:Mapper_Functions#addMapEvent|addMapEvent]], etc.<br />
<br />
==== Mapper favorites ====<br />
<br />
[http://forums.mudlet.org/viewtopic.php?f=6&t=2739 This post here] describes how to add a right click menu to your mapper filled with rooms to speedwalk to.<br />
<br />
=== Placing the mapper ===<br />
<br />
==== Placing the mapper into a corner ====<br />
<br />
Here's a snippet you can use to place the mapper window into a corner and have it automatically come up whenever you open Mudlet. To use this, create a new script (you can make it anywhere) and copy/paste the code into it.<br />
<br />
<syntaxhighlight lang="lua" highlight="5" line><br />
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})<br />
<br />
local mapper = Geyser.Mapper:new({<br />
name = "mapper",<br />
x = "70%", y = 0, -- edit here if you want to move it<br />
width = "30%", height = "50%"<br />
}, main)<br />
</syntaxhighlight><br />
==== Placing the mapper into its own window ====<br />
<br />
{{MudletVersion|4.7+}}<br />
<br />
It's possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded=false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation, use:<br />
<syntaxhighlight lang="lua"> -- this will create a map window docked at the left corner<br />
myMapWidget = Geyser.Mapper:new({embedded=false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are: left "l", right "r", top "t", bottom "b" and floating "f"<br />
<br />
To change the dockPosition after creation, use:<br />
<syntaxhighlight lang="lua"> -- this will change myMapWidget dockPosition to "f" floating <br />
myMapWidget:setDockPosition("f")<br />
</syntaxhighlight><br />
<br />
== Making your own mapping script ==<br />
<br />
Your own mapping script will need to be tailored specifically to your game, depending on how exactly your rooms are shown, how the exits are listed, or if the game maybe sends some of this relevant information via GMCP, etc. <br />
<br />
=== The generic mapper ===<br />
To ease your work, all new profiles in Mudlet come with a [[Generic mapper package]], which tries to draw a map by guessing most of the information from your game. It knows the most common ways to write an exit, etc. You can find more details by typing "map basics" in Mudlet.<br />
<br />
Even if the generic mapper does not 100% grasp your very game details, you could maybe just adjust a few triggers and be done with it. Remember to stop by and ask for help in forums or chat, if you get stuck anywhere.<br />
<br />
Some players have collected a list of [[Generic Mapper Additions]] on how to modify the generic mapper to better fit their game already.<br />
<br />
=== Starting from scratch ===<br />
If you'd like to code your own mapping script, see the [[Manual:Lua_Functions#Mapper_Functions|Mapper API]] and read on for a short tutorial.<br />
<br />
To start off, create a new script that'll be included with your mapping script (can even place it into the script folder for your mapping script), and have it do:<br />
<br />
<syntaxhighlight lang="lua"><br />
mudlet = mudlet or {}; mudlet.mapper_script = true<br />
</syntaxhighlight><br />
<br />
This'll let Mudlet know that a mapping script is installed, so it won't bother you or whoever else installs your script with a warning that one is necessary.<br />
<br />
Next, you want to hook into Mudlet's gotoRoom(id) function and the user clicking on a room in the visual map - for that, define your own ''doSpeedWalk()'' function. Mudlet will store the directions / special exits commands your script will need to take in the ''speedWalkDir'' table, and the room IDs you'll pass through in the ''speedWalkPath'' table:<br />
<br />
<syntaxhighlight lang="lua"><br />
function doSpeedWalk()<br />
echo("Path we need to take: " .. table.concat(speedWalkDir, ", ") .. "\n")<br />
echo("Rooms we'll pass through: " .. table.concat(speedWalkPath, ", ") .. "\n")<br />
end<br />
</syntaxhighlight><br />
<br />
''speedWalkPath'' is especially useful for making sure you're still on the path. Most Mudlet mapping scripts keep track of how many rooms along the path they have visited so far and check upon arrival into a new room to make sure it's still on the path.<br />
<br />
That's it! (But see below if you want more.)<br />
<br />
From here, you'd want to build a walking script that'll send the commands to walk you along the path, along with aliases for the user to use - see the [[Manual:Lua_Functions#Mapper_Functions|Mapper API functions]] and [[Manual:Event_Engine#Mudlet-raised_events|Mudlet mapper events]].<br />
<br />
=== Adding rooms ===<br />
To make your first room, do the following steps:<br />
<br />
* create an area with setAreaName(areaID, areaname). You can choose any areaID - if you'd like to use the IDs incrementally, see which is the latest from getAreaTable()<br />
* if you want the Mudlet mapper to generate roomIDs for you, get one with createRoomID(). This is an optional step<br />
* create your room with addRoom(roomID)<br />
* give the room coordinates with setRoomCoordinates(roomID, x, y, z). If you're just starting out, put it at 0,0,0 so the room is at the center of the map<br />
* assign your room to an area with setRoomArea(roomID, areaID)<br />
* and finally, call centerview(roomID) to make the map view refresh and show your new room!<br />
<br />
==== Labelling rooms ====<br />
<br />
Rooms have three attributes which you can show on the map:<br />
* an ID. You can't change it; the ID is shown in the room's box when you check "IDs" in the dialog below the map and you're zoomed in far enough.<br />
* a symbol, also displayed in the room's box. You set it with the [https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomChar ''setRoomChar''] Lua function, or via the map's context menu.<br />
* a name, typically sent via GMCP. You add it to the map with [https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomName ''setRoomName''].<br />
<br />
The room name can be displayed along with a room's box. Its position defaults to "centered below the room". It is not visible by default because many maps have rooms that are quite close to each other; showing the names by default would create an ugly visual mess.<br />
<br />
If you want to enable room names in your mapper, you need to<br />
* stagger rooms. Four or five units' distance instead of one works best if you want to show every label; less is OK if you only show labels when the user asks you to.<br />
* call ''setMapUserData("room.ui_showName","1")''. The existence of this entry controls whether the "Names" checkbox is shown next to "IDs", below the map. This value is zero if the user has unchecked the "Names" checkbox.<br />
* optionally call ''setMapUserData("room.ui_nameFont","FontName")'' to change the names' font. The default is the same monospaced font used for the room IDs and symbols.<br />
* call ''setRoomUserData(room_id, "room.ui_showName","1")'' to show a room's label. You might want to add an entry to the map's pop-up menu which toggles this.<br />
<br />
If the name is misplaced (collision with another room, label, or whatever), you can modify the room's "room.ui_nameOffset" attribute to move it around. The value of this attribute consists of two floating-point values, separated by a space, which offset the room's label (in units of the room box's size). You might want to bind functions that increase or decrease these values to keys like Shift-Control-Arrow and/or Control-Numpad-2468. A hotkey to toggle a room's label display from "on" to "off" and back (e.g. Control-Numpad-5?) is also a good idea.<br />
<br />
You also might default to staggering room names. One possible algorithm: '''if''' a new room's X coordinate, divided by your default room distance, is an odd number '''then''' position its label with an offset like "0 -1.6", which would place it above the room in question. The optimal value for the Y offset depends on the font.<br />
<br />
Changes are displayed only when the map is next redrawn.<br />
<br />
Font options are global. Overriding them for a single room can be be implemented if requested.<br />
<br />
=== Working with the mapper API ===<br />
Whenever working with mapper API, keep in mind of the following things:<br />
<br />
* You'll want to call centerview after you do some modifications, to get to have the map render your new changes<br />
<br />
=== Translating directions ===<br />
Several functions in the mapper API take and return #'s for directions - and to make it easier to work with them, you can define a table that maps directions to those numbers in a script with the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
exitmap = {<br />
n = 1,<br />
north = 1,<br />
ne = 2,<br />
northeast = 2,<br />
nw = 3,<br />
northwest = 3,<br />
e = 4,<br />
east = 4,<br />
w = 5,<br />
west = 5,<br />
s = 6,<br />
south = 6,<br />
se = 7,<br />
southeast = 7,<br />
sw = 8,<br />
southwest = 8,<br />
u = 9,<br />
up = 9,<br />
d = 10,<br />
down = 10,<br />
["in"] = 11,<br />
out = 12,<br />
[1] = "north",<br />
[2] = "northeast",<br />
[3] = "northwest",<br />
[4] = "east",<br />
[5] = "west",<br />
[6] = "south",<br />
[7] = "southeast",<br />
[8] = "southwest",<br />
[9] = "up",<br />
[10] = "down",<br />
[11] = "in",<br />
[12] = "out",<br />
}<br />
</syntaxhighlight><br />
<br />
Then, using exitmap[input], you'll get a direction number or a direction name. Here's an example that uses it to work out in which directions are the exit stubs available in room 6:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local stubs = getExitStubs(6)<br />
for i = 0, #stubs do print(exitmap[stubs[i]]) end<br />
</syntaxhighlight><br />
<br />
=== Custom speedwalking and pathfinding ===<br />
<br />
{{MudletVersion|4.10}}<br />
If you'd like to use a custom pathfinding algorithm instead of the built-in one, you can do that:<br />
<br />
* Set ''mudlet.custom_speedwalk = true''.<br />
* Your ''doSpeedwalk'' script will now see different parameters:<br />
<br />
<syntaxhighlight lang="lua"><br />
function doSpeedWalk()<br />
echo("Room we're coming from: " .. speedWalkFrom .. "\n")<br />
echo("Room you're going to: " .. speedWalkTo .. "\n")<br />
end<br />
</syntaxhighlight><br />
<br />
The forum topic [https://forums.mudlet.org/viewtopic.php?f=6&t=22930&p=45930#p45930 Wayfinder] contains an example package that implements a shortest-path-first algorithm.<br />
<br />
=== Custom room name search function in the generic_mapper ===<br />
<br />
{{MudletVersion|4.11}}<br />
Sometimes the generic_mapper script is not flexible enough to find the room name in your favorite game. You can create a custom function that handle that search instead of the standard one included in the mapper:<br />
<br />
* Type in the input area ''map config custom_name_search true'' to enable the usage of the custom function.<br />
* Write your own function called ''mudlet.custom_name_search''. The script call it for your:<br />
<br />
<syntaxhighlight lang="lua"><br />
mudlet.custom_name_search = function (lines)<br />
-- ...<br />
local line_count = #lines + 1<br />
if string.match(cur_line, " ") then<br />
line_count = line_count - 1<br />
room_name = lines[line_count]<br />
-- map.echo("Name Search: room_nameome:" ..room_name) <br />
elseif string.find(cur_line,prompt_pattern) then<br />
-- ...<br />
return room_name<br />
end<br />
</syntaxhighlight><br />
<br />
I suggest to start from original name_search function in generic_mapper to avoid common problem.<br />
<br />
=== onVisionFail for generic_mapper - moving through dark rooms ===<br />
generic_mapper uses a combination of room titles, descriptions and exits to locate your character position in the mapper. Sometimes this information may not be available due to blindness, dark rooms or other affects that may prevent full vision and correct room matching. Using the <code>onVisionFail</code> event and appropriate triggers you can force your character to move to the next room and update the map accordingly even when vision is limited.<br />
<br />
generic_mapper comes with two predefined triggers, add or replace these as necessary with the appropriate lines your game sends.<br />
[[File:English Vision Fail Triggers.png|alt=Predefined triggers in generic_mapper calling onVisionFail event.|none|thumb|843x843px|Predefined triggers in generic_mapper calling onVisionFail event.]]<br />
In these examples when the game sends <code>It is pitch black...</code> or <code>It's too dark</code> or <code>It is too dark</code> starting on a newline (<code>^</code> character) then it will raise the <code>onVisionFail</code> event. When called this event will skip looking to match the room, and simply move the character in the direction they sent prior.<br />
<br />
== Screenshots ==<br />
Just a few example maps from different players and games:<br />
<gallery><br />
File:Mapper 562.png<br />
File:Mudlet 563.png<br />
File:TK6fS.png<br />
File:Stary kontynent-min-scaled.png|Here is the [https://i.imgur.com/IaV6lDc.png full image] (17160 x 10120 pixel)<br />
File:MG Port Vain.png<br />
</gallery><br />
<br />
== Notes ==<br />
<references /><br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Talk:Main_Page&diff=20876Talk:Main Page2024-01-23T18:40:48Z<p>Kebap: /* Redesign */ +1</p>
<hr />
<div>== Redesign ==<br />
<br />
So I'm thinking a redesign of this page with 6 or so sections with some minor subsections (and maybe some nice images to add some appeal).<br />
Maybe with the launch of dt192's theme ideas?<br />
<br />
* About Mudlet<br />
** Contact methods, forums, discord, etc<br />
<br />
* Downloads<br />
** Main download area<br />
** Dev and Compiling<br />
** PTB<br />
<br />
* Tutorials<br />
** current wiki walkthroughs<br />
** learn lua<br />
** regex<br />
<br />
* Manual<br />
** main manual<br />
** technical API<br />
<br />
* Accessibility<br />
** packages<br />
** screen readers<br />
<br />
and removal of <br />
<br />
* Standards - I don't think the casual user is interested in the tech details,<br />
* Special links - already available on sidebar<br />
* Mediawiki links - already available on sidebar<br />
<br />
<br />
--[[User:Zooka|Zooka]] ([[User talk:Zooka|talk]]) 10:04, 19 January 2024 (UTC)<br />
: Sounds like a plan. Build it up in your [[User:Zooka/Main_Page|sandbox]], then we can tweak it and get some side by side opinions from Discord before going live. --[[User:Dt192|Dt192]] ([[User talk:Dt192|talk]]) 11:52, 19 January 2024 (UTC)<br />
: I would not sort packages under accessibility. Also we have a range of different user types to consider. While players mostly don't care about standards. We also have game admins, package developers, etc. Maybe it makes sense to create different main pages for different topics? 🤔 --[[User:Kebap|Kebap]] ([[User talk:Kebap|talk]]) 18:40, 23 January 2024 (UTC)</div>Kebaphttps://wiki.mudlet.org/index.php?title=Talk:Main_Page&diff=20875Talk:Main Page2024-01-23T18:40:23Z<p>Kebap: /* Redesign */ Add header to the topic</p>
<hr />
<div>== Redesign ==<br />
<br />
So I'm thinking a redesign of this page with 6 or so sections with some minor subsections (and maybe some nice images to add some appeal).<br />
Maybe with the launch of dt192's theme ideas?<br />
<br />
* About Mudlet<br />
** Contact methods, forums, discord, etc<br />
<br />
* Downloads<br />
** Main download area<br />
** Dev and Compiling<br />
** PTB<br />
<br />
* Tutorials<br />
** current wiki walkthroughs<br />
** learn lua<br />
** regex<br />
<br />
* Manual<br />
** main manual<br />
** technical API<br />
<br />
* Accessibility<br />
** packages<br />
** screen readers<br />
<br />
and removal of <br />
<br />
* Standards - I don't think the casual user is interested in the tech details,<br />
* Special links - already available on sidebar<br />
* Mediawiki links - already available on sidebar<br />
<br />
<br />
--[[User:Zooka|Zooka]] ([[User talk:Zooka|talk]]) 10:04, 19 January 2024 (UTC)<br />
: Sounds like a plan. Build it up in your [[User:Zooka/Main_Page|sandbox]], then we can tweak it and get some side by side opinions from Discord before going live. --[[User:Dt192|Dt192]] ([[User talk:Dt192|talk]]) 11:52, 19 January 2024 (UTC)</div>Kebaphttps://wiki.mudlet.org/index.php?title=Talk:Main_Page&diff=20874Talk:Main Page2024-01-23T18:39:57Z<p>Kebap: /* Redesign */ new section</p>
<hr />
<div>So I'm thinking a redesign of this page with 6 or so sections with some minor subsections (and maybe some nice images to add some appeal).<br />
Maybe with the launch of dt192's theme ideas?<br />
<br />
* About Mudlet<br />
** Contact methods, forums, discord, etc<br />
<br />
* Downloads<br />
** Main download area<br />
** Dev and Compiling<br />
** PTB<br />
<br />
* Tutorials<br />
** current wiki walkthroughs<br />
** learn lua<br />
** regex<br />
<br />
* Manual<br />
** main manual<br />
** technical API<br />
<br />
* Accessibility<br />
** packages<br />
** screen readers<br />
<br />
and removal of <br />
<br />
* Standards - I don't think the casual user is interested in the tech details,<br />
* Special links - already available on sidebar<br />
* Mediawiki links - already available on sidebar<br />
<br />
<br />
--[[User:Zooka|Zooka]] ([[User talk:Zooka|talk]]) 10:04, 19 January 2024 (UTC)<br />
: Sounds like a plan. Build it up in your [[User:Zooka/Main_Page|sandbox]], then we can tweak it and get some side by side opinions from Discord before going live. --[[User:Dt192|Dt192]] ([[User talk:Dt192|talk]]) 11:52, 19 January 2024 (UTC)<br />
<br />
== Redesign ==<br />
<br />
x</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Mapper&diff=20873Manual:Mapper2024-01-23T18:35:44Z<p>Kebap: /* Making your own mapping script */ Split and add sections: The generic mapper vs. Starting from scratch</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Manual on creating maps, areas, rooms, and advanced features like autowalking, creating lables, custom exit lines, etc.}}<br />
<br />
= Mapper =<br />
Mudlet's mapper is split into two parts for the best compatibility on all games: <br />
# The display of the map itself and functions to modify the map in Mudlet, and <br />
# A very game-specific Lua script to track where you are, and provide aliases for using the mapper, automatic mapping, etc.<br />
<br />
If your game does not provide a mapping script for you, then you may not see a map at first. <br />
<br />
Fear not! Pre-made mapping scripts for many games are available from [https://forums.mudlet.org/search.php?keywords=mapping+script&terms=all&author=&sc=1&sf=titleonly&sr=topics&sk=t&sd=d&st=0&ch=400&t=0&submit=Search Mudlet forums] - all topics that have the "mapping script"-prefix on them. <br />
<br />
If you still don't find any, or if you want to create your own mapping script, see [[#Making your own mapping script]] further down below. Remember, you can always find help in Mudlet forums or Discord, etc. <br />
<br />
==Visual Map Editor==<br />
Maps can be comfortably edited by using the visual map editor or by scripts. The editor behaves like the usual WYSIWYG editors. Select objects with a left click and then right click to open a context menus and do actions on the selected objects.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
The mapper starts in "view-only" mode to prevent accidental edits. The editing mode can be toggled in the map's right-click menu.<br />
<br />
===Object selection===<br />
<br />
* left click = select element<br />
* left click + drag = sizing group selection box choosing all rooms in the box on the current z-level<br />
* left click + shift + drag = sizing group selection box choosing all rooms in the box on all z-levels<br />
* left click + alt (or the mapper menu move map buttons) = move map<br />
* left click + control = add a room to current group selection or remove it<br />
<br />
If multiple rooms are being selected, a room id selection list box is being shown where you can fine tune the current room selection via the usual ''left click + control'' or ''left click + shift''. The box disappears if the number of rooms in group selection is zero.<br />
<br />
===Moving Objects===<br />
Move selected objects either by right click and select "move" or with following handy short cut:<br />
<br />
* left button down on custom line point + drag = move custom line point<br />
* left button down + drag usually moves the item directly (as a handy shortcut) if only one element has been selected<br />
* '''or''' hold left button down + control + drag if multiple rooms have been selected<br />
<br />
== Maps and Autowalking ==<br />
Maps are implemented as directed graphs of connected nodes (rooms). Nodes are connected by edges (exits). Nodes are referenced by unique integer IDs. Edges fall into 2 categories: Standard exits with a visual representation on the map (e. g. north, south) and "special exits" without a calculated visual representation on the map e. g. the command "jump cliff" is a special exit that connects to a room without a clear spatial orientation. However, special exits can be visually represented if the user provides custom exit line strips. Standard exits are referenced by their respective node and a directional integer value. Special exits are referenced by their respective nodes and strings that hold the exit commands. Both nodes and individual exits can seperately be locked and thus excluded from speed walk path finding graphs. Path finding uses the fast A* search algorithm. Mudlet choses a path with the fastest travel time (-> room weights) as opposed to the shortest path.<br />
<br />
Maps are divided into areas or zones where the area/room relationship is unique, i. e. rooms cannot be in more than 1 area. <br />
<br />
{{note}}Areas help make do with the typical geographical irregularities of game maps where an entire city with hundrets of rooms makes up a single room on a wilderness map. In other words, if you can't make a place look geographically correctly, create (sub) areas to deal with the problem.<br />
<br />
There are 2 forms of visual representations of maps. Standard mode shows exits and custom exit lines whereas "grid mode" hides exit details and sizes rooms to form a perfect grid without any empty space in between rooms. Grid maps can be made to look exactly like ASCII color text maps with character symbols to keep the look and feel of the game. Technically, grid maps are a special optimized representation of the typically very large LPC MUD style wilderness maps where every room has 8 direct neighbors in a n*m grid of rooms with relatively few holes. The grid map implementation uses pre image caching and fast gfx hardware render support and can thus render very large grid maps in less than 1ms that would take much longer if the map were to be displayed in regular mode. Changing the zoom level of maps in grid mode can take a significant amount of time if the maps are very large, because the pre cached images of the map need to be recreated at the new zoom level. Areas remember their particular zoom level so this is no hindering issue in actual gameplay.<br />
<br />
Any map can be displayed in both modes, though the visual map editor only works in regular mode. To enable area mode, use the [[Manual:Lua Functions#setGridMode|setGridMode()]] function.<br />
<br />
Regular mode:<br />
<br />
[[File:Mapper-regular-mode.png|frameless|716x716px]]<br />
<br />
Grid mode:<br />
<br />
[[File:Mapper-grid-mode.png|frameless|713x713px]]<br />
=== Areas ===<br />
Areas are defined by a unique integer number ID and a unique area name. Mudlet builds an internal numerical area ID table on the basis of the rooms that belong to the respective areas. Mudlet keeps a seperate lookup table to retrieve the area name on the basis of the area IDs. This name lookup table is not guaranteed to be correct because it may be imported invalid information if the map has been downloaded by the game server as an xml map description file on the basis of the MMP protocol. <ref>MMP allows for an area ID/area names table to be defined, but Mudlet has no means to verify which definition is the correct one if 2 different area names relate to the same area ID.</ref> However, if the map has been created with Mudlet directly, there will be no such problems as the area name lookup table API is made to enforce uniqueness.<br />
<br />
==== Area Properties ====<br />
* area map display mode (-> regular map display mode or grid mode)<br />
* area name<br />
<br />
=== Rooms ===<br />
Rooms are invisible on the map unless the required properties have been set.<br />
==== Room Properties ====<br />
*Room object need following required properties in order to be shown on the respective area map:<br />
** unique room ID in form of an integer value <br />
** area ID in form of an integer value (To which area does this room belong - or in other words, which area map displays this room)<br />
** x, y and z coordinates as integer values which relate to its paricular area map coordinate system<br />
<br />
*Optional room properties:<br />
** regular exits with or without respective exit locks<br />
** special exits with or without respecitve special exit locks<br />
** room lock<br />
** exit stubs (draw exit directions even though the exit rooms have not yet been defined)<br />
** custom exit lines (user defined line strips of various formats to visualize special exits or redefine regular exit lines)<br />
** searchable room name that can be used for bookmarks, annotations etc. <br />
** room weight (How long does it travel through this node. A high room weight makes it less likely that this room will be chosen for pathfinding e. g. a safe road should have a low weight, whereas a dangerous place should have a high weight<br />
** room color<br />
** room character e. g. the symbol $ to symbolize a bank or H for a hotel.<br />
<br />
== Advanced map features ==<br />
=== Map labels ===<br />
Maps can be embellished with images and text labels. Map labels can be either used as background (default) or as the top most foreground e. g. for player name location scripts. Labels are defined by position and size according to the map coordinate system and keep their position and size relative to the rest of the map when the map is zoomed or moved.<br />
Contrary to rooms which work on the basis of integer (natural numbers) coordinates, labels are described (with respect to both position & size) by real numbers in order to allow for more advanced placement and label sizes within the map coordinate system. Map labels are stored in form of png images directly in the map file and are thus a direct part of the map. As these images are being scaled to fit the label creation size, the image quality will depend on the initial size of the label (the large the better the quality, but the more memory will be used).<br />
<br />
[[File:MapTextLabelDemo.PNG|250px|frameless|misc label types]]<br />
[[File:MalLabelsScaled.PNG|250px|frameless|zoomed]]<br />
[[File:MapBackgroundImageLabel.PNG|250px|frameless|label as background image]]<br />
<br />
(The desert and dragon images used in this example are licensed under the Creative Commons Attribution 2.0 Generic license and can be found here: http://en.wikipedia.org/wiki/File:Ninedragonwallpic1.jpg and http://en.wikipedia.org/wiki/File:Siwa_sand_dunes2009a.jpg)<br />
<br />
=== Custom exit line definitions ===<br />
The mapper supports user defined visual exit lines on the basis of a sequence of line points in the map coordinate system. Custom lines as well as labels work on real numbers to allow for fine grained placement. User defined lines can be solid, dotted, dashed etc. line types with or without ending arrows. The line color can be freely selected. By default the regular exit color is being used.<br />
<br />
[[File:CustomExitSelection.PNG|400px|frameless|custom exit line demo]] [[File:DifficultGeography.PNG|500px|frameless|custom exit line demo]]<br />
<br />
The above example shows 3 different types of user defined exit lines, where the orange one on the left has been selected by the user in order to be edited.<br />
<br />
Custom exit lines are purely visual tools and have no effect on the pathfinding, but each custom line must be linked to a valid room exit - either standard or special exit.<br />
<br />
=== Map formats ===<br />
Whenever a mapping feature is added to Mudlet that requires storing something in the map, the map format version needs to be increased - so older Mudlets can know that a map is too new and they can't load it. To this end, every map has a version number embedded inside it, which you can see by going to mapper settings:<br />
<br />
[[File:Map formats setting.png]]<br />
<br />
You'll also notice that you have the ability to downgrade a map's version for compatibility with older Mudlets. Be careful when you do so though - features available in the new map won't be available in the older map when you downgrade. Here's a table of all the versions and features:<br />
<br />
{| class="wikitable"<br />
! style="font-weight: bold;" | version<br />
! style="font-weight: bold;" | Mudlet version<br />
! style="font-weight: bold;" | features<br />
|-<br />
| 20<br />
| 3.16.0<br />
| - Improved way that custom exit line data was held internally, to make coding Mudlet mapper's easier and safer ([https://github.com/Mudlet/Mudlet/pull/2999 details]). Code is in place to support a workaround to work within map formats back to include version 17.<br />
|- <br />
| 19<br />
| 3.8.0<br />
| - added support for more than one of any grapheme (symbol) for the 2D map room symbol. Code is in place to support a workaround to work within map formats back to including version 17.<br />
|-<br />
| 18<br />
| 3.0.0<br />
| - keeps player's position when copying to a new profile<br />
- faster map loading<br />
|-<br />
| 17<br />
| 3.0.0<br />
| - allows use of setAreaUserData(), setMapUserData(), and related functions<br />
|-<br />
| 16<br />
| 2.1<br />
| - doors (visual effect on the mapper that a locked/closed/open door is there)<br />
- exit weights (in addition to existing room weights)<br />
|}<br />
<br />
== Mapper tips ==<br />
<br />
=== General ===<br />
<br />
* Don't move the room you're currently in, you'll go haywire<br />
* The number when spreading/shrinking room selections it the ''multiplication'' factor - 2 is a good number to try<br />
<br />
=== Merging areas ===<br />
<br />
To merge two areas together, see [https://forums.mudlet.org/viewtopic.php?f=8&t=2273&view=unread#unread this how-to by Heiko]. In short:<br />
<br />
# Zoom out ''really'' far away on the area you'd like to move, and select everything (the selection affects all z-levels as well). <br />
# Right-click, select ''move to area'', and move them to another area. Your selection will still be selected - do '''not''' unselect <br />
# Right-click again, select ''move to position'', and move all of your still selected rooms in the new area so it fits.<br />
<br />
=== Zooming the mapper ===<br />
<br />
You can zoom in/out in the mapper using your (vertical) mousewheel. If you'd like to zoom quicker, hold down <code>Ctrl</code> while doing so!<br />
<br />
To set the zoom level via script, use [[Manual:Mapper_Functions#setMapZoom|setMapZoom()]].<br />
<br />
<br />
=== Add a right-click menu to your mapper ===<br />
<br />
It is easy to add your own options to the menu you see when you right-click on your map. To do so, use [[Manual:Mapper_Functions#addMapMenu|addMapMenu]], [[Manual:Mapper_Functions#addMapEvent|addMapEvent]], etc.<br />
<br />
==== Mapper favorites ====<br />
<br />
[http://forums.mudlet.org/viewtopic.php?f=6&t=2739 This post here] describes how to add a right click menu to your mapper filled with rooms to speedwalk to.<br />
<br />
=== Placing the mapper ===<br />
<br />
==== Placing the mapper into a corner ====<br />
<br />
Here's a snippet you can use to place the mapper window into a corner and have it automatically come up whenever you open Mudlet. To use this, create a new script (you can make it anywhere) and copy/paste the code into it.<br />
<br />
<syntaxhighlight lang="lua" highlight="5" line><br />
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})<br />
<br />
local mapper = Geyser.Mapper:new({<br />
name = "mapper",<br />
x = "70%", y = 0, -- edit here if you want to move it<br />
width = "30%", height = "50%"<br />
}, main)<br />
</syntaxhighlight><br />
==== Placing the mapper into its own window ====<br />
<br />
{{MudletVersion|4.7+}}<br />
<br />
It's possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded=false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation, use:<br />
<syntaxhighlight lang="lua"> -- this will create a map window docked at the left corner<br />
myMapWidget = Geyser.Mapper:new({embedded=false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are: left "l", right "r", top "t", bottom "b" and floating "f"<br />
<br />
To change the dockPosition after creation, use:<br />
<syntaxhighlight lang="lua"> -- this will change myMapWidget dockPosition to "f" floating <br />
myMapWidget:setDockPosition("f")<br />
</syntaxhighlight><br />
<br />
== Making your own mapping script ==<br />
<br />
Your own mapping script will need to be tailored specifically to your game, depending on how exactly your rooms are shown, how the exits are listed, or if the game maybe sends some of this relevant information via GMCP, etc. <br />
<br />
=== The generic mapper ===<br />
To ease your work, all new profiles in Mudlet come with a "generic mapper" package, which tries to draw a map by guessing most of the information from your game. It knows the most common ways to write an exit, etc. You can find more details by typing "map basics" in Mudlet.<br />
<br />
Even if the generic mapper does not 100% grasp your very game details, you could maybe just adjust a few triggers and be done with it. Remember to stop by and ask for help in forums or chat, if you get stuck anywhere.<br />
<br />
Some players have collected a list of [[Generic_Mapper_Additions]] on how to modify the generic mapper to better fit their game already.<br />
<br />
=== Starting from scratch ===<br />
If you'd like to code your own mapping script, see the [[Manual:Lua_Functions#Mapper_Functions|Mapper API]] and read on for a short tutorial.<br />
<br />
To start off, create a new script that'll be included with your mapping script (can even place it into the script folder for your mapping script), and have it do:<br />
<br />
<syntaxhighlight lang="lua"><br />
mudlet = mudlet or {}; mudlet.mapper_script = true<br />
</syntaxhighlight><br />
<br />
This'll let Mudlet know that a mapping script is installed, so it won't bother you or whoever else installs your script with a warning that one is necessary.<br />
<br />
Next, you want to hook into Mudlet's gotoRoom(id) function and the user clicking on a room in the visual map - for that, define your own ''doSpeedWalk()'' function. Mudlet will store the directions / special exits commands your script will need to take in the ''speedWalkDir'' table, and the room IDs you'll pass through in the ''speedWalkPath'' table:<br />
<br />
<syntaxhighlight lang="lua"><br />
function doSpeedWalk()<br />
echo("Path we need to take: " .. table.concat(speedWalkDir, ", ") .. "\n")<br />
echo("Rooms we'll pass through: " .. table.concat(speedWalkPath, ", ") .. "\n")<br />
end<br />
</syntaxhighlight><br />
<br />
''speedWalkPath'' is especially useful for making sure you're still on the path. Most Mudlet mapping scripts keep track of how many rooms along the path they have visited so far and check upon arrival into a new room to make sure it's still on the path.<br />
<br />
That's it! (But see below if you want more.)<br />
<br />
From here, you'd want to build a walking script that'll send the commands to walk you along the path, along with aliases for the user to use - see the [[Manual:Lua_Functions#Mapper_Functions|Mapper API functions]] and [[Manual:Event_Engine#Mudlet-raised_events|Mudlet mapper events]].<br />
<br />
=== Adding rooms ===<br />
To make your first room, do the following steps:<br />
<br />
* create an area with setAreaName(areaID, areaname). You can choose any areaID - if you'd like to use the IDs incrementally, see which is the latest from getAreaTable()<br />
* if you want the Mudlet mapper to generate roomIDs for you, get one with createRoomID(). This is an optional step<br />
* create your room with addRoom(roomID)<br />
* give the room coordinates with setRoomCoordinates(roomID, x, y, z). If you're just starting out, put it at 0,0,0 so the room is at the center of the map<br />
* assign your room to an area with setRoomArea(roomID, areaID)<br />
* and finally, call centerview(roomID) to make the map view refresh and show your new room!<br />
<br />
==== Labelling rooms ====<br />
<br />
Rooms have three attributes which you can show on the map:<br />
* an ID. You can't change it; the ID is shown in the room's box when you check "IDs" in the dialog below the map and you're zoomed in far enough.<br />
* a symbol, also displayed in the room's box. You set it with the [https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomChar ''setRoomChar''] Lua function, or via the map's context menu.<br />
* a name, typically sent via GMCP. You add it to the map with [https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomName ''setRoomName''].<br />
<br />
The room name can be displayed along with a room's box. Its position defaults to "centered below the room". It is not visible by default because many maps have rooms that are quite close to each other; showing the names by default would create an ugly visual mess.<br />
<br />
If you want to enable room names in your mapper, you need to<br />
* stagger rooms. Four or five units' distance instead of one works best if you want to show every label; less is OK if you only show labels when the user asks you to.<br />
* call ''setMapUserData("room.ui_showName","1")''. The existence of this entry controls whether the "Names" checkbox is shown next to "IDs", below the map. This value is zero if the user has unchecked the "Names" checkbox.<br />
* optionally call ''setMapUserData("room.ui_nameFont","FontName")'' to change the names' font. The default is the same monospaced font used for the room IDs and symbols.<br />
* call ''setRoomUserData(room_id, "room.ui_showName","1")'' to show a room's label. You might want to add an entry to the map's pop-up menu which toggles this.<br />
<br />
If the name is misplaced (collision with another room, label, or whatever), you can modify the room's "room.ui_nameOffset" attribute to move it around. The value of this attribute consists of two floating-point values, separated by a space, which offset the room's label (in units of the room box's size). You might want to bind functions that increase or decrease these values to keys like Shift-Control-Arrow and/or Control-Numpad-2468. A hotkey to toggle a room's label display from "on" to "off" and back (e.g. Control-Numpad-5?) is also a good idea.<br />
<br />
You also might default to staggering room names. One possible algorithm: '''if''' a new room's X coordinate, divided by your default room distance, is an odd number '''then''' position its label with an offset like "0 -1.6", which would place it above the room in question. The optimal value for the Y offset depends on the font.<br />
<br />
Changes are displayed only when the map is next redrawn.<br />
<br />
Font options are global. Overriding them for a single room can be be implemented if requested.<br />
<br />
=== Working with the mapper API ===<br />
Whenever working with mapper API, keep in mind of the following things:<br />
<br />
* You'll want to call centerview after you do some modifications, to get to have the map render your new changes<br />
<br />
=== Translating directions ===<br />
Several functions in the mapper API take and return #'s for directions - and to make it easier to work with them, you can define a table that maps directions to those numbers in a script with the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
exitmap = {<br />
n = 1,<br />
north = 1,<br />
ne = 2,<br />
northeast = 2,<br />
nw = 3,<br />
northwest = 3,<br />
e = 4,<br />
east = 4,<br />
w = 5,<br />
west = 5,<br />
s = 6,<br />
south = 6,<br />
se = 7,<br />
southeast = 7,<br />
sw = 8,<br />
southwest = 8,<br />
u = 9,<br />
up = 9,<br />
d = 10,<br />
down = 10,<br />
["in"] = 11,<br />
out = 12,<br />
[1] = "north",<br />
[2] = "northeast",<br />
[3] = "northwest",<br />
[4] = "east",<br />
[5] = "west",<br />
[6] = "south",<br />
[7] = "southeast",<br />
[8] = "southwest",<br />
[9] = "up",<br />
[10] = "down",<br />
[11] = "in",<br />
[12] = "out",<br />
}<br />
</syntaxhighlight><br />
<br />
Then, using exitmap[input], you'll get a direction number or a direction name. Here's an example that uses it to work out in which directions are the exit stubs available in room 6:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local stubs = getExitStubs(6)<br />
for i = 0, #stubs do print(exitmap[stubs[i]]) end<br />
</syntaxhighlight><br />
<br />
=== Custom speedwalking and pathfinding ===<br />
<br />
{{MudletVersion|4.10}}<br />
If you'd like to use a custom pathfinding algorithm instead of the built-in one, you can do that:<br />
<br />
* Set ''mudlet.custom_speedwalk = true''.<br />
* Your ''doSpeedwalk'' script will now see different parameters:<br />
<br />
<syntaxhighlight lang="lua"><br />
function doSpeedWalk()<br />
echo("Room we're coming from: " .. speedWalkFrom .. "\n")<br />
echo("Room you're going to: " .. speedWalkTo .. "\n")<br />
end<br />
</syntaxhighlight><br />
<br />
The forum topic [https://forums.mudlet.org/viewtopic.php?f=6&t=22930&p=45930#p45930 Wayfinder] contains an example package that implements a shortest-path-first algorithm.<br />
<br />
=== Custom room name search function in the generic_mapper ===<br />
<br />
{{MudletVersion|4.11}}<br />
Sometimes the generic_mapper script is not flexible enough to find the room name in your favorite game. You can create a custom function that handle that search instead of the standard one included in the mapper:<br />
<br />
* Type in the input area ''map config custom_name_search true'' to enable the usage of the custom function.<br />
* Write your own function called ''mudlet.custom_name_search''. The script call it for your:<br />
<br />
<syntaxhighlight lang="lua"><br />
mudlet.custom_name_search = function (lines)<br />
-- ...<br />
local line_count = #lines + 1<br />
if string.match(cur_line, " ") then<br />
line_count = line_count - 1<br />
room_name = lines[line_count]<br />
-- map.echo("Name Search: room_nameome:" ..room_name) <br />
elseif string.find(cur_line,prompt_pattern) then<br />
-- ...<br />
return room_name<br />
end<br />
</syntaxhighlight><br />
<br />
I suggest to start from original name_search function in generic_mapper to avoid common problem.<br />
<br />
=== onVisionFail for generic_mapper - moving through dark rooms ===<br />
generic_mapper uses a combination of room titles, descriptions and exits to locate your character position in the mapper. Sometimes this information may not be available due to blindness, dark rooms or other affects that may prevent full vision and correct room matching. Using the <code>onVisionFail</code> event and appropriate triggers you can force your character to move to the next room and update the map accordingly even when vision is limited.<br />
<br />
generic_mapper comes with two predefined triggers, add or replace these as necessary with the appropriate lines your game sends.<br />
[[File:English Vision Fail Triggers.png|alt=Predefined triggers in generic_mapper calling onVisionFail event.|none|thumb|843x843px|Predefined triggers in generic_mapper calling onVisionFail event.]]<br />
In these examples when the game sends <code>It is pitch black...</code> or <code>It's too dark</code> or <code>It is too dark</code> starting on a newline (<code>^</code> character) then it will raise the <code>onVisionFail</code> event. When called this event will skip looking to match the room, and simply move the character in the direction they sent prior.<br />
<br />
== Screenshots ==<br />
Just a few example maps from different players and games:<br />
<gallery><br />
File:Mapper 562.png<br />
File:Mudlet 563.png<br />
File:TK6fS.png<br />
File:Stary kontynent-min-scaled.png|Here is the [https://i.imgur.com/IaV6lDc.png full image] (17160 x 10120 pixel)<br />
File:MG Port Vain.png<br />
</gallery><br />
<br />
== Notes ==<br />
<references /><br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Migrating&diff=20795Manual:Migrating2024-01-18T16:48:06Z<p>Kebap: /* From ZMUD */ Link to CMUD</p>
<hr />
<div>{{TOC right}}<br />
=From Nexus=<br />
<br />
{{note}} The Nexus information seems a bit out of date. Please feel free to add or update with more current instructions.<br />
<br />
'''Trigger patterns'''<br />
<br />
Lets start with triggers. For translating Nexus patterns into Mudlet, use the following table below. Make sure to set the pattern type in Mudlet to be perl regex, because the default substring works differently.<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th> <br />
<th>What it does</th> <br />
<tr><br />
<td>(\w+)</td><br />
<td>{w}</td><br />
<td>Match one or more non-whitespace characters (a 'word')</td><br />
</tr><br />
<tr><br />
<td>(\d+)</td><br />
<td>{d}</td><br />
<td>Match one or more numeric digits (a number)</td><br />
</tr><br />
<tr><br />
<td>([abc])</td><br />
<td>{[abc]}</td><br />
<td>Match one or more of either 'a', 'b' or 'c'. (a character class)</td><br />
</tr><br />
<tr><br />
<td>([^abc])</td><br />
<td>{[^abc]}</td><br />
<td>Match one or more of anything EXCEPT 'a', 'b', or 'c'</td><br />
</tr><br />
<tr><br />
<td>(.*)</td><br />
<td>{*}</td><br />
<td>Match zero or more characters (anything)</td><br />
</tr><br />
<tr><br />
<td>^</td><br />
<td>{<} </td><br />
<td>Match the beginning of a line (not the actual newline character)</td><br />
</tr><br />
<tr><br />
<td>$</td><br />
<td>{>}</td><br />
<td>Match the end of a line (not the actual newline character)</td><br />
</table> <br />
<table frame="box"><br />
<caption>'''Note:'''</caption><br />
<td>If you just have a pattern with a {<} and {>} and nothing else, copy the pattern over without the {<}{>} and select the exact match pattern type. For example {<}You sit down.{>} in Nexus would become '''You sit down.''' in Mudlet with the pattern type of exact match. This is easier to read and matches way faster!</td><br />
</table><br />
<br />
<br />
'''Basic scripting'''<br />
<br />
The Nexus way of doing a function is like this: #function stuff it does. In Mudlet, it’s function(stuff it does). Note that if you’d like to give text to a function, you put it inside double or single quotes.<br />
<br />
'''Calling functions'''<br />
<table border="1" width="100%"><br />
<caption>Calling functions</caption><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
send("hi")<br />
echo("Hello to me!")<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
#send hi<br />
#echo Hello to me!<br />
</code><br />
</td><br />
</tr><br />
</table><br />
<table frame="box"><br />
<caption>'''Note:'''</caption><br />
<td><br />
If you’d like to use a variable inside text, you’d put it outside the quotes and glue it together with two dots.<br />
</td><br />
</table><br />
<br />
'''Setting variables'''<br />
<table border="1" width="100%"><br />
<caption>Setting variables</caption><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
number = 1234<br />
echo("My number is: " .. number.. "\n")<br />
echo("the " .. number .. " is in the middle of my text\n")<br />
echo(string.format("And here's another - %s - way to format things\n", number))<br />
</syntaxhighlight><br />
<td><br />
<code><br />
#set number 1234<br />
#echo My number is: $number<br />
#echo the $number is in the middle of my text<br />
</code><br />
</td><br />
</tr><br />
<table><br />
<br />
'''Wildcards'''<br />
<br />
To use the wildcard variable in Nexus, you’d use $1 for the first match, $2 for the second and so on. In Mudlet, the matches[] table contains the matches - and it starts placing the matches from 2. So the Nexus $1 would be matches[2], $2 would be matches[3].<br />
<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
(\w+) kicks you\.<br />
badguy = matches[2]<br />
echo(badguy .. " kicked me!")<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
{w} kicks you.<br />
#set badguy $1<br />
#echo $badguy kicked me!<br />
</code><br />
</td><br />
</tr><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
alias pattern: ^t (.*)$<br />
alias script: target = matches[2]<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
alias name: t<br />
alias script: #set target $1<br />
</code><br />
</td><br />
</tr><br />
<table><br />
<table frame="box"><br />
<caption>'''Note:'''</caption><br />
<td><br />
The reason the first match goes into matches[2] and not matches[1] is because matches[1] contains the part of the line that matched your trigger / alias.<br />
</td><br />
<table><br />
<br />
'''#wait'''<br />
<br />
In Nexus, a #wait will freeze the script while it’s executing - such that commands after it are delayed. In Mudlet, we use tempTimer which that works a bit differently - it doesn’t freeze the script, but instead makes it so commands a tempTimer is asked to do will get done in the future.<br />
<br />
So the difference is that a tempTimer doesn’t freeze the commands following it at all, everything gets done at once as usual. Just things a tempTimer was asked to do get done in the future.<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
send("hello")<br />
tempTimer(1, [[send("hi")]])<br />
tempTimer(1.5, [[send("bye")]])<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
#send hello<br />
#wait 1000<br />
#send hi<br />
#wait 500<br />
#send bye<br />
</code><br />
</td><br />
</tr><br />
</table><br />
<br />
'''ifs in Mudlet'''<br />
<br />
Next are the #if statements. Here’s a table comparing the syntaxes of Nexus and Mudlet:<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
if <condition> then <text> end<br />
</td><br />
<td><br />
<nowiki>#if <condition> <text></nowiki><br />
<nowiki>#if <condition> { <script> }</nowiki><br />
</td><br />
</tr><br />
<tr><br />
<td><br />
if <condition> then <script> else <script> end<br />
</td><br />
<td><br />
<nowiki>#if <condition> { <script> } else { <script> }</nowiki><br />
<nowiki>#if <condition> { <script> } { <script> }</nowiki><br />
</td><br />
</tr><br />
<tr><br />
<td><br />
if <condition> then <script> elseif <condition> then <script> end<br />
</td><br />
<td><br />
<nowiki>#if <condition> { <script> } elsif <condition> { <script> }</nowiki><br />
</td><br />
</tr><br />
<tr><br />
<td><br />
if <condition> then <script> elseif <condition> then <script> else <script> end<br />
</td><br />
<td><br />
<nowiki>#if <condition> { <script> } elsif <condition> { <script> } else { <script> }</nowiki><br />
</td><br />
<tr><br />
</table><br />
<br />
<br />
Here is the sample side-by-side comparison of how you’d use it:<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
-- If foo is true, echo that fact.<br />
if foo then echo ("Foo is true!") end -- If foo is true, echo that fact.<br />
<br />
-- A slight modification of the above that illustrates an 'else' clause.<br />
-- Note that the 'then' is always necessary to avoid confusion.<br />
if foo then echo ("Foo is true!") else echo ("Foo is false!") end<br />
<br />
-- Illustration of putting more than one statement in a block (also<br />
-- spans lines here). Note the if doesn't end until the last 'end' is<br />
-- encountered.<br />
-- We also add a \n at the end of multiple echos so each one is on it's own line.<br />
if foo then<br />
echo ("Foo is true!\n")<br />
echo ("Isn't it grand?\n")<br />
echo ("These commands are all on separate lines too!\n")<br />
end<br />
<br />
-- This shows how ifs continue (on 'logical' lines) even though the<br />
-- blocks in its constituent clauses may have multiple lines. The<br />
-- following lines are all _one_ single if statement.<br />
if foo > 50 then<br />
echo ("Foo is big!\nYes it is.")<br />
elseif foo > 10 then<br />
echo ("Foo is pretty big...\n")<br />
echo ("I've seen bigger.")<br />
else<br />
echo ("Foo is actually kind of small.")<br />
end<br />
<br />
-- Ifs can be nested too.<br />
if foo then<br />
if bar then<br />
echo ("Both foo and bar are true.")<br />
else<br />
echo ("Foo's true, but bar isn't.")<br />
end<br />
end<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
<br>// If $foo is true, echo that fact.<br />
#if $foo #echo Foo is true! // If $foo is true, echo that fact.<br />
<br />
<br>// A slight modification of the above that illustrates an 'else' clause.<br />
<br>// The second form shows that the word 'else' is actually optional too.<br />
<br>// (The two lines are functionally the same.)<br />
#if $foo { #echo Foo is true! } else { #echo Foo is false! }<br />
#if $foo { #echo Foo is true! } { #echo Foo is false! }<br />
<br />
<br>// Illustration of putting more than one statement in a block (also<br />
<br>// spans lines here). Note the if doesn't end until the last '}' is<br />
<br>// encountered.<br />
#if $foo {<br />
#echo Foo is true!<br />
#echo Isn't it grand?<br />
#echo These commands are all on separate lines too!<br />
}<br />
<br />
<br>// This shows how ifs continue (on 'logical' lines) even though the<br />
<br>// blocks in its constituent clauses may have multiple lines. The<br />
<br>// following lines are all _one_ single if statement.<br />
#if $foo > 50 {<br />
#echo Foo is big!<br />
#echo Yes it is.<br />
} elsif $foo > 10 {<br />
#echo Foo is pretty big...<br />
#echo I've seen bigger.<br />
} else {<br />
#echo Foo is actually kind of small.<br />
}<br />
<br />
// Ifs can be nested too.<br />
#if $foo {<br />
#if $bar {<br />
#echo Both foo and bar are true.<br />
} else {<br />
#echo Foo's true, but bar isn't.<br />
}<br />
}<br />
</code><br />
</td><br />
</tr><br />
</table><br />
<br />
'''Mudlet equivalents of Nexus functions'''<br />
<br />
Now that we got the ifs covered, lets go over the Mudlet equivalents of other Nexus functions. Note that this is a direct Nexus→Mudlet comparison; certain functions in Mudlet have much more capability.<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><variable name> = "<text value>"</td><br />
<td><nowiki>#set <variable name> <text value></nowiki></td><br />
</tr><br />
<tr><br />
<td><variable name> = <expression></td><br />
<td><nowiki>#set <variable name> = <expression></nowiki></td><br />
</tr><br />
<tr><br />
<td><variable name> = nil</td><br />
<td><nowiki>#unset <variable name></nowiki></td><br />
</tr><br />
<tr><br />
<td><variable> = <variablename> <+ - / *> <number or variable></td><br />
<td><nowiki>#add <variablename> <expression></nowiki></td><br />
</tr><br />
<tr><br />
<td>echo "text\n" or echo("text\n")</td><br />
<td><nowiki>#echo <text></nowiki></td><br />
</tr><br />
<tr><br />
<td>echo "text" or echo("text")</td><br />
<td><nowiki>#echo_ <text></nowiki></td><br />
</tr><br />
<tr><br />
<td>enableAlias("<group name>")/enableTrigger()/enableKey()/enableTimer()</td><br />
<td><nowiki>#groupon <group name></nowiki></td><br />
</tr><br />
<tr><br />
<td>disableAlias("<group name>")disableTrigger()disableKey()disableTimer()</td><br />
<td><nowiki>#groupoff <group name></nowiki></td><br />
</tr><br />
<tr><br />
<td>selectString (line, 1) bg("<color>") resetFormat()</td><br />
<td><nowiki> #highlight <color></nowiki></td><br />
</tr><br />
<tr><br />
<td>deleteLine()</td><br />
<td><nowiki>#gag</nowiki></td><br />
</tr><br />
<tr><br />
<td>openUrl("<url>")</td><br />
<td><nowiki>#openurl <url></nowiki></td><br />
</tr><br />
<tr><br />
<td>send("<stuff>")</td><br />
<td><nowiki>#send <text></nowiki></td><br />
</tr><br />
<tr><br />
<td>sendAll("hi", "hello", "bye")</td><br />
<td><nowiki>#send_ hi #send_ hello #send bye</nowiki></td><br />
</tr><br />
<tr><br />
<td>tempTimer(<nowiki><time in s></nowiki>, [[ <nowiki><lua code to do once time is up></nowiki> ]])</td><br />
<td><nowiki>#wait <milliseconds></nowiki></td><br />
</tr><br />
</table><br />
<br />
'''How to call aliases in Mudlet'''<br />
<br />
The typical workflow in Nexus is that you’d define the aliases for yourself to use, and also use aliases for system-related things (things like checking if you’d need to eat a herb, etc).<br />
<br />
While the first use is good, the second isn’t - because the user can also run this alias at an inopportune time, because if you want to call an alias it has to match all alises again, and so on.<br />
<br />
Now, while in Mudlet you can call another alias with the expandAlias() function, this is strongly discouraged. What you do instead if create a function (for example, send() and echo() are functions) that you can then call from your alias or trigger. This has many advantages - it’s faster, you can easily give your function values, and your function can return you values, too.<br />
<br />
To make a function, you go to the Scripts section, create a new script, and write in your function:<br />
<syntaxhighlight lang="lua"><br />
function <name> ()<br />
<stuff it does><br />
end<br />
</syntaxhighlight><br />
For example, if we want to make a function that does two things for us at once, we’d do this:<br />
<syntaxhighlight lang="lua"><br />
function eat_bloodroot()<br />
send ("outr bloodroot")<br />
send ("eat bloodroot")<br />
end<br />
</syntaxhighlight><br />
Then just do this in our alias or trigger to outr and eat bloodroot:<br />
<syntaxhighlight lang="lua"><br />
eat_bloodroot()<br />
</syntaxhighlight><br />
As mentioned, you can also give things to functions - in this case lets expand the function to eat any herb for us we tell it:<br />
<syntaxhighlight lang="lua"><br />
function eat (what)<br />
send ("outr " .. what)<br />
send ("eat " .. what)<br />
end<br />
[...]<br />
eat ("bloodroot")<br />
eat ("kelp")<br />
eat ("ginseng")<br />
</syntaxhighlight><br />
Lastly, functions can also give you data back. One useful example for this is to break down tasks into functions, which will help your code readability:<br />
<syntaxhighlight lang="lua"><br />
function can_i_stand()<br />
if not paralyzed and not prone and not stunned then<br />
return true<br />
else<br />
return false<br />
end<br />
[...]<br />
if can_i_stand() and have_balance and have_equilibrium then<br />
send ("stand")<br />
end<br />
</syntaxhighlight><br />
==Notes to be aware of==<br />
<br />
To finish off, a couple of points that should be remembered:<br />
* Mudlet does profile snapshots (nexus archives) automatically - to load a different one, select it from the list when connecting<br />
* Mudlet can import and export xml<br />
* Mudlet and Nexus xml formats aren’t compatible<br />
* Mudlet can do nexus graphics, here is a package for - [https://forums.mudlet.org/viewtopic.php?f=6&t=981 Achaea], [https://www.lusternia.com/node/28106 Lusternia]<br />
* Mudlet has a ton more features such as more speed, less bugs, copy from the normal window, replay logging, color html logging, more powerful scripting, and the list goes on.<br />
<br />
=From MUSHclient=<br />
<br />
* Mudlet doesn't use %#'s - uses matches[] instead. "%1" or %1 would be matches[2], "%2" or %2 would be matches[3] and so on<br />
* No variables in trigger patterns - but you can check against your variables in scripts, or lua function pattern types<br />
* <code>Send()</code> in MUSHclient is called [[Manual:Lua Functions#send|send()]] with a lower S in Mudlet - in Lua, capitalization matters! To send a command without echoing it on the screen, use:<br />
<syntaxhighlight lang="lua">send("my text", false)</syntaxhighlight><br />
* While MUSHclient uses [https://www.gammon.com.au/scripts/doc.php?function=AnsiNote AnsiNote] to write colorful text, Mudlet offers different ways as well: [[Manual:Lua Functions#cecho|cecho()]] works with the name of a color. You can find lots of predefined colors with [[Manual:Lua Functions#showColors|showColors()]]. You can also style foreground and background seperately with [[Manual:Lua Functions#fg|fg()]] and [[Manual:Lua Functions#bg|bg()]]. To keep your original ANSI colors, use [[Manual:Lua Functions#ansi2decho|ansi2decho()]]. If you need more colors, [[Manual:Lua Functions#decho|decho()]] will take rgb numbers, [[Manual:Lua Functions#hecho|hecho()]] uses hex codes.<br />
* Mudlet does not offer 'GetConnectDuration()' but you could create a script to connect to the [[Manual:Event_Engine#sysConnectionEvent|connection event]] (and maybe sysDisconnectionEvent) and in that function [[Manual:Mudlet_Object_Functions#createStopWatch|start a stopwatch]] to keep count of how long you've been connected for. See [[Manual:Event Engine]] on how to use events in Mudlet.<br />
* Mudlet does not have lpeg built-in but you can include the lpeg library installed on your system in your lua code. On Windows, you can choose to put the lpeg.dll file into Mudlet's install folder. On macOS that is not possible due to restrictions placed by Apple.<br />
* If you used OnPluginPartialLine to match "partial lines" such as prompts, please note that any type of Mudlet triggers should work with such lines so you can just use them for your purpose. For prompts specifically, try tempPromptTrigger.<br />
* If you used OnPluginTick, you can use a GUI timer in Mudlet for essentially the same functionality.<br />
* If you used OnPluginCommandEntered, you can use a "catch all" alias (with a pattern like "^.+") to send all user commands to your script.<br />
* If you have an existing database you'd like to use and don't want to put it into the profile folder, you can use the standard luaSQL interface to load and use it. Some basic examples can be found at https://keplerproject.github.io/luasql/examples.html<br />
* Line numbers in Mudlet are absolute - lines will not get renumbered when they start getting deleted from the buffer.<br />
<br />
'''Converting MUSHclient triggers into Mudlet triggers'''<br />
<br />
The following scripts by Discord user Buck allow you to paste a MUSHclient trigger and automatically have a corresponding Mudlet trigger created. <br />
<br />
First, create a new script with this:<br />
<syntaxhighlight lang="lua"><br />
TRIGGER_GROUP_NAME = "mushtriggers"<br />
MUSHTRIGGER_PREFIX = "mt_"<br />
<br />
function getAvailableMushTriggerID()<br />
local n=1<br />
<br />
while exists( MUSHTRIGGER_PREFIX..tostring( n), 'trigger')>0 do<br />
n=n+1<br />
end<br />
<br />
return MUSHTRIGGER_PREFIX..tostring( n)<br />
end<br />
<br />
function addMushTrigger( pattern, actions)<br />
pattern = string.gsub( pattern, '%.', '\\.')<br />
pattern = string.gsub( pattern, '*', '(.+)')<br />
actions_regex = string.gsub( actions, '%%(%d)', function(x) return ']]..matches['..tostring(x+1)..']..[[' end)<br />
<br />
local id = getAvailableMushTriggerID()<br />
<br />
createTriggerGroup( TRIGGER_GROUP_NAME)<br />
permRegexTrigger(<br />
id,<br />
TRIGGER_GROUP_NAME,<br />
{pattern},<br />
'for _, cmd in ipairs( splitCommands( [['..actions_regex..']])) do expandAlias( cmd) end')<br />
end<br />
</syntaxhighlight><br />
<br />
Also create an alias with this:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- ^/trigger '([^']+)' (.+)$<br />
local pattern = matches[2]<br />
local actions = matches[3]<br />
<br />
addMushTrigger(pattern, actions)<br />
<br />
cecho("<green>New trigger added")<br />
</syntaxhighlight><br />
<br />
Now you can transfer your MUSH triggers like so:<br />
<br />
<syntaxhighlight lang="lua"><br />
/trigger 'A wild * enters the room' hit %1 <br />
<br />
/trigger '%d/%dhp %d/%dmn' /checkhealth %1<br />
</syntaxhighlight><br />
<br />
=From CMUD=<br />
Changing over to Mudlet requires learning some simple syntax changes and some general concept changes:<br />
<br />
'''In a mudlet trigger for example:'''<br />
Name is just the name you want to use to label the trigger. It doesn't effect the actual firing of the trigger. The trigger fires based on the "pattern" and you can have multiple patterns for a single piece of code. You can also have a multi-line trigger, where the entire trigger must see all the patterns to fire.<br />
'''Example #1 - Using a variable and a temp trigger'''<br />
'''Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern:<br />
^A (.*) shard appears and clatters to the ground\.$<br />
<br />
Code:<br />
#IF (@autogold) {<br />
#temp {You have recovered balance on all limbs.} <br />
{get shard}<br />
} <br />
</syntaxhighlight><br />
<br />
'''Mudlet Example:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
^A (.*) shard appears and clatters to the ground\.$<br />
<br />
Code:<br />
if autogold then<br />
shardtrigger = tempTrigger("You have recovered balance on all limbs.", [[send("get shard") killTrigger(shardtrigger)]])<br />
end<br />
</syntaxhighlight><br />
<br />
'''Example #2 - Doing Math:'''<br />
'''Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern:<br />
^You put (\d+) gold sovereigns in (.*)\.$<br />
<br />
Code:<br />
#ADD goldcounter %1<br />
</syntaxhighlight><br />
'''Mudlet:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
^You put (\d+) gold sovereigns in (.*)\.$<br />
<br />
Code:<br />
goldcounter = goldcounter + tonumber(matches[2])<br />
</syntaxhighlight><br />
<br />
'''Example #3 - Replacing Text'''<br />
'''Cmud'''<br />
<syntaxhighlight lang="lua"><br />
Pattern:<br />
^You raze (\w+) magical shield with (.*)\.$<br />
<br />
Code:<br />
#sub {%ansi(yellow,cyan,bold)(*X*)%ansi(white) RAZED %ansi(red)%1's %ansi(white)Shield %ansi(yellow,cyan,bold)(*X*)}<br />
</syntaxhighlight><br />
'''Mudlet'''<br />
<syntaxhighlight lang="lua"><br />
Pattern:<br />
^You raze (\w+) magical shield with (.*)\.$<br />
<br />
Code:<br />
deleteLine()<br />
cecho("<yellow:cyan>You RAZED " .. matches[2] .. " shield")<br />
</syntaxhighlight><br />
<br />
'''Example #4 - Enable/Disable Classes'''<br />
<br />
'''Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
#T+ ClassFolderName<br />
</syntaxhighlight><br />
<br />
'''Mudlet:''' <br />
<syntaxhighlight lang="lua"><br />
enableAlias("ClassFolderName")<br />
<br />
-- Note: Alias can be an alias, trigger (enableTrigger), timer (enableTimer), key (enableKey), etc. <br />
-- You can disable entire classes or just single triggers.<br />
</syntaxhighlight><br />
<br />
'''Example 5 - Multi-action Commands<br />
Let's say we create an alias called silly<br />
<br />
Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
sillyAction<br />
<br />
Code:<br />
look;ct Hello City;pt Hello Party;laugh<br />
<br />
-- Now in cmud if we called this alias from a trigger or another alias,<br />
-- we would just call sillyAction<br />
<br />
</syntaxhighlight><br />
'''<br />
Mudlet:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
sillyAction<br />
<br />
Code:<br />
sendAll("look","ct Hello City","pt Hello Party", "laugh") <br />
</syntaxhighlight><br />
<br />
-- Now, in mudlet, if we want to call on that alias, we need to tell mudlet that we want to execute the alias sillyAction rather than sending "sillyAction" directly to the mud. To do that we would do:<br />
<br />
<syntaxhighlight lang="lua"><br />
expandAlias("sillyAction")<br />
</syntaxhighlight><br />
<br />
'''Example 6 - Using if statements with and, or and nil.'''<br />
<br />
'''Cmud Code:'''<br />
<syntaxhighlight lang="lua"><br />
#IF (@myclass="knight" & !(@pets))<br />
{<br />
say cool<br />
}<br />
</syntaxhighlight><br />
'''<br />
Mudlet Code:'''<br />
<syntaxhighlight lang="lua"><br />
if myclass == "knight" and not pets then<br />
send("say cool")<br />
end<br />
</syntaxhighlight><br />
<br />
'''Example 7 - Hitting your target OR your first argument.'''<br />
This is for when you want to either hit the person you have targeted, or the name you type. <br />
<br />
For example, to kick Das you'd type:<br />
kk Das<br />
<br />
Or if Das is your target, just typing kk<br />
<br />
'''Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: ^kk ?(\w+)?$<br />
#VAR target Das<br />
if (@target) {<br />
kick @target<br />
}<br />
if (%1) {<br />
kick %1<br />
}<br />
</syntaxhighlight><br />
<br />
'''Mudlet:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
^kk ?(\w+)?$<br />
<br />
Code:<br />
target = "Das"<br />
send("kick "..(matches[2] or target))<br />
</syntaxhighlight><br />
'''<br />
Example #7 - Two Pattern Examples'''<br />
<syntaxhighlight lang="lua">^rz(?:(.*)|)$ <br />
-- This would let you do rzDas to raze Das for example.<br />
</syntaxhighlight><br />
Versus:<br />
<syntaxhighlight lang="lua"><br />
^rz ?(\w+)?$ <br />
-- This would require you to do rz Das with a space between rz and Das.<br />
</syntaxhighlight><br />
<br />
'''Example #8 - Repeat Commands a number of times''' with %i functionality, i.e., #12 kill bug %i will send "kill bug 1", "kill bug 2", "kill bug 3"...etc<br />
<syntaxhighlight lang="lua"><br />
--Pattern: ^\#(\d+)\s(.+)$<br />
<br />
local cmd = matches[3]<br />
for i=1, tonumber(matches[2]) do <br />
local tempCMD = string.gsub(cmd, "%%i", i)<br />
expandAlias(tempCMD)<br />
end<br />
<br />
-- We have to store the initial matches table in a variable because each loop might change the current matches table.<br />
<br />
</syntaxhighlight><br />
<br />
'''#Example #9 - controlling many characters at once'''<br />
Check out [https://forums.mudlet.org/viewtopic.php?f=6&t=23023 this premade package] that helps you with this.<br />
<br />
=From zMUD=<br />
Pretty similar to migrating [[#From CMUD]] - see above.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Migrating&diff=20794Manual:Migrating2024-01-18T16:46:11Z<p>Kebap: /* From Nexus */ Add note on dated instructions</p>
<hr />
<div>{{TOC right}}<br />
=From Nexus=<br />
<br />
{{note}} The Nexus information seems a bit out of date. Please feel free to add or update with more current instructions.<br />
<br />
'''Trigger patterns'''<br />
<br />
Lets start with triggers. For translating Nexus patterns into Mudlet, use the following table below. Make sure to set the pattern type in Mudlet to be perl regex, because the default substring works differently.<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th> <br />
<th>What it does</th> <br />
<tr><br />
<td>(\w+)</td><br />
<td>{w}</td><br />
<td>Match one or more non-whitespace characters (a 'word')</td><br />
</tr><br />
<tr><br />
<td>(\d+)</td><br />
<td>{d}</td><br />
<td>Match one or more numeric digits (a number)</td><br />
</tr><br />
<tr><br />
<td>([abc])</td><br />
<td>{[abc]}</td><br />
<td>Match one or more of either 'a', 'b' or 'c'. (a character class)</td><br />
</tr><br />
<tr><br />
<td>([^abc])</td><br />
<td>{[^abc]}</td><br />
<td>Match one or more of anything EXCEPT 'a', 'b', or 'c'</td><br />
</tr><br />
<tr><br />
<td>(.*)</td><br />
<td>{*}</td><br />
<td>Match zero or more characters (anything)</td><br />
</tr><br />
<tr><br />
<td>^</td><br />
<td>{<} </td><br />
<td>Match the beginning of a line (not the actual newline character)</td><br />
</tr><br />
<tr><br />
<td>$</td><br />
<td>{>}</td><br />
<td>Match the end of a line (not the actual newline character)</td><br />
</table> <br />
<table frame="box"><br />
<caption>'''Note:'''</caption><br />
<td>If you just have a pattern with a {<} and {>} and nothing else, copy the pattern over without the {<}{>} and select the exact match pattern type. For example {<}You sit down.{>} in Nexus would become '''You sit down.''' in Mudlet with the pattern type of exact match. This is easier to read and matches way faster!</td><br />
</table><br />
<br />
<br />
'''Basic scripting'''<br />
<br />
The Nexus way of doing a function is like this: #function stuff it does. In Mudlet, it’s function(stuff it does). Note that if you’d like to give text to a function, you put it inside double or single quotes.<br />
<br />
'''Calling functions'''<br />
<table border="1" width="100%"><br />
<caption>Calling functions</caption><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
send("hi")<br />
echo("Hello to me!")<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
#send hi<br />
#echo Hello to me!<br />
</code><br />
</td><br />
</tr><br />
</table><br />
<table frame="box"><br />
<caption>'''Note:'''</caption><br />
<td><br />
If you’d like to use a variable inside text, you’d put it outside the quotes and glue it together with two dots.<br />
</td><br />
</table><br />
<br />
'''Setting variables'''<br />
<table border="1" width="100%"><br />
<caption>Setting variables</caption><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
number = 1234<br />
echo("My number is: " .. number.. "\n")<br />
echo("the " .. number .. " is in the middle of my text\n")<br />
echo(string.format("And here's another - %s - way to format things\n", number))<br />
</syntaxhighlight><br />
<td><br />
<code><br />
#set number 1234<br />
#echo My number is: $number<br />
#echo the $number is in the middle of my text<br />
</code><br />
</td><br />
</tr><br />
<table><br />
<br />
'''Wildcards'''<br />
<br />
To use the wildcard variable in Nexus, you’d use $1 for the first match, $2 for the second and so on. In Mudlet, the matches[] table contains the matches - and it starts placing the matches from 2. So the Nexus $1 would be matches[2], $2 would be matches[3].<br />
<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
(\w+) kicks you\.<br />
badguy = matches[2]<br />
echo(badguy .. " kicked me!")<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
{w} kicks you.<br />
#set badguy $1<br />
#echo $badguy kicked me!<br />
</code><br />
</td><br />
</tr><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
alias pattern: ^t (.*)$<br />
alias script: target = matches[2]<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
alias name: t<br />
alias script: #set target $1<br />
</code><br />
</td><br />
</tr><br />
<table><br />
<table frame="box"><br />
<caption>'''Note:'''</caption><br />
<td><br />
The reason the first match goes into matches[2] and not matches[1] is because matches[1] contains the part of the line that matched your trigger / alias.<br />
</td><br />
<table><br />
<br />
'''#wait'''<br />
<br />
In Nexus, a #wait will freeze the script while it’s executing - such that commands after it are delayed. In Mudlet, we use tempTimer which that works a bit differently - it doesn’t freeze the script, but instead makes it so commands a tempTimer is asked to do will get done in the future.<br />
<br />
So the difference is that a tempTimer doesn’t freeze the commands following it at all, everything gets done at once as usual. Just things a tempTimer was asked to do get done in the future.<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
send("hello")<br />
tempTimer(1, [[send("hi")]])<br />
tempTimer(1.5, [[send("bye")]])<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
#send hello<br />
#wait 1000<br />
#send hi<br />
#wait 500<br />
#send bye<br />
</code><br />
</td><br />
</tr><br />
</table><br />
<br />
'''ifs in Mudlet'''<br />
<br />
Next are the #if statements. Here’s a table comparing the syntaxes of Nexus and Mudlet:<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
if <condition> then <text> end<br />
</td><br />
<td><br />
<nowiki>#if <condition> <text></nowiki><br />
<nowiki>#if <condition> { <script> }</nowiki><br />
</td><br />
</tr><br />
<tr><br />
<td><br />
if <condition> then <script> else <script> end<br />
</td><br />
<td><br />
<nowiki>#if <condition> { <script> } else { <script> }</nowiki><br />
<nowiki>#if <condition> { <script> } { <script> }</nowiki><br />
</td><br />
</tr><br />
<tr><br />
<td><br />
if <condition> then <script> elseif <condition> then <script> end<br />
</td><br />
<td><br />
<nowiki>#if <condition> { <script> } elsif <condition> { <script> }</nowiki><br />
</td><br />
</tr><br />
<tr><br />
<td><br />
if <condition> then <script> elseif <condition> then <script> else <script> end<br />
</td><br />
<td><br />
<nowiki>#if <condition> { <script> } elsif <condition> { <script> } else { <script> }</nowiki><br />
</td><br />
<tr><br />
</table><br />
<br />
<br />
Here is the sample side-by-side comparison of how you’d use it:<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><br />
<syntaxhighlight lang="lua"><br />
-- If foo is true, echo that fact.<br />
if foo then echo ("Foo is true!") end -- If foo is true, echo that fact.<br />
<br />
-- A slight modification of the above that illustrates an 'else' clause.<br />
-- Note that the 'then' is always necessary to avoid confusion.<br />
if foo then echo ("Foo is true!") else echo ("Foo is false!") end<br />
<br />
-- Illustration of putting more than one statement in a block (also<br />
-- spans lines here). Note the if doesn't end until the last 'end' is<br />
-- encountered.<br />
-- We also add a \n at the end of multiple echos so each one is on it's own line.<br />
if foo then<br />
echo ("Foo is true!\n")<br />
echo ("Isn't it grand?\n")<br />
echo ("These commands are all on separate lines too!\n")<br />
end<br />
<br />
-- This shows how ifs continue (on 'logical' lines) even though the<br />
-- blocks in its constituent clauses may have multiple lines. The<br />
-- following lines are all _one_ single if statement.<br />
if foo > 50 then<br />
echo ("Foo is big!\nYes it is.")<br />
elseif foo > 10 then<br />
echo ("Foo is pretty big...\n")<br />
echo ("I've seen bigger.")<br />
else<br />
echo ("Foo is actually kind of small.")<br />
end<br />
<br />
-- Ifs can be nested too.<br />
if foo then<br />
if bar then<br />
echo ("Both foo and bar are true.")<br />
else<br />
echo ("Foo's true, but bar isn't.")<br />
end<br />
end<br />
</syntaxhighlight><br />
</td><br />
<td><br />
<code><br />
<br>// If $foo is true, echo that fact.<br />
#if $foo #echo Foo is true! // If $foo is true, echo that fact.<br />
<br />
<br>// A slight modification of the above that illustrates an 'else' clause.<br />
<br>// The second form shows that the word 'else' is actually optional too.<br />
<br>// (The two lines are functionally the same.)<br />
#if $foo { #echo Foo is true! } else { #echo Foo is false! }<br />
#if $foo { #echo Foo is true! } { #echo Foo is false! }<br />
<br />
<br>// Illustration of putting more than one statement in a block (also<br />
<br>// spans lines here). Note the if doesn't end until the last '}' is<br />
<br>// encountered.<br />
#if $foo {<br />
#echo Foo is true!<br />
#echo Isn't it grand?<br />
#echo These commands are all on separate lines too!<br />
}<br />
<br />
<br>// This shows how ifs continue (on 'logical' lines) even though the<br />
<br>// blocks in its constituent clauses may have multiple lines. The<br />
<br>// following lines are all _one_ single if statement.<br />
#if $foo > 50 {<br />
#echo Foo is big!<br />
#echo Yes it is.<br />
} elsif $foo > 10 {<br />
#echo Foo is pretty big...<br />
#echo I've seen bigger.<br />
} else {<br />
#echo Foo is actually kind of small.<br />
}<br />
<br />
// Ifs can be nested too.<br />
#if $foo {<br />
#if $bar {<br />
#echo Both foo and bar are true.<br />
} else {<br />
#echo Foo's true, but bar isn't.<br />
}<br />
}<br />
</code><br />
</td><br />
</tr><br />
</table><br />
<br />
'''Mudlet equivalents of Nexus functions'''<br />
<br />
Now that we got the ifs covered, lets go over the Mudlet equivalents of other Nexus functions. Note that this is a direct Nexus→Mudlet comparison; certain functions in Mudlet have much more capability.<br />
<table border="1" width="100%"><br />
<th>Mudlet</th><br />
<th>Nexus</th><br />
<tr><br />
<td><variable name> = "<text value>"</td><br />
<td><nowiki>#set <variable name> <text value></nowiki></td><br />
</tr><br />
<tr><br />
<td><variable name> = <expression></td><br />
<td><nowiki>#set <variable name> = <expression></nowiki></td><br />
</tr><br />
<tr><br />
<td><variable name> = nil</td><br />
<td><nowiki>#unset <variable name></nowiki></td><br />
</tr><br />
<tr><br />
<td><variable> = <variablename> <+ - / *> <number or variable></td><br />
<td><nowiki>#add <variablename> <expression></nowiki></td><br />
</tr><br />
<tr><br />
<td>echo "text\n" or echo("text\n")</td><br />
<td><nowiki>#echo <text></nowiki></td><br />
</tr><br />
<tr><br />
<td>echo "text" or echo("text")</td><br />
<td><nowiki>#echo_ <text></nowiki></td><br />
</tr><br />
<tr><br />
<td>enableAlias("<group name>")/enableTrigger()/enableKey()/enableTimer()</td><br />
<td><nowiki>#groupon <group name></nowiki></td><br />
</tr><br />
<tr><br />
<td>disableAlias("<group name>")disableTrigger()disableKey()disableTimer()</td><br />
<td><nowiki>#groupoff <group name></nowiki></td><br />
</tr><br />
<tr><br />
<td>selectString (line, 1) bg("<color>") resetFormat()</td><br />
<td><nowiki> #highlight <color></nowiki></td><br />
</tr><br />
<tr><br />
<td>deleteLine()</td><br />
<td><nowiki>#gag</nowiki></td><br />
</tr><br />
<tr><br />
<td>openUrl("<url>")</td><br />
<td><nowiki>#openurl <url></nowiki></td><br />
</tr><br />
<tr><br />
<td>send("<stuff>")</td><br />
<td><nowiki>#send <text></nowiki></td><br />
</tr><br />
<tr><br />
<td>sendAll("hi", "hello", "bye")</td><br />
<td><nowiki>#send_ hi #send_ hello #send bye</nowiki></td><br />
</tr><br />
<tr><br />
<td>tempTimer(<nowiki><time in s></nowiki>, [[ <nowiki><lua code to do once time is up></nowiki> ]])</td><br />
<td><nowiki>#wait <milliseconds></nowiki></td><br />
</tr><br />
</table><br />
<br />
'''How to call aliases in Mudlet'''<br />
<br />
The typical workflow in Nexus is that you’d define the aliases for yourself to use, and also use aliases for system-related things (things like checking if you’d need to eat a herb, etc).<br />
<br />
While the first use is good, the second isn’t - because the user can also run this alias at an inopportune time, because if you want to call an alias it has to match all alises again, and so on.<br />
<br />
Now, while in Mudlet you can call another alias with the expandAlias() function, this is strongly discouraged. What you do instead if create a function (for example, send() and echo() are functions) that you can then call from your alias or trigger. This has many advantages - it’s faster, you can easily give your function values, and your function can return you values, too.<br />
<br />
To make a function, you go to the Scripts section, create a new script, and write in your function:<br />
<syntaxhighlight lang="lua"><br />
function <name> ()<br />
<stuff it does><br />
end<br />
</syntaxhighlight><br />
For example, if we want to make a function that does two things for us at once, we’d do this:<br />
<syntaxhighlight lang="lua"><br />
function eat_bloodroot()<br />
send ("outr bloodroot")<br />
send ("eat bloodroot")<br />
end<br />
</syntaxhighlight><br />
Then just do this in our alias or trigger to outr and eat bloodroot:<br />
<syntaxhighlight lang="lua"><br />
eat_bloodroot()<br />
</syntaxhighlight><br />
As mentioned, you can also give things to functions - in this case lets expand the function to eat any herb for us we tell it:<br />
<syntaxhighlight lang="lua"><br />
function eat (what)<br />
send ("outr " .. what)<br />
send ("eat " .. what)<br />
end<br />
[...]<br />
eat ("bloodroot")<br />
eat ("kelp")<br />
eat ("ginseng")<br />
</syntaxhighlight><br />
Lastly, functions can also give you data back. One useful example for this is to break down tasks into functions, which will help your code readability:<br />
<syntaxhighlight lang="lua"><br />
function can_i_stand()<br />
if not paralyzed and not prone and not stunned then<br />
return true<br />
else<br />
return false<br />
end<br />
[...]<br />
if can_i_stand() and have_balance and have_equilibrium then<br />
send ("stand")<br />
end<br />
</syntaxhighlight><br />
==Notes to be aware of==<br />
<br />
To finish off, a couple of points that should be remembered:<br />
* Mudlet does profile snapshots (nexus archives) automatically - to load a different one, select it from the list when connecting<br />
* Mudlet can import and export xml<br />
* Mudlet and Nexus xml formats aren’t compatible<br />
* Mudlet can do nexus graphics, here is a package for - [https://forums.mudlet.org/viewtopic.php?f=6&t=981 Achaea], [https://www.lusternia.com/node/28106 Lusternia]<br />
* Mudlet has a ton more features such as more speed, less bugs, copy from the normal window, replay logging, color html logging, more powerful scripting, and the list goes on.<br />
<br />
=From MUSHclient=<br />
<br />
* Mudlet doesn't use %#'s - uses matches[] instead. "%1" or %1 would be matches[2], "%2" or %2 would be matches[3] and so on<br />
* No variables in trigger patterns - but you can check against your variables in scripts, or lua function pattern types<br />
* <code>Send()</code> in MUSHclient is called [[Manual:Lua Functions#send|send()]] with a lower S in Mudlet - in Lua, capitalization matters! To send a command without echoing it on the screen, use:<br />
<syntaxhighlight lang="lua">send("my text", false)</syntaxhighlight><br />
* While MUSHclient uses [https://www.gammon.com.au/scripts/doc.php?function=AnsiNote AnsiNote] to write colorful text, Mudlet offers different ways as well: [[Manual:Lua Functions#cecho|cecho()]] works with the name of a color. You can find lots of predefined colors with [[Manual:Lua Functions#showColors|showColors()]]. You can also style foreground and background seperately with [[Manual:Lua Functions#fg|fg()]] and [[Manual:Lua Functions#bg|bg()]]. To keep your original ANSI colors, use [[Manual:Lua Functions#ansi2decho|ansi2decho()]]. If you need more colors, [[Manual:Lua Functions#decho|decho()]] will take rgb numbers, [[Manual:Lua Functions#hecho|hecho()]] uses hex codes.<br />
* Mudlet does not offer 'GetConnectDuration()' but you could create a script to connect to the [[Manual:Event_Engine#sysConnectionEvent|connection event]] (and maybe sysDisconnectionEvent) and in that function [[Manual:Mudlet_Object_Functions#createStopWatch|start a stopwatch]] to keep count of how long you've been connected for. See [[Manual:Event Engine]] on how to use events in Mudlet.<br />
* Mudlet does not have lpeg built-in but you can include the lpeg library installed on your system in your lua code. On Windows, you can choose to put the lpeg.dll file into Mudlet's install folder. On macOS that is not possible due to restrictions placed by Apple.<br />
* If you used OnPluginPartialLine to match "partial lines" such as prompts, please note that any type of Mudlet triggers should work with such lines so you can just use them for your purpose. For prompts specifically, try tempPromptTrigger.<br />
* If you used OnPluginTick, you can use a GUI timer in Mudlet for essentially the same functionality.<br />
* If you used OnPluginCommandEntered, you can use a "catch all" alias (with a pattern like "^.+") to send all user commands to your script.<br />
* If you have an existing database you'd like to use and don't want to put it into the profile folder, you can use the standard luaSQL interface to load and use it. Some basic examples can be found at https://keplerproject.github.io/luasql/examples.html<br />
* Line numbers in Mudlet are absolute - lines will not get renumbered when they start getting deleted from the buffer.<br />
<br />
'''Converting MUSHclient triggers into Mudlet triggers'''<br />
<br />
The following scripts by Discord user Buck allow you to paste a MUSHclient trigger and automatically have a corresponding Mudlet trigger created. <br />
<br />
First, create a new script with this:<br />
<syntaxhighlight lang="lua"><br />
TRIGGER_GROUP_NAME = "mushtriggers"<br />
MUSHTRIGGER_PREFIX = "mt_"<br />
<br />
function getAvailableMushTriggerID()<br />
local n=1<br />
<br />
while exists( MUSHTRIGGER_PREFIX..tostring( n), 'trigger')>0 do<br />
n=n+1<br />
end<br />
<br />
return MUSHTRIGGER_PREFIX..tostring( n)<br />
end<br />
<br />
function addMushTrigger( pattern, actions)<br />
pattern = string.gsub( pattern, '%.', '\\.')<br />
pattern = string.gsub( pattern, '*', '(.+)')<br />
actions_regex = string.gsub( actions, '%%(%d)', function(x) return ']]..matches['..tostring(x+1)..']..[[' end)<br />
<br />
local id = getAvailableMushTriggerID()<br />
<br />
createTriggerGroup( TRIGGER_GROUP_NAME)<br />
permRegexTrigger(<br />
id,<br />
TRIGGER_GROUP_NAME,<br />
{pattern},<br />
'for _, cmd in ipairs( splitCommands( [['..actions_regex..']])) do expandAlias( cmd) end')<br />
end<br />
</syntaxhighlight><br />
<br />
Also create an alias with this:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- ^/trigger '([^']+)' (.+)$<br />
local pattern = matches[2]<br />
local actions = matches[3]<br />
<br />
addMushTrigger(pattern, actions)<br />
<br />
cecho("<green>New trigger added")<br />
</syntaxhighlight><br />
<br />
Now you can transfer your MUSH triggers like so:<br />
<br />
<syntaxhighlight lang="lua"><br />
/trigger 'A wild * enters the room' hit %1 <br />
<br />
/trigger '%d/%dhp %d/%dmn' /checkhealth %1<br />
</syntaxhighlight><br />
<br />
=From CMUD=<br />
Changing over to Mudlet requires learning some simple syntax changes and some general concept changes:<br />
<br />
'''In a mudlet trigger for example:'''<br />
Name is just the name you want to use to label the trigger. It doesn't effect the actual firing of the trigger. The trigger fires based on the "pattern" and you can have multiple patterns for a single piece of code. You can also have a multi-line trigger, where the entire trigger must see all the patterns to fire.<br />
'''Example #1 - Using a variable and a temp trigger'''<br />
'''Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern:<br />
^A (.*) shard appears and clatters to the ground\.$<br />
<br />
Code:<br />
#IF (@autogold) {<br />
#temp {You have recovered balance on all limbs.} <br />
{get shard}<br />
} <br />
</syntaxhighlight><br />
<br />
'''Mudlet Example:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
^A (.*) shard appears and clatters to the ground\.$<br />
<br />
Code:<br />
if autogold then<br />
shardtrigger = tempTrigger("You have recovered balance on all limbs.", [[send("get shard") killTrigger(shardtrigger)]])<br />
end<br />
</syntaxhighlight><br />
<br />
'''Example #2 - Doing Math:'''<br />
'''Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern:<br />
^You put (\d+) gold sovereigns in (.*)\.$<br />
<br />
Code:<br />
#ADD goldcounter %1<br />
</syntaxhighlight><br />
'''Mudlet:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
^You put (\d+) gold sovereigns in (.*)\.$<br />
<br />
Code:<br />
goldcounter = goldcounter + tonumber(matches[2])<br />
</syntaxhighlight><br />
<br />
'''Example #3 - Replacing Text'''<br />
'''Cmud'''<br />
<syntaxhighlight lang="lua"><br />
Pattern:<br />
^You raze (\w+) magical shield with (.*)\.$<br />
<br />
Code:<br />
#sub {%ansi(yellow,cyan,bold)(*X*)%ansi(white) RAZED %ansi(red)%1's %ansi(white)Shield %ansi(yellow,cyan,bold)(*X*)}<br />
</syntaxhighlight><br />
'''Mudlet'''<br />
<syntaxhighlight lang="lua"><br />
Pattern:<br />
^You raze (\w+) magical shield with (.*)\.$<br />
<br />
Code:<br />
deleteLine()<br />
cecho("<yellow:cyan>You RAZED " .. matches[2] .. " shield")<br />
</syntaxhighlight><br />
<br />
'''Example #4 - Enable/Disable Classes'''<br />
<br />
'''Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
#T+ ClassFolderName<br />
</syntaxhighlight><br />
<br />
'''Mudlet:''' <br />
<syntaxhighlight lang="lua"><br />
enableAlias("ClassFolderName")<br />
<br />
-- Note: Alias can be an alias, trigger (enableTrigger), timer (enableTimer), key (enableKey), etc. <br />
-- You can disable entire classes or just single triggers.<br />
</syntaxhighlight><br />
<br />
'''Example 5 - Multi-action Commands<br />
Let's say we create an alias called silly<br />
<br />
Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
sillyAction<br />
<br />
Code:<br />
look;ct Hello City;pt Hello Party;laugh<br />
<br />
-- Now in cmud if we called this alias from a trigger or another alias,<br />
-- we would just call sillyAction<br />
<br />
</syntaxhighlight><br />
'''<br />
Mudlet:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
sillyAction<br />
<br />
Code:<br />
sendAll("look","ct Hello City","pt Hello Party", "laugh") <br />
</syntaxhighlight><br />
<br />
-- Now, in mudlet, if we want to call on that alias, we need to tell mudlet that we want to execute the alias sillyAction rather than sending "sillyAction" directly to the mud. To do that we would do:<br />
<br />
<syntaxhighlight lang="lua"><br />
expandAlias("sillyAction")<br />
</syntaxhighlight><br />
<br />
'''Example 6 - Using if statements with and, or and nil.'''<br />
<br />
'''Cmud Code:'''<br />
<syntaxhighlight lang="lua"><br />
#IF (@myclass="knight" & !(@pets))<br />
{<br />
say cool<br />
}<br />
</syntaxhighlight><br />
'''<br />
Mudlet Code:'''<br />
<syntaxhighlight lang="lua"><br />
if myclass == "knight" and not pets then<br />
send("say cool")<br />
end<br />
</syntaxhighlight><br />
<br />
'''Example 7 - Hitting your target OR your first argument.'''<br />
This is for when you want to either hit the person you have targeted, or the name you type. <br />
<br />
For example, to kick Das you'd type:<br />
kk Das<br />
<br />
Or if Das is your target, just typing kk<br />
<br />
'''Cmud:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: ^kk ?(\w+)?$<br />
#VAR target Das<br />
if (@target) {<br />
kick @target<br />
}<br />
if (%1) {<br />
kick %1<br />
}<br />
</syntaxhighlight><br />
<br />
'''Mudlet:'''<br />
<syntaxhighlight lang="lua"><br />
Pattern: <br />
^kk ?(\w+)?$<br />
<br />
Code:<br />
target = "Das"<br />
send("kick "..(matches[2] or target))<br />
</syntaxhighlight><br />
'''<br />
Example #7 - Two Pattern Examples'''<br />
<syntaxhighlight lang="lua">^rz(?:(.*)|)$ <br />
-- This would let you do rzDas to raze Das for example.<br />
</syntaxhighlight><br />
Versus:<br />
<syntaxhighlight lang="lua"><br />
^rz ?(\w+)?$ <br />
-- This would require you to do rz Das with a space between rz and Das.<br />
</syntaxhighlight><br />
<br />
'''Example #8 - Repeat Commands a number of times''' with %i functionality, i.e., #12 kill bug %i will send "kill bug 1", "kill bug 2", "kill bug 3"...etc<br />
<syntaxhighlight lang="lua"><br />
--Pattern: ^\#(\d+)\s(.+)$<br />
<br />
local cmd = matches[3]<br />
for i=1, tonumber(matches[2]) do <br />
local tempCMD = string.gsub(cmd, "%%i", i)<br />
expandAlias(tempCMD)<br />
end<br />
<br />
-- We have to store the initial matches table in a variable because each loop might change the current matches table.<br />
<br />
</syntaxhighlight><br />
<br />
'''#Example #9 - controlling many characters at once'''<br />
Check out [https://forums.mudlet.org/viewtopic.php?f=6&t=23023 this premade package] that helps you with this.<br />
<br />
=From zMUD=<br />
Pretty similar to CMUD - see above.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Main_Page&diff=20724Main Page2024-01-08T23:35:27Z<p>Kebap: */ Lua /* shuffle more links</p>
<hr />
<div><languages/><br />
<!-- BANNER ACROSS TOP OF PAGE --><br />
{| id="mp-topbanner" style="width:100%; background:#fcfcfc; margin-top:1.2em; border:1px solid #ccc;"<br />
| style="width:56%; color:#000;" |<br />
<!-- "WELCOME TO THE MUDLET WIKI" AND ARTICLE COUNT --><br />
{| style="width:280px; border:none; background:none;"<br />
| style="width:280px; text-align:center; white-space:nowrap; color:#000;" |<br />
<div style="font-size:162%; border:none; margin:0; padding:.1em; color:#000;"><translate><!--T:1--> Welcome to the Mudlet Wiki!</translate></div><br />
|}<br />
<!-- BASIC INTRO --><br />
{| id="mp-upper" style="margin:0 0 0 0; background:none;"<br />
| class="MainPageBG" style="width:100%; border:1px solid #c9c07f; background:#c9c07f; vertical-align:top; color:#000;" |<br />
{| id="mp-left" cellpadding="2" cellspacing="5" style="width:100%; vertical-align:top; background:#fdf7bb;"<br />
! <h2 id="mp-tfa-h2" style="margin:0; background:#f4e9bc; font-size:120%; font-weight:bold; border:1px solid #a3b00f; text-align:left; color:#000; padding:0.2em 0.4em;"><translate><!--T:2--> About Mudlet</translate></h2><br />
|-<br />
| style="color:#000;" | <div id="mp-tfa"><br />
<br />
{{TOC right}}<br />
<br />
<translate><br />
<!--T:3--><br />
A cross-platform, open source, and super fast [http://en.wikipedia.org/wiki/Mud_client MUD client] with scripting in [http://en.wikipedia.org/wiki/Lua Lua].<br />
<br />
<!--T:4--><br />
New to Mudlet? Why not start with [http://mudlet.org/media the basics], or take a look at '''[[Special:MyLanguage/Manual:Contents | Mudlet Manual]]'''. Or perhaps you want to find the answer to a [[Special:MyLanguage/FAQ | Frequently Asked Question]]. If you don't have it yet, [http://www.mudlet.org/download/ download it] - it's free, and works on Windows, macOS, and Linux computers.<br />
<br />
<!--T:5--><br />
Are you having troubles with Mudlet? We can help. [http://forums.mudlet.org/viewforum.php?f=9 Start here].<br />
<br />
<br />
== External Links == <!--T:6--><br />
<br />
<!--T:7--><br />
* [http://www.mudlet.org Mudlet Homepage]<br />
* [http://forums.mudlet.org Forums]<br />
<br />
<br />
== Wiki Links == <!--T:8--><br />
<br />
<!--T:9--><br />
* [[Special:MyLanguage/Manual:Contents | Mudlet Manual]]<br />
* [[Manual:Technical_Manual|Technical Manual]]<br />
** [[Special:MyLanguage/Manual:Lua Functions | Mudlet Lua API]]<br />
*** [[Manual:Database Functions]]<br />
*** [[Manual:Date/Time Functions]]<br />
*** [[Manual:Discord Functions]]<br />
*** [[Manual:Mapper Functions]]<br />
*** [[Manual:Miscellaneous Functions]]<br />
*** [[Manual:Mudlet Object Functions]]<br />
*** [[Manual:Networking Functions]]<br />
*** [[Manual:String Functions]]<br />
*** [[Manual:Table Functions]]<br />
*** [[Manual:Text to Speech Functions]]<br />
*** [[Manual:UI Functions]]<br />
* [https://www.mudlet.org/geyser/files/geyser/Geyser.html Geyser Reference Docs]<br />
* [[Special:MyLanguage/FAQ | Frequently Asked Questions]]<br />
* [http://forums.mudlet.org/viewforum.php?f=6 Mudlet Packages Forum]<br />
* [[Special:MyLanguage/Compiling Mudlet|Compiling Mudlet]]<br />
* [[Special:MyLanguage/Translating Mudlet|Translating Mudlet]]<br />
* [[Accessibility]]<br />
<br />
<br />
== MUD standards == <!--T:10--><br />
<br />
<!--T:11--><br />
We will preserve the documentation of MUD standards that may get lost (because the original site is breaking down or is already offline) as they are implemented in Mudlet. We may also look into developing some of them in the future.<br />
* [[Special:MyLanguage/Standards:MMP | MUD Mapping Protocol]]<br />
* [[Special:MyLanguage/Standards:Discord_GMCP | Discord Rich Presence over GMCP]]<br />
* [[Special:MyLanguage/Standards:MUD_Client_Media_Protocol | Mud Client Media Protocol]]<br />
<br />
<br />
== Lua == <!--T:12--><br />
<br />
<!--T:13--><br />
Mudlet uses Lua! <br />
Learning Lua is really rewarding - Take a look at excellent stuff like:<br />
<br />
* [http://www.lua.org/pil/ Programming in Lua] (official, but might be hard to follow)<br />
* [https://www.youtube.com/playlist?list=PLxgtJR7f0RBKGid7F2dfv7qc-xWwSee2O Learning Lua] (video playlist)<br />
* [https://learnxinyminutes.com/docs/lua/ Learn X in Y minutes - Lua] (if you're familiar with coding already)<br />
* [https://www.youtube.com/watch?v=S4eNl1rA1Ns Learn Lua in an Hour] (video from the same author)<br />
* [https://devhints.io/lua Lua cheatsheet]<br />
* and various [http://lua-users.org/wiki/TutorialDirectory Lua tutorials]<br />
<br />
== Special Links == <!--T:14--><br />
<br />
<!--T:15--><br />
* [[Special:AllPages | All Pages]]<br />
* [[Special:MyLanguage/Report Spam|Report spam]] if you notice suspicious behavior<br />
<br />
<br />
== Using MediaWiki == <!--T:16--><br />
<br />
<!--T:17--><br />
Interested in contributing to this site? Please do! While first edit will be manually approved (this is to help against spambots), any follow-up edits will show up right away.<br />
<br />
Use the following links to learn more about MediaWiki: (note that the following links are not related to Mudlet)<br />
<br />
<!--T:18--><br />
* [http://www.mediawiki.org/wiki/Help:Formatting Wiki syntax]<br />
* [http://en.wikipedia.org/wiki/Help:Table Wiki table syntax]<br />
<br />
</translate><br />
<br />
|}<br />
|}<br />
|}</div>Kebaphttps://wiki.mudlet.org/index.php?title=Main_Page&diff=20723Main Page2024-01-08T23:14:27Z<p>Kebap: </p>
<hr />
<div><languages/><br />
<!-- BANNER ACROSS TOP OF PAGE --><br />
{| id="mp-topbanner" style="width:100%; background:#fcfcfc; margin-top:1.2em; border:1px solid #ccc;"<br />
| style="width:56%; color:#000;" |<br />
<!-- "WELCOME TO THE MUDLET WIKI" AND ARTICLE COUNT --><br />
{| style="width:280px; border:none; background:none;"<br />
| style="width:280px; text-align:center; white-space:nowrap; color:#000;" |<br />
<div style="font-size:162%; border:none; margin:0; padding:.1em; color:#000;"><translate><!--T:1--> Welcome to the Mudlet Wiki!</translate></div><br />
|}<br />
<!-- BASIC INTRO --><br />
{| id="mp-upper" style="margin:0 0 0 0; background:none;"<br />
| class="MainPageBG" style="width:100%; border:1px solid #c9c07f; background:#c9c07f; vertical-align:top; color:#000;" |<br />
{| id="mp-left" cellpadding="2" cellspacing="5" style="width:100%; vertical-align:top; background:#fdf7bb;"<br />
! <h2 id="mp-tfa-h2" style="margin:0; background:#f4e9bc; font-size:120%; font-weight:bold; border:1px solid #a3b00f; text-align:left; color:#000; padding:0.2em 0.4em;"><translate><!--T:2--> About Mudlet</translate></h2><br />
|-<br />
| style="color:#000;" | <div id="mp-tfa"><br />
<br />
{{TOC right}}<br />
<br />
<translate><br />
<!--T:3--><br />
A cross-platform, open source, and super fast [http://en.wikipedia.org/wiki/Mud_client MUD client] with scripting in [http://en.wikipedia.org/wiki/Lua Lua].<br />
<br />
<!--T:4--><br />
New to Mudlet? Why not start with [http://mudlet.org/media the basics], or take a look at '''[[Special:MyLanguage/Manual:Contents | Mudlet Manual]]'''. Or perhaps you want to find the answer to a [[Special:MyLanguage/FAQ | Frequently Asked Question]]. If you don't have it yet, [http://www.mudlet.org/download/ download it] - it's free, and works on Windows, macOS, and Linux computers.<br />
<br />
<!--T:5--><br />
Are you having troubles with Mudlet? We can help. [http://forums.mudlet.org/viewforum.php?f=9 Start here].<br />
<br />
<br />
== External Links == <!--T:6--><br />
<br />
<!--T:7--><br />
* [http://www.mudlet.org Mudlet Homepage]<br />
* [http://forums.mudlet.org Forums]<br />
<br />
<br />
== Wiki Links == <!--T:8--><br />
<br />
<!--T:9--><br />
* [[Special:MyLanguage/Manual:Contents | Mudlet Manual]]<br />
* [[Manual:Technical_Manual|Technical Manual]]<br />
** [[Special:MyLanguage/Manual:Lua Functions | Mudlet Lua API]]<br />
*** [[Manual:Database Functions]]<br />
*** [[Manual:Date/Time Functions]]<br />
*** [[Manual:Discord Functions]]<br />
*** [[Manual:Mapper Functions]]<br />
*** [[Manual:Miscellaneous Functions]]<br />
*** [[Manual:Mudlet Object Functions]]<br />
*** [[Manual:Networking Functions]]<br />
*** [[Manual:String Functions]]<br />
*** [[Manual:Table Functions]]<br />
*** [[Manual:Text to Speech Functions]]<br />
*** [[Manual:UI Functions]]<br />
* [https://www.mudlet.org/geyser/files/geyser/Geyser.html Geyser Reference Docs]<br />
* [[Special:MyLanguage/FAQ | Frequently Asked Questions]]<br />
* [http://forums.mudlet.org/viewforum.php?f=6 Mudlet Packages Forum]<br />
* [[Special:MyLanguage/Compiling Mudlet|Compiling Mudlet]]<br />
* [[Special:MyLanguage/Translating Mudlet|Translating Mudlet]]<br />
* [[Accessibility]]<br />
<br />
<br />
== MUD standards == <!--T:10--><br />
<br />
<!--T:11--><br />
We will preserve the documentation of MUD standards that may get lost (because the original site is breaking down or is already offline) as they are implemented in Mudlet. We may also look into developing some of them in the future.<br />
* [[Special:MyLanguage/Standards:MMP | MUD Mapping Protocol]]<br />
* [[Special:MyLanguage/Standards:Discord_GMCP | Discord Rich Presence over GMCP]]<br />
* [[Special:MyLanguage/Standards:MUD_Client_Media_Protocol | Mud Client Media Protocol]]<br />
<br />
<br />
== Lua == <!--T:12--><br />
<br />
<!--T:13--><br />
Mudlet uses Lua! <br />
Learning Lua is really rewarding - Take a look at excellent stuff like:<br />
<br />
* [https://www.youtube.com/playlist?list=PLxgtJR7f0RBKGid7F2dfv7qc-xWwSee2O Learning Lua]<br />
* [https://devhints.io/lua Lua cheatsheet]<br />
* [http://tylerneylon.com/a/learn-lua/ Learn Lua in 15 mins] (if you're familiar with coding already)<br />
* [http://www.lua.org/pil/ Programming in Lua] (official, but might be hard to follow)<br />
* [https://learnxinyminutes.com/docs/lua/ Learn X in Y minutes - Lua] (quick intro, assumes programming experience)<br />
* and various [http://lua-users.org/wiki/TutorialDirectory Lua tutorials].<br />
<br />
== Special Links == <!--T:14--><br />
<br />
<!--T:15--><br />
* [[Special:AllPages | All Pages]]<br />
* [[Special:MyLanguage/Report Spam|Report spam]] if you notice suspicious behavior<br />
<br />
<br />
== Using MediaWiki == <!--T:16--><br />
<br />
<!--T:17--><br />
Interested in contributing to this site? Please do! While first edit will be manually approved (this is to help against spambots), any follow-up edits will show up right away.<br />
<br />
Use the following links to learn more about MediaWiki: (note that the following links are not related to Mudlet)<br />
<br />
<!--T:18--><br />
* [http://www.mediawiki.org/wiki/Help:Formatting Wiki syntax]<br />
* [http://en.wikipedia.org/wiki/Help:Table Wiki table syntax]<br />
<br />
</translate><br />
<br />
|}<br />
|}<br />
|}</div>Kebaphttps://wiki.mudlet.org/index.php?title=Main_Page&diff=20722Main Page2024-01-08T23:12:36Z<p>Kebap: */ Lua /* +1</p>
<hr />
<div><languages/><br />
<!-- BANNER ACROSS TOP OF PAGE --><br />
{| id="mp-topbanner" style="width:100%; background:#fcfcfc; margin-top:1.2em; border:1px solid #ccc;"<br />
| style="width:56%; color:#000;" |<br />
<!-- "WELCOME TO THE MUDLET WIKI" AND ARTICLE COUNT --><br />
{| style="width:280px; border:none; background:none;"<br />
| style="width:280px; text-align:center; white-space:nowrap; color:#000;" |<br />
<div style="font-size:162%; border:none; margin:0; padding:.1em; color:#000;"><translate><!--T:1--> Welcome to the Mudlet Wiki!</translate></div><br />
|}<br />
<!-- BASIC INTRO --><br />
{| id="mp-upper" style="margin:0 0 0 0; background:none;"<br />
| class="MainPageBG" style="width:100%; border:1px solid #c9c07f; background:#c9c07f; vertical-align:top; color:#000;" |<br />
{| id="mp-left" cellpadding="2" cellspacing="5" style="width:100%; vertical-align:top; background:#fdf7bb;"<br />
! <h2 id="mp-tfa-h2" style="margin:0; background:#f4e9bc; font-size:120%; font-weight:bold; border:1px solid #a3b00f; text-align:left; color:#000; padding:0.2em 0.4em;"><translate><!--T:2--> About Mudlet</translate></h2><br />
|-<br />
| style="color:#000;" | <div id="mp-tfa"><br />
<br />
{{TOC right}}<br />
<br />
<translate><br />
<!--T:3--><br />
A cross-platform, open source, and super fast [http://en.wikipedia.org/wiki/Mud_client MUD client] with scripting in [http://en.wikipedia.org/wiki/Lua Lua].<br />
<br />
<!--T:4--><br />
New to Mudlet? Why not start with [http://mudlet.org/media the basics], or take a look at '''[[Special:MyLanguage/Manual:Contents | Mudlet Manual]]'''. Or perhaps you want to find the answer to a [[Special:MyLanguage/FAQ | Frequently Asked Question]]. If you don't have it yet, [http://www.mudlet.org/download/ download it] - it's free, and works on Windows, macOS, and Linux computers.<br />
<br />
<!--T:5--><br />
Are you having troubles with Mudlet? We can help. [http://forums.mudlet.org/viewforum.php?f=9 Start here].<br />
<br />
<br />
== External Links == <!--T:6--><br />
<br />
<!--T:7--><br />
* [http://www.mudlet.org Mudlet Homepage]<br />
* [http://forums.mudlet.org Forums]<br />
<br />
<br />
== Wiki Links == <!--T:8--><br />
<br />
<!--T:9--><br />
* [[Special:MyLanguage/Manual:Contents | Mudlet Manual]]<br />
* [[Manual:Technical_Manual|Technical Manual]]<br />
** [[Special:MyLanguage/Manual:Lua Functions | Mudlet Lua API]]<br />
*** [[Manual:Database Functions]]<br />
*** [[Manual:Date/Time Functions]]<br />
*** [[Manual:Discord Functions]]<br />
*** [[Manual:Mapper Functions]]<br />
*** [[Manual:Miscellaneous Functions]]<br />
*** [[Manual:Mudlet Object Functions]]<br />
*** [[Manual:Networking Functions]]<br />
*** [[Manual:String Functions]]<br />
*** [[Manual:Table Functions]]<br />
*** [[Manual:Text to Speech Functions]]<br />
*** [[Manual:UI Functions]]<br />
* [https://www.mudlet.org/geyser/files/geyser/Geyser.html Geyser Reference Docs]<br />
* [[Special:MyLanguage/FAQ | Frequently Asked Questions]]<br />
* [http://forums.mudlet.org/viewforum.php?f=6 Mudlet Packages Forum]<br />
* [[Special:MyLanguage/Compiling Mudlet|Compiling Mudlet]]<br />
* [[Special:MyLanguage/Translating Mudlet|Translating Mudlet]]<br />
* [[Accessibility]]<br />
<br />
<br />
== MUD standards == <!--T:10--><br />
<br />
<!--T:11--><br />
We will preserve the documentation of MUD standards that may get lost (because the original site is breaking down or is already offline) as they are implemented in Mudlet. We may also look into developing some of them in the future.<br />
* [[Special:MyLanguage/Standards:MMP | MUD Mapping Protocol]]<br />
* [[Special:MyLanguage/Standards:Discord_GMCP | Discord Rich Presence over GMCP]]<br />
* [[Special:MyLanguage/Standards:MUD_Client_Media_Protocol | Mud Client Media Protocol]]<br />
<br />
<br />
== Lua == <!--T:12--><br />
<br />
<!--T:13--><br />
Mudlet uses Lua! Learning it is really rewarding - take a look at excellent stuff like:<br />
<br />
* [https://www.youtube.com/playlist?list=PLxgtJR7f0RBKGid7F2dfv7qc-xWwSee2O Learning Lua]<br />
* [https://devhints.io/lua Lua cheatsheet]<br />
* [http://tylerneylon.com/a/learn-lua/ Learn Lua in 15 mins] (if you're familiar with coding already)<br />
* [http://www.lua.org/pil/ Programming in Lua] (official, but might be hard to follow)<br />
* [https://learnxinyminutes.com/docs/lua/ Learn X in Y minutes - Lua] (quick intro, assumes programming experience)<br />
* and various [http://lua-users.org/wiki/TutorialDirectory Lua tutorials].<br />
<br />
== Special Links == <!--T:14--><br />
<br />
<!--T:15--><br />
* [[Special:AllPages | All Pages]]<br />
* [[Special:MyLanguage/Report Spam|Report spam]] if you notice suspicious behavior<br />
<br />
<br />
== Using MediaWiki == <!--T:16--><br />
<br />
<!--T:17--><br />
Interested in contributing to this site? Please do! While first edit will be manually approved (this is to help against spambots), any follow-up edits will show up right away.<br />
<br />
Use the following links to learn more about MediaWiki: (note that the following links are not related to Mudlet)<br />
<br />
<!--T:18--><br />
* [http://www.mediawiki.org/wiki/Help:Formatting Wiki syntax]<br />
* [http://en.wikipedia.org/wiki/Help:Table Wiki table syntax]<br />
<br />
</translate><br />
<br />
|}<br />
|}<br />
|}</div>Kebaphttps://wiki.mudlet.org/index.php?title=Fonts&diff=20650Fonts2023-12-24T20:15:54Z<p>Kebap: -1</p>
<hr />
<div>= Fonts =<br />
<br />
A collection of open source, typically monospaced fonts recommended by Mudlet users.<br />
<br />
* [https://fontlibrary.org/en/font/neomatrixcode Neomatrix Code] - monospaced font for developers<br />
* [https://github.com/tonsky/FiraCode Fira Code] - free monospaced font with programming ligatures<br />
* [https://www.jetbrains.com/lp/mono/ JetBrains Mono/]<br />
* [https://sourcefoundry.org/hack/ Hack]<br />
*[https://en.wikipedia.org/wiki/Source_Code_Pro Source Code Pro]<br />
<br />
<br />
'''How to choose the next font you want to test?''' <br />
<br />
* Maybe try [https://www.codingfont.com/ Coding Font], a "gamified experience to help you find your true love of coding fonts!" This is quite fun, lets you keep comparing and choosing between pairs of fonts until you get down to the one you like most.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Fonts&diff=20649Fonts2023-12-24T20:15:43Z<p>Kebap: +1</p>
<hr />
<div>= Fonts =<br />
<br />
A collection of open source, typically monospaced fonts recommended by Mudlet users.<br />
<br />
* [https://fontlibrary.org/en/font/neomatrixcode Neomatrix Code] - monospaced font for developers<br />
* [https://github.com/tonsky/FiraCode Fira Code] - free monospaced font with programming ligatures<br />
* [https://www.jetbrains.com/lp/mono/ JetBrains Mono/]<br />
* [https://sourcefoundry.org/hack/ Hack]<br />
* [https://www.monolisa.dev/ MonoLisa]<br />
* [https://en.wikipedia.org/wiki/Source_Code_Pro Source Code Pro]<br />
<br />
<br />
'''How to choose the next font you want to test?''' <br />
<br />
* Maybe try [https://www.codingfont.com/ Coding Font], a "gamified experience to help you find your true love of coding fonts!" This is quite fun, lets you keep comparing and choosing between pairs of fonts until you get down to the one you like most.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Fonts&diff=20648Fonts2023-12-24T20:11:10Z<p>Kebap: Add more fonts and links</p>
<hr />
<div>= Fonts =<br />
<br />
A collection of open source, typically monospaced fonts recommended by Mudlet users.<br />
<br />
* [https://fontlibrary.org/en/font/neomatrixcode Neomatrix Code] - monospaced font for developers<br />
* [https://github.com/tonsky/FiraCode Fira Code] - free monospaced font with programming ligatures<br />
* [https://www.jetbrains.com/lp/mono/ JetBrains Mono/]<br />
* [https://sourcefoundry.org/hack/ Hack]<br />
* [https://www.monolisa.dev/ MonoLisa]<br />
<br />
<br />
'''How to choose the next font you want to test?''' <br />
<br />
* Maybe try [https://www.codingfont.com/ Coding Font], a "gamified experience to help you find your true love of coding fonts!" This is quite fun, lets you keep comparing and choosing between pairs of fonts until you get down to the one you like most.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Fonts&diff=20647Fonts2023-12-24T20:10:35Z<p>Kebap: Add more fonts and links</p>
<hr />
<div>= Fonts =<br />
<br />
A collection of open source, typically monospaced fonts recommended by Mudlet users.<br />
<br />
* [https://fontlibrary.org/en/font/neomatrixcode Neomatrix Code] - monospaced font for developers<br />
* [https://github.com/tonsky/FiraCode Fira Code] - free monospaced font with programming ligatures<br />
* [https://www.jetbrains.com/lp/mono/ JetBrains Mono/]<br />
* [https://sourcefoundry.org/hack/ Hack]<br />
* [https://www.monolisa.dev/ MonoLisa]<br />
<br />
<br />
'''How to choose the next font you want to test?''' <br />
<br />
* Maybe try Coding Font[https://www.codingfont.com/ /], a "gamified experience to help you find your true love of coding fonts!" This is quite fun, lets you keep comparing and choosing between pairs of fonts until you get down to the one you like most.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Compiling_Mudlet&diff=20638Compiling Mudlet2023-12-21T10:19:01Z<p>Kebap: /* Compiling on Windows */ Mention execution policies</p>
<hr />
<div>{{TOC right}}<br />
<br />
If you just want to use Mudlet, you can skip these steps, and use one of the already ready (pre-compiled) installers [https://www.mudlet.org/download ready for download].<br />
<br />
Otherwise, hop in for new adventure! <br />
<br />
[[File:Easy Mudlet code understanding.png|frame|none]]<br />
<br />
= Key contributing information =<br />
<br />
Clang format is used to automatically format code submissions using the [https://github.com/Mudlet/Mudlet/blob/development/src/.clang-format src/.clang-format] style. [http://doc.qt.io/qtcreator/creator-beautifier.html See here] how to enable clang-format with Qt Creator - and make sure to specify the 'File' option for the configuration style.<br />
<br />
Branches:<br />
<br />
'''development''' is the development branch where new features can go.<br />
<br />
Workflow:<br />
<br />
Fork and submit a PR with your changes ([https://guides.github.com/activities/forking/ Github tutorial]).<br />
<br />
Here is a list of package versions delivered with different Linux distros. You may want to upgrade these: <br />
https://repology.org/project/mudlet/versions<br />
<br />
= Lua & Luarocks =<br />
<br />
Mudlet includes a [https://en.wikipedia.org/wiki/Lua_(programming_language) Lua] (version 5.1) scripting system for the end-user, which you, as a reader of this Wiki, may already be aware of! If not, you might wish to (after you have got your hands on a working Mudlet) take a look at [https://wiki.mudlet.org/w/Manual:Lua_Functions Mudlet Lua API] as that is the recommended place to find out the details of all the functions that Mudlet provides on top of the core Lua functionality.<br />
<br />
Some of that ability comes from extra code that is not built-in to Lua but is in the form of external modules either in the form of script (text) files written in the Lua language itself or binary (library) files compiled from (usually but not exclusively [https://en.wikipedia.org/wiki/C_(programming_language) 'C']) source code. In order to have that functionality Mudlet makes use of several of these modules which can most readily (if not already available as "packages" for a particular Operating System) be obtained as '''rocks''' from the public [https://en.wikipedia.org/wiki/LuaRocks Luarocks] collection. Such a rock actually consists of a ''rockspec'' file that gives instructions to the Luarocks tool how to obtains the (source) code, compile it on any supported OS into the form that a Lua interpreter (including the one included in '''''each''''' running Mudlet ''profile'') can use, and where and what it will be placed and called when it has been made. After that it should be available to Lua via the ''require'' command.<br />
<br />
Anyone compiling Mudlet for themselves will find it desirable to ensure they have a usable Luarocks installation and have the ''lua-yajl'' module installed before commencing to compile Mudlet itself; this is because a Lua (version 5.1) interpreter and that module are used within the build process of making the executable code that is the Mudlet application.<br />
<br />
= Compiling =<br />
<br />
== Compiling on Ubuntu ==<br />
<br />
These instructions will get you setup compiling on Ubuntu. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
===Ubuntu 22.04===<br />
Following instructions will work on Ubuntu 22.04 as well as all its flavours and derivatives (such as KDE Neon, for example)<br />
Important thing is to have ''Universe'' repository enabled in your package manager. (on Ubuntu you will have all the repositories that you need already enabled by default.)<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo apt install ubuntu-restricted-extras qtcreator build-essential git zlib1g-dev libhunspell-dev \<br />
libpcre3-dev libzip-dev libboost-dev libboost-all-dev libyajl-dev libpulse-dev libpugixml-dev \<br />
liblua5.1-0-dev lua-filesystem lua-zip lua-sql-sqlite3 luarocks ccache lua5.1 \<br />
libglu1-mesa-dev mesa-common-dev libglib2.0-dev libgstreamer1.0-dev libqt5opengl5-dev \<br />
qtmultimedia5-dev qttools5-dev qt5keychain-dev libsecret-1-dev \<br />
libqt5texttospeech5-dev qtspeech5-flite-plugin qtspeech5-speechd-plugin \<br />
qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo luarocks install lcf<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
sudo luarocks install lrexlib-pcre<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
4. '''installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
5. '''optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo apt install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.<br />
Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybidings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
===Other Ubuntu Versions===<br />
<br />
Most of the installation instructions for 22.04 should work for older versions as well. Of note is the required version of Qt, which is 5.14. If your used version of Ubuntu only supplies older<br />
Qt versions, have a look at [https://launchpad.net/~beineri Stephan Binners PPAs], which supplies a whole range of packages for different Ubuntu versions. Be sure to read the installation and<br />
usage instructions as Qt is installed to /opt and requires sourcing a script to set up.<br />
<br />
== Compiling on Chrome OS ==<br />
<br />
These instructions will get you setup compiling on Chrome OS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Install dependencies'''<br />
<br />
sudo apt install git build-essential qt5-default qtmultimedia5-dev qttools5-dev \<br />
lua5.1 liblua5.1-0-dev libpcre3-dev libboost-dev zlib1g-dev cmake \<br />
libhunspell-dev lua-rex-pcre lua-sql-sqlite3 lua-filesystem lua-zip libyajl-dev \<br />
libzip-dev libglu1-mesa-dev ccache libpugixml-dev mesa-common-dev qtcreator \<br />
libpulse-dev libglib2.0-dev luarocks libboost-all-dev libsecret-1-dev \<br />
ninja-build libsecret-1-dev<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''3. Get Mudlet source'''<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''4. Create a build directory'''<br />
<br />
cd mudlet<br />
mkdir build && cd build<br />
<br />
'''5. Run the following command '''<br />
<br />
cmake .. -G Ninja<br />
<br />
'''then:'''<br />
<br />
ninja<br />
<br />
'''5. Start the application you have just compiled - enjoy'''<br />
<br />
src/mudlet<br />
{{Note}}Did <code>ninja</code> fail with <code>c++: fatal error: Killed signal terminated program cclplus</code>? Try again with <code>ninja -j 2</code><br />
<br />
== Compiling on macOS ==<br />
<br />
These instructions will get you setup compiling on macOS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums] otherwise.<br />
<br />
<br />
'''1. Install prerequisites'''<br />
<br />
Install [https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12 XCode], command line tools for XCode, and [http://brew.sh HomeBrew].<br />
<br />
Once everything is installed, do:<br />
<br />
brew doctor<br />
brew update<br />
brew install git<br />
<br />
'''2. Get Mudlet source'''<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git <br />
<br />
'''3. Go to the parent of the mudlet "src" folder and create (if necessary) a build subdirectory (this is so that we can build out of source which keeps the source code clean)'''<br />
cd Mudlet && mkdir build<br />
<br />
'''3. Setup your environment'''<br />
./CI/travis.osx.before_install.sh<br />
./CI/travis.osx.install.sh<br />
<br />
luarocks config lua_version 5.1<br />
eval `luarocks path --lua-version=5.1`<br />
For the following, one may have to add <code>''_DIR="/opt/homebrew/"''</code> such as <code>PCRE_DIR="/opt/homebrew/"</code> or <code>ZIP_DIR="/opt/homebrew/"</code> if the installation could not find header files.<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lrexlib-pcre PCRE_DIR=`brew --prefix pcre`<br />
brew install sqlite<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luasql-sqlite3 SQLITE_DIR=`brew --prefix sqlite` <br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luautf8<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-yajl YAJL_LIBDIR=`brew --prefix yajl`<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luafilesystem<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-zip ZIP_DIR=`brew --prefix libzip`<br />
<br />
brew install p7zip<br />
export BOOST_ROOT="$(pwd)/../Mudlet/3rdparty/boost"<br />
export BOOST_URL="https://sourceforge.net/projects/boost/files/boost/1.83.0/boost_1_83_0.tar.bz2/download"<br />
mkdir -p $BOOST_ROOT<br />
curl --progress-bar --location --output $BOOST_ROOT/download.tar.bz2 $BOOST_URL<br />
7z -o$BOOST_ROOT x $BOOST_ROOT/download.tar.bz2 -y -bd<br />
7z -o$BOOST_ROOT x $BOOST_ROOT/download.tar -y -bd<br />
cd $BOOST_ROOT && cp -r boost_*/* .<br />
rm -rf boost_*/* download.tar.bz2 download.tar<br />
OK to answer yes to delete files if prompted for the <code>rm</code> command above.<br />
<br />
'''4. Run the following commands'''<br />
<br />
cd ../../build<br />
cmake ../../Mudlet -DCMAKE_PREFIX_PATH=`brew --prefix qt5`<br />
make -j `sysctl -n hw.ncpu`<br />
<br />
<br />
'''5. Enjoy'''<br />
<br />
The mudlet.app is now available in <code>src/</code> for launching:<br />
<br />
open src/Mudlet.app<br />
<br />
'''6. Qt Creator setup'''<br />
<br />
No Lua installation is found, despite it existing on your system? Launch Qt Creator by doing <code>open /Applications/Qt Creator.app</code> (location depends on how you installed it).<br />
<br />
Receiving a <code>No rule to make target ... libQt5UiTools_debug.a</code> error? A workaround is to [https://bugreports.qt.io/browse/QTBUG-81251?focusedCommentId=538705&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-538705 symlink a file].<br />
<br />
Mudlet in Qt Creator is not launching due to <code>dyld: Symbol not found: __cg_jpeg_resync_to_restart</code>? See [https://stackoverflow.com/a/44851430/72944 here] for a workaround.<br />
<br />
====== 7. Troubleshooting ======<br />
If you exhaust all efforts to get YAJL to compile on your local system with homebrew, [https://github.com/lloyd/yajl/ clone from the YAJL repository] then <code>./configure && sudo make install</code>.<br />
<br />
== Compiling on Debian 'Sid' ==<br />
<br />
'''1. Install required packages from main repo.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev<br />
<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Grab latest Mudlet source.'''<br />
<br />
mkdir ~/projects && cd ~/projects && git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
cd ~/projects/mudlet/src<br />
<br />
qmake<br />
<br />
make<br />
<br />
sudo make install<br />
<br />
== Compiling on Debian 11 'Bullseye' ==<br />
<br />
'''1. Install required packages.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev \<br />
qttools5-dev luarocks ccache libpugixml-dev libqt5texttospeech5-dev qtspeech5-flite-plugin \<br />
qtspeech5-speechd-plugin libqt5opengl5-dev ninja-build cmake libsecret-1-dev<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Get Mudlet source.'''<br />
<br />
mkdir ~/source && cd ~/source<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git<br />
<br />
Note: the line above will check out `development` branch source code, and this might not always be stable. You can check out the latest release source code using this command:<br />
<br />
git clone --recursive --branch main https://github.com/Mudlet/Mudlet.git<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
mkdir ~/source/Mudlet/build && cd ~/source/Mudlet/build<br />
<br />
qmake ../src/mudlet.pro<br />
<br />
make -j `nproc`<br />
<br />
sudo make install<br />
<br />
After these steps you can run Mudlet by typing:<br />
<br />
mudlet<br />
<br />
'''4. (Optional) Discord library'''<br />
<br />
If you get the following error;<br />
<br />
Could not find Discord library - searched in:<br />
<br />
you need to specify the discord library in your build. Run the following, changing the path where necessary;<br />
<br />
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/mudlet-dev/Mudlet/3rdparty/discord/rpc/lib/<br />
<br />
and recompile. You should see<br />
<br />
Discord integration loaded. Using functions from: "libdiscord-rpc.so"<br />
<br />
== Compiling on Raspberry Pi OS ==<br />
<br />
These instructions will get you compiling and running Mudlet on Raspberry Pi OS (Buster). Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
''' 1.a Install apt dependencies '''<br />
<br />
sudo apt-get update<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-graph-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev cmake<br />
<br />
<br />
[[File:Apt-get-install-y-n.png|center|thumb|installing apt dependencies]]<br />
<br />
''' 1.b Install luarocks dependencies '''<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl YAJL_LIBDIR=`find /usr -name "libyajl.so" -printf '%h\n'` YAJL_INCDIR=/usr/include<br />
<br />
<br />
[[File:After-luarocks-dependencies.png|center|thumb|after luarocks dependencies]]<br />
<br />
''' 2. Get Mudlet source '''<br />
<br />
mkdir ~/source && cd ~/source <br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
<br />
[[File:After-get-mudlet-source.png|center|thumb|After cloning]]<br />
<br />
''' 3. Create a build directory '''<br />
<br />
cd Mudlet && mkdir build && cd build<br />
<br />
''' 4. Run the following commands to build '''<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake ../src/mudlet.pro<br />
<br />
:If you get a response along the lines of:<br />
<br />
qmake: could not find a Qt installation of ''<br />
<br />
:then you likely have ''qtchooser'' present in your system that allows for both Qt4 and Qt5 (or more than one Qt5 version) and it modifiers qmake and some other Qt development programs to take an additional argument to specify which version to use. In that case you should use:<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake -qt=qt5 ../src/mudlet.pro<br />
<br />
[[File:After-qmake.png|center|thumb|After qmake]]<br />
<br />
''' THEN: '''<br />
:For the fastest compile time while still being able to use the system at all (~35min on a RPi4 with 4GB of ram)<br />
make -j $(expr `nproc` - 1)<br />
<br />
''' OR: '''<br />
<br />
:Use this if you have an older Raspberry Pi. Be prepared for it to take a while (over an hour) - ''it is not recommended to try to more than one compilation task at a time on the older systems with the '''-j''' option as they will only have a system memory with enough space for one of some of those tasks'':<br />
make<br />
<br />
[[File:Success.png|center|thumb|Success!]]<br />
<br />
''' 4. Install the application you have just compiled '''<br />
<br />
sudo make install<br />
<br />
[[File:Installed.png|center|thumb|Installed now]]<br />
<br />
''' 5. Enjoy! '''<br />
<br />
# mudlet is in the path, can just run it<br />
mudlet<br />
<br />
== Compiling on Arch Linux ==<br />
<br />
===AUR Install and Compile===<br />
Mudlet is available in the [https://aur.archlinux.org Arch User Repository].<br />
(If the AUR has become unmaintained/orphaned, then skip below to [https://wiki.mudlet.org/w/Compiling_Mudlet#Manual_Install_and_Compile Manual install].)<br />
<br />
To install it use your favourite AUR helper (helper tool will automatically resove dependancies); example using ''yay'' :<br />
yay -S mudlet<br />
<br />
For more info on this process, visit [https://wiki.archlinux.org/index.php/Arch_User_Repository Arch User Repository - ArchWiki].<br />
<br />
''Note: For the most recent development version of Mudlet, replace 'mudlet' with 'mudlet-git' in the above commands and proceed as described.''<br />
<br />
''Built in fonts have been disabled, but are available in packages listed as optional dependancies.''<br />
<br />
''Discord support in Mudlet depends on an external library provided by discord-rpc-api, which is also available in AUR, choose whichever variant suits you best.''<br />
<br />
===Manual Install and Compile===<br />
These instructions will get you setup compiling on Arch. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo pacman -S --needed cmake qt5-multimedia hunspell libzip lua51-filesystem qt5-gamepad lua51-luautf8 pugixml \<br />
ttf-font qtkeychain-qt5 boost qt5-tools ttf-bitstream-vera ttf-ubuntu-font-family noto-fonts-emoji glu luarocks<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo lua5.1 /usr/bin/luarocks install lcf<br />
sudo lua5.1 /usr/bin/luarocks install luautf8<br />
sudo lua5.1 /usr/bin/luarocks install lua-yajl<br />
sudo lua5.1 /usr/bin/luarocks install lrexlib-pcre<br />
sudo lua5.1 /usr/bin/luarocks install luasql-sqlite3<br />
sudo lua5.1 /usr/bin/luarocks install lua-zip<br />
<br />
There is an optional dependency for discord integration:<br />
git clone https://github.com/discord/discord-rpc<br />
cd discord-rpc<br />
mkdir build<br />
cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=/usr<br />
sudo cmake --build . --config Release --target install<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
'''4. installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''5. optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo pacman -S install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.↵Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybindings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
== Compiling on Fedora (aarch64) ==<br />
<br />
'''1. Install dependencies'''<br />
sudo dnf groupinstall "Development Tools" "Development Libraries"<br />
<br />
sudo dnf install compat-lua compat-lua-devel compat-lua-libs hunspell-devel lua5.1-filesystem luarocks pugixml-devel qtkeychain-qt5-devel bitstream-vera-fonts-all ccache qt-creator qt5-qtmultimedia-devel qt5-qtgamepad-devel yajl-devel qtchooser qt5-qttools-devel qt5-qttools-static zziplib-devel pcre-devel libzip-devel sqlite-devel<br />
<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luazip<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luasql-sqlite3<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lcf<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luautf8<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lua-yajl<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lrexlib-pcre<br />
In your user's home directory:<br />
<br />
If you use a bash shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .bashenv<br />
source .bashenv<br />
If you use a zsh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .zshenv<br />
source .zshenv<br />
If you use a csh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .cshenv<br />
source .cshenv<br />
This should cover paths, but you may want to reboot to be sure.<br />
<br />
'''2. Obtain the source code'''<br />
git clone --recursive --branch=development <nowiki>https://github.com/Mudlet/Mudlet.git</nowiki><br />
mkdir Mudlet/build<br />
cd Mudlet/src<br />
<br />
'''3. Make necessary compiling instruction adjustments'''<br />
<br />
Edit mudlet.pro - find these lines in mudlet.pro and make the following changes:<br />
linux {<br />
LIBS += \<br />
-llua5.1 \<br />
-lhunspell<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
We're adding a - between lua and 5.1 and adding -1.7 to hunspell under LIBS so that it becomes this:<br />
linux {<br />
LIBS += \<br />
-llua-5.1 \<br />
-lhunspell-1.7<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
Save and exit.<br />
<br />
'''4. Compile'''<br />
cd ../build<br />
Run this in the build directory:<br />
WITH_FONTS=NO WITH_OWN_QTKEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share qmake-qt5 PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1 LUA_SEARCH_OUT=lua-5.1 ../src/mudlet.pro<br />
An explanation of the qmake arguments -- we're passing these environment variables to mudlet.pro:<br />
WITH_FONTS=NO WITH_OWN_KEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share<br />
Adding build variables to mudlet.pro so that it finds the correct libraries:<br />
PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1<br />
And finally adding a build variable to translations/translated/updateqm.pri so that it uses the correct version of the Lua compiler (Fedora also comes with 5.4) to generate translation statistics.<br />
LUA_SEARCH_OUT=lua-5.1<br />
Once complete, run the following:<br />
<br />
If you have time to kill (About 10 minutes on an Apple M1 Max in Fedora):<br />
make<br />
If you want it done as fast as possible(Less than a minute on an Apple M1 Max in Fedora):<br />
make -j `nproc`<br />
Or if you want something in between, make -j `nproc` tells it to use all available processor cores. If you want to use a specific number instead (ie 2), you can use:<br />
make -j 2<br />
<br />
'''5. Install'''<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''6. Hang onto the cloned git repo '''<br />
If you need to uninstall, you can go back into the /build directory and 'sudo make uninstall'.<br />
<br />
== Compiling on Gentoo ==<br />
An [https://github.com/toaster/gentoo-overlay overlay containing Mudlet is available] for compiling Mudlet on Gentoo.<br />
<br />
== Compiling on Windows ==<br />
<br />
These instructions will get you setup compiling on Windows. <br />
<br />
Need a hand? Join us on the Mudlet [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Download Mudlet source code'''<br />
<br />
# Install [https://desktop.github.com/ Github Desktop].<br />
# Clone ([https://help.github.com/desktop/guides/contributing-to-projects/cloning-a-repository-from-github-to-github-desktop/#platform-windows instructions]) Mudlet's [https://github.com/mudlet/mudlet repository] to your local drive.<br />
{{note}} You must use a location on <code>C:\</code> without any spaces in folder names! <br />
<br />
'''2. Perform a one-time setup'''<br />
<br />
# Right-click on <code>setup-windows-sdk.ps1</code> and select <code>Run with PowerShell</code>. <br />
<br />
This will automatically download all of the requires tools (including Python 2) and libraries, set them up for you, build Mudlet, and launch it! <br />
<br />
{{note}} If this script exits immediately, please [https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/install/installing-windows-powershell?view=powershell-7.1#upgrading-existing-windows-powershell upgrade your PowerShell version] first. You may also need to [https://learn.microsoft.com/de-de/powershell/module/microsoft.powershell.core/about/about_execution_policies?view=powershell-7.4 allow to run scripts from the internet]<br />
<br />
{{note}} Depending on your Internet connection and computer speed, this one-time setup will take 30 minutes or more - so grab a cup of tea or coffee.<br />
<br />
'''3. Watch the magic happen'''<br />
<br />
Here is a video recording of the setup unfolding, compiling, etc. for your comparsion:<br />
<br />
[[File:Start-of-installation.gif|frame|none|Sometimes the output will get stuck and not progress - just press Enter to make it continue. This is a well-known [https://serverfault.com/questions/204150/sometimes-powershell-stops-sending-output-until-i-press-enter-why Powershell bug.]]]<br />
<br />
During the installation, you'll see the Qt installer window pop-up - this is normal:<br />
<br />
[[File:Qt-installer.gif|thumb|none]]<br />
<br />
The Qt installer might ask you about your data collection preferences - answer as you wish and the automated install will continue:<br />
<br />
[[File:Qt-installer-data-collection.png|thumb|none]]<br />
<br />
The installer's final step will be compiling all of the source code, which looks like this:<br />
<br />
[[File:Compiling-step.gif|thumb|none]]<br />
<br />
After it's all done, a Mudlet version ending in "-dev" will launch automatically:<br />
<br />
[[File:Mudlet-launching.gif|frame|none]]<br />
<br />
If something didn't work right, you can check out the verbose log that is available at <code>C:\src\verbose_output.log</code>.<br />
<br />
=== Coding on Mudlet ===<br />
<br />
Open <code>C:\<path to repository>\src\mudlet.pro</code> in Qt Creator, which resides here: <code>C:\Qt\Tools\QtCreator\bin\qtcreator.exe</code>. Then enable Debug and Release builds and hit ''Configure Project'':<br />
<br />
[[File:Selection_173.png|frame|none]]<br />
<br />
Press <code>Ctrl+5</code> and update project settings. Check how many logical processors are available in your system with the Task Manager:<br />
<br />
[[File:Task-manager.png|thumb|none|2 processors are available in this example]]<br />
<br />
And set this amount in Qt Creator:<br />
<br />
[[File:Change Qt Creator to use many cores.gif|frame|none]]<br />
<br />
Hit run:<br />
<br />
[[File:Selection 176.png|frame|none]]<br />
<br />
Click on '''Compile Output''' to see progress on compiling:<br />
<br />
[[File:Selection 177.png|frame|none]]<br />
<br />
When it's all ready, the new Mudlet with your changes will launch. '''You're all done'''!<br />
<br />
=== Contributing changes ===<br />
<br />
Once you're all done with your changes, contribute them to Mudlet using a [https://help.github.com/desktop/guides/contributing-to-projects/creating-a-pull-request/#platform-windows pull request]. Thanks for improving open-source!<br />
<br />
=== Uninstalling ===<br />
To get rid of everything, remove the following folders:<br />
<br />
C:\Libraries<br />
C:\LuaRocks<br />
C:\MinGW<br />
C:\Python27<br />
C:\Qt<br />
C:\src<br />
<br />
== Compiling on Github Codespaces ==<br />
<br />
[https://github.com/features/codespaces/ Github Codespaces] allow you to code and run Mudlet all from the browser - makes it a lot easier to get started. It also allows you to code Mudlet itself from any computer in the world! <br />
<br />
'''1. Create a new codespace'''<br />
<br />
Create a new Codespace by going to https://github.com/Mudlet/Mudlet using Google Chrome or Microsoft Edge (Firefox at the time of the writing doesn't have working copy/paste). There, click the green "Code" button, select the "Codespaces" tab and click "New codespace".<br />
<br />
[[File:New codespace.png|alt=New codespace screenshot|frameless]]<br />
<br />
'''2. Wait for it to load'''<br />
<br />
This will take a while (~5min) so grab a tea:<br />
<br />
[[File:Building Visual Studio Codespace.png|frameless]]<br />
<br />
'''3. Connect to the environment'''<br />
<br />
Go to the <code>Ports</code> section at the bottom and change the Port Privacy of the Open Mudlet port to Public:<br />
<br />
[[File:Port privacy in Github Codespaces.png|900x900px]]<br />
<br />
<br />
Then connect to your online Linux desktop with <code>mudlet</code> as the password by clicking on the web icon. <br />
<br />
[[File:Connect to remote machine.png|frameless]]<br />
<br />
<br />
In case it can't connect, make sure the port privacy is set to <code>Public</code>. If it still can't connect, try 4-5 more times - eventually it'll work.<br />
<br />
<br />
<br />
We chose a retro 90's look here to fit with the whole hacking theme, so if you see this you're good 😉<br />
<br />
[[File:Github_codespaces_desktop.png|alt=|frameless|400x400px]]<br />
<br />
'''4. Build Mudlet'''<br />
<br />
In Codespaces, hit <code>F7</code> and select <code>Let CMake guess...</code><br />
<br />
[[File:CMake configuration.png|none]]<br />
<br />
It will then start building Mudlet automatically. Using the [https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/about-billing-for-codespaces Basic instance] (only kind available in beta) the first-time build will take ~25min, so take a break here - you've made excellent progress. All follow-up compiles after this will be quicker, by the way.<br />
<br />
[[File:Building Mudlet in codespaces.png|none]]<br />
<br />
'''5. Run Mudlet'''<br />
<br />
[[File:Launch Mudlet.png|none]]<br />
<br />
Hit the little play button at the bottom of the screen, and Mudlet will now launch in the remote connection tab. Not working? [https://discord.gg/kuYvMQ9 We can help]. Otherwise, enjoy!<br />
<br />
[[File:Mudlet running remotely.png |500px]]<br />
<br />
Note: When the codespace is unused for a while, it will disconnect. It'll never disconnect while you're actively using it. See [https://github.com/microsoft/vscode-dev-containers/issues/588 Github issue] for details.<br />
<br />
== Developing with Docker ==<br />
<br />
Docker is a system designed for more reproducible and isolated builds. A docker setup exists and has been tested using Pop OS! 20.04 (which is derived from Ubuntu 20.04). First, follow the instructions to install both [https://docs.docker.com/get-docker/ docker] and [https://docs.docker.com/compose/install/ docker-compose].<br />
<br />
Clone the development branch<br />
<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
cd Mudlet/docker<br />
<br />
Make a local copy of the .env.template file:<br />
<br />
cp .env.template .env<br />
<br />
If you wish to customize things like the number of cores to use for building mudlet, feel free to change the corresponding values in the .env file.<br />
<br />
To run Qt-Creator and develop Mudlet, run <code>docker-compose up dev</code>.<br />
<br />
To run Mudlet, run <code>docker-compose up mudlet</code>. Note: At the moment, the mudlet build will not persist settings past container rebuilds.<br />
<br />
== Compiling on Windows 7+ (MSYS2 Alternative)==<br />
<br />
''INCOMPLETE, IN PROGRESS''<br />
<br />
Go to http://www.msys2.org/ to download the 64 bit MSYS2 installer (as of 2020/05/24 32 bit hosts - for '''compiling''' software, but ''not'' for using code built with it have been deprecated, the last installer for that 32-bit systems is held at: http://repo.msys2.org/distrib/i686/msys2-i686-20200517.exe) and follow the installation instructions (Steps 1 to 8 on that page), these instructions assume that "C:\msys64" or "C:\msys32" is used depending on the bitness of the system it is being installed on.<br />
<br />
Install the following packages (using "pacman -S ''packageName''"), the ones with a '''-i686-''' in the middle are the ones for 32-bit (i686) targets and '''-x86_64-''' are the ones for 64-bit targets - it is possible to install both for building Mudlet for target PCs of both bitnesses on a 64-bit host, it is not clear whether the reverse is true with a 32-bit host. These will pull in a number of other required packages as well (the ''--needed'' option prevents the re-installation of packages that have already been installed by MSYS2/Mingw-w64's own setup/installation process) - as some of the packages, e.g. ''base-devel'' are actually ''groups'' you will be requested to select which members of that group are actually required, it is easiest to just go with the default which is to install ALL of the packages in that group!<br />
<br />
: For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-i686-toolchain mingw-w64-i686-qt-creator mingw-w64-i686-qt5-multimedia mingw-w64-i686-libzip mingw-w64-i686-pugixml mingw-w64-i686-lua51 mingw-w64-i686-lua51-lpeg mingw-w64-i686-lua51-lsqlite3 mingw-w64-i686-hunspell mingw-w64-i686-boost mingw-w64-i686-yajl mingw-w64-i686-clang mingw-w64-i686-cmake mingw-w64-i686-SDL unzip<br />
</syntaxhighlight><br />
<br />
: For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-x86_64-toolchain mingw-w64-x86_64-qt-creator mingw-w64-x86_64-qt5-multimedia mingw-w64-x86_64-libzip mingw-w64-x86_64-pugixml mingw-w64-x86_64-lua51 mingw-w64-x86_64-lua51-lpeg mingw-w64-x86_64-lua51-lsqlite3 mingw-w64-x86_64-hunspell mingw-w64-x86_64-boost mingw-w64-x86_64-yajl mingw-w64-x86_64-clang mingw-w64-x86_64-cmake mingw-w64-x86_64-SDL unzip<br />
</syntaxhighlight><br />
<br />
::The ''*-zziplib'' libraries are used by the ''luazip'' luarock {from the Kepler project} but Mudlet will work perfectly well with the alternative ''lua-zip'' {from the brimworks GitHub repository - which also provides the ''lua-yajl'' rock} which does not require this library - although it is possible that it might still be pulled into the system as a dependency of another MSYS2 package.<br />
<br />
:Note that this will install the MSYS2 builds of the Qt Libraries and Creator IDE - ''THE ON/OFF-LINE INSTALLER OF THE QT LIBRARIES AND CREATOR VIA DOWNLOADS FROM QT ARE NOT USEFUL IN THIS SETUP!''<br />
<br />
:{| class="wikitable"<br />
|-<br />
|'''Attention - Luarocks packages problem'''<br />
|-<br />
| Recently the Luarocks project attempted to adopt the MSYS2/Mingw-w64 platform as one it would supported natively and the MSYS2/Mingw-w64 project went and upgraded its luarocks packages to make use of the changes and also on-board other improvements (and the version number increased from ''2.4.4-2'' to ''3.5.0-1'') unfortunately this completely broke them and although the issue has been reported ([https://github.com/msys2/MINGW-packages/issues/9037 MSYS2 Issue 9037]) a fix has not yet materialised. The only way to work around this in the meantime is to download the older package (with '''wget''') and install it manually (with '''pacman -U):<br />
|-<br />
|For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:19:09-- https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97905 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-i686-lua51-luarocks-2.4.4-2- 100%[===========================================================================>] 95.61K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:19:10 (1.43 MB/s) - ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97905/97905]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-i686-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-i686-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|-<br />
|For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:17:32-- https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97935 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-x86_64-lua51-luarocks-2.4.4- 100%[===========================================================================>] 95.64K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:17:32 (1.28 MB/s) - ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97935/97935]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-x86_64-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-x86_64-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|}<br />
<br />
::{| class="wikitable"<br />
|-<br />
|'''Warning for those planning to build ''both'' 32 and 64 bit versions'''<br />
|-<br />
|If one is planning to build ''both'' bitness binaries an additional step is necessary as, by default, the MSYS2/Mingw-w64 ''luarocks'' setup seems to place any ''.lua'' or ''.dll'' modules it builds/installs on a per user (the so-called ''local'' basis) into the same directories with the same names. This is no good for two reasons:<br />
* It is difficult to work out which bitness a particular module is for and whilst 32-bit modules ''might'' work in a 64-bit environment the reverse is definitely not the case<br />
* It confuses the Luarocks package management systems (as effectively there will be two different luarocks systems operated side-by-side)<br />
<br />
This can be worked around by:<br />
* Editing the '''.\etc\luarocks\config-5.1.lua''' for each bitness so that the ''rocks_trees'' table entry for the ''user'' key is changed from this in '''both''' files:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks]] },</syntaxhighlight><br />
to something different for each of them, say, for example, for the the 64-bit one:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks-x64]] },</syntaxhighlight><br />
* Then by specifying the ''rocktree'' name ('''user''') on the command line when '''installing''' or '''building''' a luarock with the ''--tree user'' argument - note that for some inexplicable reason the ''--local'' argument that '''''should''''' do the same thing does not seem to work for these two actions, it is not clear whether this is a MSYS2/Mingw-w64 specific issue or it goes further upstream to Luarocks in general. Thus, in the next step it will be necessary to change from using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --local rockname<br />
</syntaxhighlight><br />
to, for the example given:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --tree user rockname<br />
</syntaxhighlight><br />
where ''user'' is the literal string "user" to match the Lua table key in the rock_trees and not, in this case, a representation of the user-name/account of the person performing the action.<br />
|}<br />
<br />
From the Windows ''Start menu'' start a shell appropriate for the target with the bitness to be built for i.e. '''"MSYS2 Mingw 32-Bit"''' or '''"MSYS2 Mingw 64-Bit"'''. This will likely position the current directory to the root directory of the MSYS2 environment, the text about the prompt line (the one with the "$") will contain three different bits of colored text '''username@computername'''; one of '''MSYS2'''/'''MINGW32'''/'''MINGW''' depending on the type of shell you currently in use and '''/''' representing the root directory (which will actually be the directory MSYS2 was installed to, for example on the author's system this is "C:/msys64"). Change to the home directory in MYSY by entering "cd" on its own with no argument (it will show up as '''~''' and it would work out to be, for '''user''' to be '''c:/msys64/home/user''' or '''c:/msys32/home/user''' (if both bitnessess are to be built it will be necessary to repeat the following step twice, one for each and also observe the steps in the above warning) install the following luarocks:<br />
<br />
:{| class="wikitable sortable"<br />
|-<br />
! rockname<br />
|-<br />
| lrexlib-pcre<br />
|-<br />
| lua-yajl<br />
|-<br />
| luafilesystem<br />
|-<br />
| luasql-sqlite3<br />
|-<br />
| luautf8<br />
|-<br />
| luazip or lua-zip<br />
|}<br />
by using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install [--local] rockname<br />
</syntaxhighlight><br />
The ''--local'' argument is an optional one that causes the luarock and the lua module to be installed on a per-user basis rather than on a system wide one, this may be important if the PC is used by multiple users and more than one of them uses Lua in any form.<br />
<br />
Now create somewhere to work on the Mudlet source, assuming that other software coding with other pieces of software will be done, create a sub-directory in the home directory, and then make one just for Mudlet under that:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ mkdir ./src<br />
<br />
MINGW64 user@computer ~<br />
$ mkdir ./src/mudlet<br />
</syntaxhighlight><br />
<br />
Change to that directory and get the source code:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ cd ./src/mudlet<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git clone git://github.com/Mudlet/Mudlet.git .<br />
</syntaxhighlight><br />
<br />
If you are planning to contribute to the Mudlet code you will want to visit Github and create your own GitHub repository, you can then push commits (changes to the code) to there and raise a Pull Request for a Mudlet Maker to drag the changes over to the above repository. You will want to add your repository and perhaps those of some other contributors so you can track what they are doing and see/try/experiment with their PRs before they get merged. Therefore you will want to add some other repositories into the mix. The names you use to identify those other repositories will show up in any utility that works with the repository you have just created in the above "clone" operation and can be anything you like but it makes sense to have clear names. So to add "myName", and those of the leading active contributors to the Mudlet codebase you will use:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Mine https://github.com/myName/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Vadim https://github.com/vadi2/Mudlet.git <br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add SlySven https://github.com/SlySven/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Kebap https://github.com/Kebap/Mudlet.git<br />
</syntaxhighlight><br />
<br />
Now obtain ''all'' the versions of the code with:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git fetch --all<br />
</syntaxhighlight><br />
<br />
This will produce a lot of lines of output the first time and it might take a little while on a slow connection...<br />
<br />
{Section missing - it turns out that the default GUI git tools that the author of this section would normally use: "gitk" and "git gui" have some problems in the versions currently supplied from the MSYS2 system - and it was necessary to import them from the set that the Git4Win have patched - see https://github.com/git-for-windows/git/wiki/Install-inside-MSYS2-proper }<br />
<br />
Some modifications to the qmake/cmake project files are needed and these are now supported in the main ''development'' branch in the upstream {the Mudlet organisation's own GitHub repository} which requires that there is an environmental variable '''WITH_MAIN_BUILD_SYSTEM''' and it is set to the (case-insensitive) value '''NO''':<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export WITH_MAIN_BUILD_SYSTEM=NO<br />
</syntaxhighlight><br />
<br />
Also the '''MINGW_BASE_DIR''' environmental variable will need to be set to the root directory for the MINGW-W64 installation for the appropriate bitness of the target to be made. For building on a 64-Bit Host {the PC that is ''compiling'' the code} to make a 64-Bit application this will likely be '''C:/msys64/mingw64''' and for a 32-Bit application it will probably be '''C:/msys64/ming32'''.<br />
: E.g. <syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw64 # To build a 64-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
: Or: <syntaxhighlight lang="shell"><br />
MINGW32 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw32 # To build a 32-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
Now checkout a branch {ideally, if working on solving a new issue, or adding a feature or resolving a bug, one should create a new branch that is a copy of the current, upstream ''development'' branch} and then work on it with Qt Creator:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ qtcreator &<br />
</syntaxhighlight><br />
<br />
Load in the '''mudlet.pro''' ''qmake'' project file in the '''src''' subdirectory (e.g. for this example: '''c:/msys64/home/user/src/mudlet/src/mudlet.pro''') and get hacking...<br />
<br />
= Setting up IDEs =<br />
== CLion ==<br />
=== Qt not detected ===<br />
If you'd like to use CLion and it is giving the following error:<br />
<br />
<nowiki><br />
By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has<br />
asked CMake to find a package configuration file provided by "Qt5Core", but<br />
CMake did not find one.<br />
<br />
...<br />
</nowiki><br />
<br />
You can fix this by setting <code>-DCMAKE_PREFIX_PATH=<your Qt + version + compiler location></code>. For example: <code>-DCMAKE_PREFIX_PATH=/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code> [[File:CLion CMake settings - finidng Qt.png|700px|none]]<br />
<br />
=== CLion setup on Windows ===<br />
After running <code>setup-windows-sdk.ps1</code> make sure to set Cmake options to:<br />
-DCMAKE_PREFIX_PATH=C:\Qt\Tools\mingw730_32;C:\Qt\5.14.2\mingw73_32 -DBoost_INCLUDE_DIR=C:\Libraries\boost_1_77_0<br />
''Directories might vary slightly, when different Qt, Boost or MinGW version will be used.''<br />
<br />
[[File:Clion Settings - Cmake.png|frameless|700x700px]]<br />
<br />
<br />
<br />
You will need 32 bit version of MinGW. Set it in the <code>Toolset</code> field to:<br />
C:\Qt\Tools\mingw730_32<br />
<br />
''Directory may be slightly different if MinGW version used will change.''<br />
<br />
[[File:Toolchain.png|frameless|700x700px]]<br />
<br />
=== Clang Tidy ===<br />
Ensure that CLion is set to run the project's [https://www.jetbrains.com/help/clion/clang-tidy-checks-support.html#paticularcheck .clang-tidy checks] with the <code>Prefer .clang-tidy files over IDE settings</code> option:<br />
<br />
[[File:Clang Tidy CLIon.png|700px|none]]<br />
<br />
This helps us catch any issues just a bit earlier.<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in CLion, adjust the CMake settings:<br />
<br />
[[File:Clion_cmake_settings.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
=== Clang Format ===<br />
Ensure that [https://www.jetbrains.com/help/clion/clangformat-as-alternative-formatter.html#clion-support CLion is set to use] the <code>.clang-format</code> formatting style:<br />
<br />
[[File:Clang-format CLion.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
== Visual Studio Code ==<br />
<br />
To set the path in Visual Studio Code, open settings, search for <code>cmake environment</code> and set the <code>CMAKE_PREFIX_PATH</code> to your path, such as <code>/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code>:<br />
<br />
[[File:CMake path in Visual Studio Code.png|none]]<br />
<br />
===Clang Tidy===<br />
clang-tidy catches common programming issues, run it by selecting 'Analysis' from the command palette (Ctrl+Shift+P by default):<br />
<br />
[[File:Clang-tidy in vscode.png|none]]<br />
<br />
It is also possible [https://devblogs.microsoft.com/cppblog/visual-studio-code-c-december-2021-update-clang-tidy/ check status of analysis and cancel if needed].<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in VSCode, set the <code>cmake.configureSettings</code> variable:<br />
<br />
[[File:Cmake.configureSettings option in vscode.png|frameless|890x890px]]<br />
<br />
[[File:Choosing which sanitizers in vscode to use.png|frameless|891x891px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
== Qt Creator==<br />
===Clang Tidy and Clazy===<br />
<br />
Configure Mudlet-specific checks for [https://clang.llvm.org/extra/clang-tidy/ clang-tidy] and [https://github.com/KDE/clazy clazy] tools help catch any issues early on. See [https://doc.qt.io/qtcreator/creator-clang-tools.html Qt Creator's instructions] for setting this up - clang-tidy can use the <code>.clang-tidy</code> file that's available at the root of the repository, and for clazy enable <code>level0</code> and <code>level1</code> checks.<br />
<br />
[[File:Clang tidy configuration.png|frame|none]]<br />
[[File:Clazy configuration.png|frame|none]]<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in Qt creator, head to <code>Projects</code> - <code>Build</code>: <br />
<br />
[[File:Sanitisers in qt creator.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
==Clang Format==<br />
Ensure that Qt Creator is set to use the <code>.clang-format</code> formatting style in the C++ settings. Turn on <code>Format instead of indenting</code> for <code>Ctrl+I</code> to format code, and ensure <code>Override Clang Format configuration file</code> is disabled:<br />
<br />
[[File:Qt Creator clang format.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
<br />
=Building with multiple versions of Lua=<br />
Mudlet uses Lua 5.1 only, so if you are compiling on a system that also has later versions installed, you might get the following error: <code>‘LUA_GLOBALSINDEX’ was not declared in this scope</code>.<br />
<br />
To fix this, pass the path to Lua headers explicitly. For CMake: <code>-DLUA_INCLUDE_DIR=/usr/include/lua5.1</code> (adjust as needed).</div>Kebaphttps://wiki.mudlet.org/index.php?title=Compiling_Mudlet&diff=20637Compiling Mudlet2023-12-21T09:50:03Z<p>Kebap: /* Compiling on Windows */ Introduction</p>
<hr />
<div>{{TOC right}}<br />
<br />
If you just want to use Mudlet, you can skip these steps, and use one of the already ready (pre-compiled) installers [https://www.mudlet.org/download ready for download].<br />
<br />
Otherwise, hop in for new adventure! <br />
<br />
[[File:Easy Mudlet code understanding.png|frame|none]]<br />
<br />
= Key contributing information =<br />
<br />
Clang format is used to automatically format code submissions using the [https://github.com/Mudlet/Mudlet/blob/development/src/.clang-format src/.clang-format] style. [http://doc.qt.io/qtcreator/creator-beautifier.html See here] how to enable clang-format with Qt Creator - and make sure to specify the 'File' option for the configuration style.<br />
<br />
Branches:<br />
<br />
'''development''' is the development branch where new features can go.<br />
<br />
Workflow:<br />
<br />
Fork and submit a PR with your changes ([https://guides.github.com/activities/forking/ Github tutorial]).<br />
<br />
Here is a list of package versions delivered with different Linux distros. You may want to upgrade these: <br />
https://repology.org/project/mudlet/versions<br />
<br />
= Lua & Luarocks =<br />
<br />
Mudlet includes a [https://en.wikipedia.org/wiki/Lua_(programming_language) Lua] (version 5.1) scripting system for the end-user, which you, as a reader of this Wiki, may already be aware of! If not, you might wish to (after you have got your hands on a working Mudlet) take a look at [https://wiki.mudlet.org/w/Manual:Lua_Functions Mudlet Lua API] as that is the recommended place to find out the details of all the functions that Mudlet provides on top of the core Lua functionality.<br />
<br />
Some of that ability comes from extra code that is not built-in to Lua but is in the form of external modules either in the form of script (text) files written in the Lua language itself or binary (library) files compiled from (usually but not exclusively [https://en.wikipedia.org/wiki/C_(programming_language) 'C']) source code. In order to have that functionality Mudlet makes use of several of these modules which can most readily (if not already available as "packages" for a particular Operating System) be obtained as '''rocks''' from the public [https://en.wikipedia.org/wiki/LuaRocks Luarocks] collection. Such a rock actually consists of a ''rockspec'' file that gives instructions to the Luarocks tool how to obtains the (source) code, compile it on any supported OS into the form that a Lua interpreter (including the one included in '''''each''''' running Mudlet ''profile'') can use, and where and what it will be placed and called when it has been made. After that it should be available to Lua via the ''require'' command.<br />
<br />
Anyone compiling Mudlet for themselves will find it desirable to ensure they have a usable Luarocks installation and have the ''lua-yajl'' module installed before commencing to compile Mudlet itself; this is because a Lua (version 5.1) interpreter and that module are used within the build process of making the executable code that is the Mudlet application.<br />
<br />
= Compiling =<br />
<br />
== Compiling on Ubuntu ==<br />
<br />
These instructions will get you setup compiling on Ubuntu. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
===Ubuntu 22.04===<br />
Following instructions will work on Ubuntu 22.04 as well as all its flavours and derivatives (such as KDE Neon, for example)<br />
Important thing is to have ''Universe'' repository enabled in your package manager. (on Ubuntu you will have all the repositories that you need already enabled by default.)<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo apt install ubuntu-restricted-extras qtcreator build-essential git zlib1g-dev libhunspell-dev \<br />
libpcre3-dev libzip-dev libboost-dev libboost-all-dev libyajl-dev libpulse-dev libpugixml-dev \<br />
liblua5.1-0-dev lua-filesystem lua-zip lua-sql-sqlite3 luarocks ccache lua5.1 \<br />
libglu1-mesa-dev mesa-common-dev libglib2.0-dev libgstreamer1.0-dev libqt5opengl5-dev \<br />
qtmultimedia5-dev qttools5-dev qt5keychain-dev libsecret-1-dev \<br />
libqt5texttospeech5-dev qtspeech5-flite-plugin qtspeech5-speechd-plugin \<br />
qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo luarocks install lcf<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
sudo luarocks install lrexlib-pcre<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
4. '''installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
5. '''optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo apt install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.<br />
Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybidings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
===Other Ubuntu Versions===<br />
<br />
Most of the installation instructions for 22.04 should work for older versions as well. Of note is the required version of Qt, which is 5.14. If your used version of Ubuntu only supplies older<br />
Qt versions, have a look at [https://launchpad.net/~beineri Stephan Binners PPAs], which supplies a whole range of packages for different Ubuntu versions. Be sure to read the installation and<br />
usage instructions as Qt is installed to /opt and requires sourcing a script to set up.<br />
<br />
== Compiling on Chrome OS ==<br />
<br />
These instructions will get you setup compiling on Chrome OS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Install dependencies'''<br />
<br />
sudo apt install git build-essential qt5-default qtmultimedia5-dev qttools5-dev \<br />
lua5.1 liblua5.1-0-dev libpcre3-dev libboost-dev zlib1g-dev cmake \<br />
libhunspell-dev lua-rex-pcre lua-sql-sqlite3 lua-filesystem lua-zip libyajl-dev \<br />
libzip-dev libglu1-mesa-dev ccache libpugixml-dev mesa-common-dev qtcreator \<br />
libpulse-dev libglib2.0-dev luarocks libboost-all-dev libsecret-1-dev \<br />
ninja-build libsecret-1-dev<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''3. Get Mudlet source'''<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''4. Create a build directory'''<br />
<br />
cd mudlet<br />
mkdir build && cd build<br />
<br />
'''5. Run the following command '''<br />
<br />
cmake .. -G Ninja<br />
<br />
'''then:'''<br />
<br />
ninja<br />
<br />
'''5. Start the application you have just compiled - enjoy'''<br />
<br />
src/mudlet<br />
{{Note}}Did <code>ninja</code> fail with <code>c++: fatal error: Killed signal terminated program cclplus</code>? Try again with <code>ninja -j 2</code><br />
<br />
== Compiling on macOS ==<br />
<br />
These instructions will get you setup compiling on macOS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums] otherwise.<br />
<br />
<br />
'''1. Install prerequisites'''<br />
<br />
Install [https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12 XCode], command line tools for XCode, and [http://brew.sh HomeBrew].<br />
<br />
Once everything is installed, do:<br />
<br />
brew doctor<br />
brew update<br />
brew install git<br />
<br />
'''2. Get Mudlet source'''<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git <br />
<br />
'''3. Go to the parent of the mudlet "src" folder and create (if necessary) a build subdirectory (this is so that we can build out of source which keeps the source code clean)'''<br />
cd Mudlet && mkdir build<br />
<br />
'''3. Setup your environment'''<br />
./CI/travis.osx.before_install.sh<br />
./CI/travis.osx.install.sh<br />
<br />
luarocks config lua_version 5.1<br />
eval `luarocks path --lua-version=5.1`<br />
For the following, one may have to add <code>''_DIR="/opt/homebrew/"''</code> such as <code>PCRE_DIR="/opt/homebrew/"</code> or <code>ZIP_DIR="/opt/homebrew/"</code> if the installation could not find header files.<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lrexlib-pcre PCRE_DIR=`brew --prefix pcre`<br />
brew install sqlite<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luasql-sqlite3 SQLITE_DIR=`brew --prefix sqlite` <br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luautf8<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-yajl YAJL_LIBDIR=`brew --prefix yajl`<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luafilesystem<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-zip ZIP_DIR=`brew --prefix libzip`<br />
<br />
brew install p7zip<br />
export BOOST_ROOT="$(pwd)/../Mudlet/3rdparty/boost"<br />
export BOOST_URL="https://sourceforge.net/projects/boost/files/boost/1.83.0/boost_1_83_0.tar.bz2/download"<br />
mkdir -p $BOOST_ROOT<br />
curl --progress-bar --location --output $BOOST_ROOT/download.tar.bz2 $BOOST_URL<br />
7z -o$BOOST_ROOT x $BOOST_ROOT/download.tar.bz2 -y -bd<br />
7z -o$BOOST_ROOT x $BOOST_ROOT/download.tar -y -bd<br />
cd $BOOST_ROOT && cp -r boost_*/* .<br />
rm -rf boost_*/* download.tar.bz2 download.tar<br />
OK to answer yes to delete files if prompted for the <code>rm</code> command above.<br />
<br />
'''4. Run the following commands'''<br />
<br />
cd ../../build<br />
cmake ../../Mudlet -DCMAKE_PREFIX_PATH=`brew --prefix qt5`<br />
make -j `sysctl -n hw.ncpu`<br />
<br />
<br />
'''5. Enjoy'''<br />
<br />
The mudlet.app is now available in <code>src/</code> for launching:<br />
<br />
open src/Mudlet.app<br />
<br />
'''6. Qt Creator setup'''<br />
<br />
No Lua installation is found, despite it existing on your system? Launch Qt Creator by doing <code>open /Applications/Qt Creator.app</code> (location depends on how you installed it).<br />
<br />
Receiving a <code>No rule to make target ... libQt5UiTools_debug.a</code> error? A workaround is to [https://bugreports.qt.io/browse/QTBUG-81251?focusedCommentId=538705&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-538705 symlink a file].<br />
<br />
Mudlet in Qt Creator is not launching due to <code>dyld: Symbol not found: __cg_jpeg_resync_to_restart</code>? See [https://stackoverflow.com/a/44851430/72944 here] for a workaround.<br />
<br />
====== 7. Troubleshooting ======<br />
If you exhaust all efforts to get YAJL to compile on your local system with homebrew, [https://github.com/lloyd/yajl/ clone from the YAJL repository] then <code>./configure && sudo make install</code>.<br />
<br />
== Compiling on Debian 'Sid' ==<br />
<br />
'''1. Install required packages from main repo.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev<br />
<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Grab latest Mudlet source.'''<br />
<br />
mkdir ~/projects && cd ~/projects && git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
cd ~/projects/mudlet/src<br />
<br />
qmake<br />
<br />
make<br />
<br />
sudo make install<br />
<br />
== Compiling on Debian 11 'Bullseye' ==<br />
<br />
'''1. Install required packages.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev \<br />
qttools5-dev luarocks ccache libpugixml-dev libqt5texttospeech5-dev qtspeech5-flite-plugin \<br />
qtspeech5-speechd-plugin libqt5opengl5-dev ninja-build cmake libsecret-1-dev<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Get Mudlet source.'''<br />
<br />
mkdir ~/source && cd ~/source<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git<br />
<br />
Note: the line above will check out `development` branch source code, and this might not always be stable. You can check out the latest release source code using this command:<br />
<br />
git clone --recursive --branch main https://github.com/Mudlet/Mudlet.git<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
mkdir ~/source/Mudlet/build && cd ~/source/Mudlet/build<br />
<br />
qmake ../src/mudlet.pro<br />
<br />
make -j `nproc`<br />
<br />
sudo make install<br />
<br />
After these steps you can run Mudlet by typing:<br />
<br />
mudlet<br />
<br />
'''4. (Optional) Discord library'''<br />
<br />
If you get the following error;<br />
<br />
Could not find Discord library - searched in:<br />
<br />
you need to specify the discord library in your build. Run the following, changing the path where necessary;<br />
<br />
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/mudlet-dev/Mudlet/3rdparty/discord/rpc/lib/<br />
<br />
and recompile. You should see<br />
<br />
Discord integration loaded. Using functions from: "libdiscord-rpc.so"<br />
<br />
== Compiling on Raspberry Pi OS ==<br />
<br />
These instructions will get you compiling and running Mudlet on Raspberry Pi OS (Buster). Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
''' 1.a Install apt dependencies '''<br />
<br />
sudo apt-get update<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-graph-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev cmake<br />
<br />
<br />
[[File:Apt-get-install-y-n.png|center|thumb|installing apt dependencies]]<br />
<br />
''' 1.b Install luarocks dependencies '''<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl YAJL_LIBDIR=`find /usr -name "libyajl.so" -printf '%h\n'` YAJL_INCDIR=/usr/include<br />
<br />
<br />
[[File:After-luarocks-dependencies.png|center|thumb|after luarocks dependencies]]<br />
<br />
''' 2. Get Mudlet source '''<br />
<br />
mkdir ~/source && cd ~/source <br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
<br />
[[File:After-get-mudlet-source.png|center|thumb|After cloning]]<br />
<br />
''' 3. Create a build directory '''<br />
<br />
cd Mudlet && mkdir build && cd build<br />
<br />
''' 4. Run the following commands to build '''<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake ../src/mudlet.pro<br />
<br />
:If you get a response along the lines of:<br />
<br />
qmake: could not find a Qt installation of ''<br />
<br />
:then you likely have ''qtchooser'' present in your system that allows for both Qt4 and Qt5 (or more than one Qt5 version) and it modifiers qmake and some other Qt development programs to take an additional argument to specify which version to use. In that case you should use:<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake -qt=qt5 ../src/mudlet.pro<br />
<br />
[[File:After-qmake.png|center|thumb|After qmake]]<br />
<br />
''' THEN: '''<br />
:For the fastest compile time while still being able to use the system at all (~35min on a RPi4 with 4GB of ram)<br />
make -j $(expr `nproc` - 1)<br />
<br />
''' OR: '''<br />
<br />
:Use this if you have an older Raspberry Pi. Be prepared for it to take a while (over an hour) - ''it is not recommended to try to more than one compilation task at a time on the older systems with the '''-j''' option as they will only have a system memory with enough space for one of some of those tasks'':<br />
make<br />
<br />
[[File:Success.png|center|thumb|Success!]]<br />
<br />
''' 4. Install the application you have just compiled '''<br />
<br />
sudo make install<br />
<br />
[[File:Installed.png|center|thumb|Installed now]]<br />
<br />
''' 5. Enjoy! '''<br />
<br />
# mudlet is in the path, can just run it<br />
mudlet<br />
<br />
== Compiling on Arch Linux ==<br />
<br />
===AUR Install and Compile===<br />
Mudlet is available in the [https://aur.archlinux.org Arch User Repository].<br />
(If the AUR has become unmaintained/orphaned, then skip below to [https://wiki.mudlet.org/w/Compiling_Mudlet#Manual_Install_and_Compile Manual install].)<br />
<br />
To install it use your favourite AUR helper (helper tool will automatically resove dependancies); example using ''yay'' :<br />
yay -S mudlet<br />
<br />
For more info on this process, visit [https://wiki.archlinux.org/index.php/Arch_User_Repository Arch User Repository - ArchWiki].<br />
<br />
''Note: For the most recent development version of Mudlet, replace 'mudlet' with 'mudlet-git' in the above commands and proceed as described.''<br />
<br />
''Built in fonts have been disabled, but are available in packages listed as optional dependancies.''<br />
<br />
''Discord support in Mudlet depends on an external library provided by discord-rpc-api, which is also available in AUR, choose whichever variant suits you best.''<br />
<br />
===Manual Install and Compile===<br />
These instructions will get you setup compiling on Arch. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo pacman -S --needed cmake qt5-multimedia hunspell libzip lua51-filesystem qt5-gamepad lua51-luautf8 pugixml \<br />
ttf-font qtkeychain-qt5 boost qt5-tools ttf-bitstream-vera ttf-ubuntu-font-family noto-fonts-emoji glu luarocks<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo lua5.1 /usr/bin/luarocks install lcf<br />
sudo lua5.1 /usr/bin/luarocks install luautf8<br />
sudo lua5.1 /usr/bin/luarocks install lua-yajl<br />
sudo lua5.1 /usr/bin/luarocks install lrexlib-pcre<br />
sudo lua5.1 /usr/bin/luarocks install luasql-sqlite3<br />
sudo lua5.1 /usr/bin/luarocks install lua-zip<br />
<br />
There is an optional dependency for discord integration:<br />
git clone https://github.com/discord/discord-rpc<br />
cd discord-rpc<br />
mkdir build<br />
cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=/usr<br />
sudo cmake --build . --config Release --target install<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
'''4. installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''5. optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo pacman -S install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.↵Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybindings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
== Compiling on Fedora (aarch64) ==<br />
<br />
'''1. Install dependencies'''<br />
sudo dnf groupinstall "Development Tools" "Development Libraries"<br />
<br />
sudo dnf install compat-lua compat-lua-devel compat-lua-libs hunspell-devel lua5.1-filesystem luarocks pugixml-devel qtkeychain-qt5-devel bitstream-vera-fonts-all ccache qt-creator qt5-qtmultimedia-devel qt5-qtgamepad-devel yajl-devel qtchooser qt5-qttools-devel qt5-qttools-static zziplib-devel pcre-devel libzip-devel sqlite-devel<br />
<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luazip<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luasql-sqlite3<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lcf<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luautf8<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lua-yajl<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lrexlib-pcre<br />
In your user's home directory:<br />
<br />
If you use a bash shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .bashenv<br />
source .bashenv<br />
If you use a zsh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .zshenv<br />
source .zshenv<br />
If you use a csh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .cshenv<br />
source .cshenv<br />
This should cover paths, but you may want to reboot to be sure.<br />
<br />
'''2. Obtain the source code'''<br />
git clone --recursive --branch=development <nowiki>https://github.com/Mudlet/Mudlet.git</nowiki><br />
mkdir Mudlet/build<br />
cd Mudlet/src<br />
<br />
'''3. Make necessary compiling instruction adjustments'''<br />
<br />
Edit mudlet.pro - find these lines in mudlet.pro and make the following changes:<br />
linux {<br />
LIBS += \<br />
-llua5.1 \<br />
-lhunspell<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
We're adding a - between lua and 5.1 and adding -1.7 to hunspell under LIBS so that it becomes this:<br />
linux {<br />
LIBS += \<br />
-llua-5.1 \<br />
-lhunspell-1.7<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
Save and exit.<br />
<br />
'''4. Compile'''<br />
cd ../build<br />
Run this in the build directory:<br />
WITH_FONTS=NO WITH_OWN_QTKEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share qmake-qt5 PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1 LUA_SEARCH_OUT=lua-5.1 ../src/mudlet.pro<br />
An explanation of the qmake arguments -- we're passing these environment variables to mudlet.pro:<br />
WITH_FONTS=NO WITH_OWN_KEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share<br />
Adding build variables to mudlet.pro so that it finds the correct libraries:<br />
PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1<br />
And finally adding a build variable to translations/translated/updateqm.pri so that it uses the correct version of the Lua compiler (Fedora also comes with 5.4) to generate translation statistics.<br />
LUA_SEARCH_OUT=lua-5.1<br />
Once complete, run the following:<br />
<br />
If you have time to kill (About 10 minutes on an Apple M1 Max in Fedora):<br />
make<br />
If you want it done as fast as possible(Less than a minute on an Apple M1 Max in Fedora):<br />
make -j `nproc`<br />
Or if you want something in between, make -j `nproc` tells it to use all available processor cores. If you want to use a specific number instead (ie 2), you can use:<br />
make -j 2<br />
<br />
'''5. Install'''<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''6. Hang onto the cloned git repo '''<br />
If you need to uninstall, you can go back into the /build directory and 'sudo make uninstall'.<br />
<br />
== Compiling on Gentoo ==<br />
An [https://github.com/toaster/gentoo-overlay overlay containing Mudlet is available] for compiling Mudlet on Gentoo.<br />
<br />
== Compiling on Windows ==<br />
<br />
These instructions will get you setup compiling on Windows. <br />
<br />
Need a hand? Join us on the Mudlet [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Download Mudlet source code'''<br />
<br />
# Install [https://desktop.github.com/ Github Desktop].<br />
# Clone ([https://help.github.com/desktop/guides/contributing-to-projects/cloning-a-repository-from-github-to-github-desktop/#platform-windows instructions]) Mudlet's [https://github.com/mudlet/mudlet repository] to your local drive.<br />
{{note}} You must use a location on <code>C:\</code> without any spaces in folder names! <br />
<br />
'''2. Perform a one-time setup'''<br />
<br />
# Right-click on <code>setup-windows-sdk.ps1</code> and select <code>Run with PowerShell</code>. <br />
<br />
This will automatically download all of the requires tools (including Python 2) and libraries, set them up for you, build Mudlet, and launch it! <br />
<br />
{{note}} If this script exits immediately, please [https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/install/installing-windows-powershell?view=powershell-7.1#upgrading-existing-windows-powershell upgrade your PowerShell version] first.<br />
<br />
{{note}} Depending on your Internet connection and computer speed, this one-time setup will take 30 minutes or more - so grab a cup of tea or coffee.<br />
<br />
'''3. Watch the magic happen'''<br />
<br />
Here is a video recording of the setup unfolding, compiling, etc. for your comparsion:<br />
<br />
[[File:Start-of-installation.gif|frame|none|Sometimes the output will get stuck and not progress - just press Enter to make it continue. This is a well-known [https://serverfault.com/questions/204150/sometimes-powershell-stops-sending-output-until-i-press-enter-why Powershell bug.]]]<br />
<br />
During the installation, you'll see the Qt installer window pop-up - this is normal:<br />
<br />
[[File:Qt-installer.gif|thumb|none]]<br />
<br />
The Qt installer might ask you about your data collection preferences - answer as you wish and the automated install will continue:<br />
<br />
[[File:Qt-installer-data-collection.png|thumb|none]]<br />
<br />
The installer's final step will be compiling all of the source code, which looks like this:<br />
<br />
[[File:Compiling-step.gif|thumb|none]]<br />
<br />
After it's all done, a Mudlet version ending in "-dev" will launch automatically:<br />
<br />
[[File:Mudlet-launching.gif|frame|none]]<br />
<br />
If something didn't work right, you can check out the verbose log that is available at <code>C:\src\verbose_output.log</code>.<br />
<br />
=== Coding on Mudlet ===<br />
<br />
Open <code>C:\<path to repository>\src\mudlet.pro</code> in Qt Creator, which resides here: <code>C:\Qt\Tools\QtCreator\bin\qtcreator.exe</code>. Then enable Debug and Release builds and hit ''Configure Project'':<br />
<br />
[[File:Selection_173.png|frame|none]]<br />
<br />
Press <code>Ctrl+5</code> and update project settings. Check how many logical processors are available in your system with the Task Manager:<br />
<br />
[[File:Task-manager.png|thumb|none|2 processors are available in this example]]<br />
<br />
And set this amount in Qt Creator:<br />
<br />
[[File:Change Qt Creator to use many cores.gif|frame|none]]<br />
<br />
Hit run:<br />
<br />
[[File:Selection 176.png|frame|none]]<br />
<br />
Click on '''Compile Output''' to see progress on compiling:<br />
<br />
[[File:Selection 177.png|frame|none]]<br />
<br />
When it's all ready, the new Mudlet with your changes will launch. '''You're all done'''!<br />
<br />
=== Contributing changes ===<br />
<br />
Once you're all done with your changes, contribute them to Mudlet using a [https://help.github.com/desktop/guides/contributing-to-projects/creating-a-pull-request/#platform-windows pull request]. Thanks for improving open-source!<br />
<br />
=== Uninstalling ===<br />
To get rid of everything, remove the following folders:<br />
<br />
C:\Libraries<br />
C:\LuaRocks<br />
C:\MinGW<br />
C:\Python27<br />
C:\Qt<br />
C:\src<br />
<br />
== Compiling on Github Codespaces ==<br />
<br />
[https://github.com/features/codespaces/ Github Codespaces] allow you to code and run Mudlet all from the browser - makes it a lot easier to get started. It also allows you to code Mudlet itself from any computer in the world! <br />
<br />
'''1. Create a new codespace'''<br />
<br />
Create a new Codespace by going to https://github.com/Mudlet/Mudlet using Google Chrome or Microsoft Edge (Firefox at the time of the writing doesn't have working copy/paste). There, click the green "Code" button, select the "Codespaces" tab and click "New codespace".<br />
<br />
[[File:New codespace.png|alt=New codespace screenshot|frameless]]<br />
<br />
'''2. Wait for it to load'''<br />
<br />
This will take a while (~5min) so grab a tea:<br />
<br />
[[File:Building Visual Studio Codespace.png|frameless]]<br />
<br />
'''3. Connect to the environment'''<br />
<br />
Go to the <code>Ports</code> section at the bottom and change the Port Privacy of the Open Mudlet port to Public:<br />
<br />
[[File:Port privacy in Github Codespaces.png|900x900px]]<br />
<br />
<br />
Then connect to your online Linux desktop with <code>mudlet</code> as the password by clicking on the web icon. <br />
<br />
[[File:Connect to remote machine.png|frameless]]<br />
<br />
<br />
In case it can't connect, make sure the port privacy is set to <code>Public</code>. If it still can't connect, try 4-5 more times - eventually it'll work.<br />
<br />
<br />
<br />
We chose a retro 90's look here to fit with the whole hacking theme, so if you see this you're good 😉<br />
<br />
[[File:Github_codespaces_desktop.png|alt=|frameless|400x400px]]<br />
<br />
'''4. Build Mudlet'''<br />
<br />
In Codespaces, hit <code>F7</code> and select <code>Let CMake guess...</code><br />
<br />
[[File:CMake configuration.png|none]]<br />
<br />
It will then start building Mudlet automatically. Using the [https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/about-billing-for-codespaces Basic instance] (only kind available in beta) the first-time build will take ~25min, so take a break here - you've made excellent progress. All follow-up compiles after this will be quicker, by the way.<br />
<br />
[[File:Building Mudlet in codespaces.png|none]]<br />
<br />
'''5. Run Mudlet'''<br />
<br />
[[File:Launch Mudlet.png|none]]<br />
<br />
Hit the little play button at the bottom of the screen, and Mudlet will now launch in the remote connection tab. Not working? [https://discord.gg/kuYvMQ9 We can help]. Otherwise, enjoy!<br />
<br />
[[File:Mudlet running remotely.png |500px]]<br />
<br />
Note: When the codespace is unused for a while, it will disconnect. It'll never disconnect while you're actively using it. See [https://github.com/microsoft/vscode-dev-containers/issues/588 Github issue] for details.<br />
<br />
== Developing with Docker ==<br />
<br />
Docker is a system designed for more reproducible and isolated builds. A docker setup exists and has been tested using Pop OS! 20.04 (which is derived from Ubuntu 20.04). First, follow the instructions to install both [https://docs.docker.com/get-docker/ docker] and [https://docs.docker.com/compose/install/ docker-compose].<br />
<br />
Clone the development branch<br />
<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
cd Mudlet/docker<br />
<br />
Make a local copy of the .env.template file:<br />
<br />
cp .env.template .env<br />
<br />
If you wish to customize things like the number of cores to use for building mudlet, feel free to change the corresponding values in the .env file.<br />
<br />
To run Qt-Creator and develop Mudlet, run <code>docker-compose up dev</code>.<br />
<br />
To run Mudlet, run <code>docker-compose up mudlet</code>. Note: At the moment, the mudlet build will not persist settings past container rebuilds.<br />
<br />
== Compiling on Windows 7+ (MSYS2 Alternative)==<br />
<br />
''INCOMPLETE, IN PROGRESS''<br />
<br />
Go to http://www.msys2.org/ to download the 64 bit MSYS2 installer (as of 2020/05/24 32 bit hosts - for '''compiling''' software, but ''not'' for using code built with it have been deprecated, the last installer for that 32-bit systems is held at: http://repo.msys2.org/distrib/i686/msys2-i686-20200517.exe) and follow the installation instructions (Steps 1 to 8 on that page), these instructions assume that "C:\msys64" or "C:\msys32" is used depending on the bitness of the system it is being installed on.<br />
<br />
Install the following packages (using "pacman -S ''packageName''"), the ones with a '''-i686-''' in the middle are the ones for 32-bit (i686) targets and '''-x86_64-''' are the ones for 64-bit targets - it is possible to install both for building Mudlet for target PCs of both bitnesses on a 64-bit host, it is not clear whether the reverse is true with a 32-bit host. These will pull in a number of other required packages as well (the ''--needed'' option prevents the re-installation of packages that have already been installed by MSYS2/Mingw-w64's own setup/installation process) - as some of the packages, e.g. ''base-devel'' are actually ''groups'' you will be requested to select which members of that group are actually required, it is easiest to just go with the default which is to install ALL of the packages in that group!<br />
<br />
: For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-i686-toolchain mingw-w64-i686-qt-creator mingw-w64-i686-qt5-multimedia mingw-w64-i686-libzip mingw-w64-i686-pugixml mingw-w64-i686-lua51 mingw-w64-i686-lua51-lpeg mingw-w64-i686-lua51-lsqlite3 mingw-w64-i686-hunspell mingw-w64-i686-boost mingw-w64-i686-yajl mingw-w64-i686-clang mingw-w64-i686-cmake mingw-w64-i686-SDL unzip<br />
</syntaxhighlight><br />
<br />
: For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-x86_64-toolchain mingw-w64-x86_64-qt-creator mingw-w64-x86_64-qt5-multimedia mingw-w64-x86_64-libzip mingw-w64-x86_64-pugixml mingw-w64-x86_64-lua51 mingw-w64-x86_64-lua51-lpeg mingw-w64-x86_64-lua51-lsqlite3 mingw-w64-x86_64-hunspell mingw-w64-x86_64-boost mingw-w64-x86_64-yajl mingw-w64-x86_64-clang mingw-w64-x86_64-cmake mingw-w64-x86_64-SDL unzip<br />
</syntaxhighlight><br />
<br />
::The ''*-zziplib'' libraries are used by the ''luazip'' luarock {from the Kepler project} but Mudlet will work perfectly well with the alternative ''lua-zip'' {from the brimworks GitHub repository - which also provides the ''lua-yajl'' rock} which does not require this library - although it is possible that it might still be pulled into the system as a dependency of another MSYS2 package.<br />
<br />
:Note that this will install the MSYS2 builds of the Qt Libraries and Creator IDE - ''THE ON/OFF-LINE INSTALLER OF THE QT LIBRARIES AND CREATOR VIA DOWNLOADS FROM QT ARE NOT USEFUL IN THIS SETUP!''<br />
<br />
:{| class="wikitable"<br />
|-<br />
|'''Attention - Luarocks packages problem'''<br />
|-<br />
| Recently the Luarocks project attempted to adopt the MSYS2/Mingw-w64 platform as one it would supported natively and the MSYS2/Mingw-w64 project went and upgraded its luarocks packages to make use of the changes and also on-board other improvements (and the version number increased from ''2.4.4-2'' to ''3.5.0-1'') unfortunately this completely broke them and although the issue has been reported ([https://github.com/msys2/MINGW-packages/issues/9037 MSYS2 Issue 9037]) a fix has not yet materialised. The only way to work around this in the meantime is to download the older package (with '''wget''') and install it manually (with '''pacman -U):<br />
|-<br />
|For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:19:09-- https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97905 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-i686-lua51-luarocks-2.4.4-2- 100%[===========================================================================>] 95.61K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:19:10 (1.43 MB/s) - ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97905/97905]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-i686-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-i686-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|-<br />
|For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:17:32-- https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97935 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-x86_64-lua51-luarocks-2.4.4- 100%[===========================================================================>] 95.64K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:17:32 (1.28 MB/s) - ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97935/97935]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-x86_64-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-x86_64-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|}<br />
<br />
::{| class="wikitable"<br />
|-<br />
|'''Warning for those planning to build ''both'' 32 and 64 bit versions'''<br />
|-<br />
|If one is planning to build ''both'' bitness binaries an additional step is necessary as, by default, the MSYS2/Mingw-w64 ''luarocks'' setup seems to place any ''.lua'' or ''.dll'' modules it builds/installs on a per user (the so-called ''local'' basis) into the same directories with the same names. This is no good for two reasons:<br />
* It is difficult to work out which bitness a particular module is for and whilst 32-bit modules ''might'' work in a 64-bit environment the reverse is definitely not the case<br />
* It confuses the Luarocks package management systems (as effectively there will be two different luarocks systems operated side-by-side)<br />
<br />
This can be worked around by:<br />
* Editing the '''.\etc\luarocks\config-5.1.lua''' for each bitness so that the ''rocks_trees'' table entry for the ''user'' key is changed from this in '''both''' files:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks]] },</syntaxhighlight><br />
to something different for each of them, say, for example, for the the 64-bit one:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks-x64]] },</syntaxhighlight><br />
* Then by specifying the ''rocktree'' name ('''user''') on the command line when '''installing''' or '''building''' a luarock with the ''--tree user'' argument - note that for some inexplicable reason the ''--local'' argument that '''''should''''' do the same thing does not seem to work for these two actions, it is not clear whether this is a MSYS2/Mingw-w64 specific issue or it goes further upstream to Luarocks in general. Thus, in the next step it will be necessary to change from using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --local rockname<br />
</syntaxhighlight><br />
to, for the example given:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --tree user rockname<br />
</syntaxhighlight><br />
where ''user'' is the literal string "user" to match the Lua table key in the rock_trees and not, in this case, a representation of the user-name/account of the person performing the action.<br />
|}<br />
<br />
From the Windows ''Start menu'' start a shell appropriate for the target with the bitness to be built for i.e. '''"MSYS2 Mingw 32-Bit"''' or '''"MSYS2 Mingw 64-Bit"'''. This will likely position the current directory to the root directory of the MSYS2 environment, the text about the prompt line (the one with the "$") will contain three different bits of colored text '''username@computername'''; one of '''MSYS2'''/'''MINGW32'''/'''MINGW''' depending on the type of shell you currently in use and '''/''' representing the root directory (which will actually be the directory MSYS2 was installed to, for example on the author's system this is "C:/msys64"). Change to the home directory in MYSY by entering "cd" on its own with no argument (it will show up as '''~''' and it would work out to be, for '''user''' to be '''c:/msys64/home/user''' or '''c:/msys32/home/user''' (if both bitnessess are to be built it will be necessary to repeat the following step twice, one for each and also observe the steps in the above warning) install the following luarocks:<br />
<br />
:{| class="wikitable sortable"<br />
|-<br />
! rockname<br />
|-<br />
| lrexlib-pcre<br />
|-<br />
| lua-yajl<br />
|-<br />
| luafilesystem<br />
|-<br />
| luasql-sqlite3<br />
|-<br />
| luautf8<br />
|-<br />
| luazip or lua-zip<br />
|}<br />
by using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install [--local] rockname<br />
</syntaxhighlight><br />
The ''--local'' argument is an optional one that causes the luarock and the lua module to be installed on a per-user basis rather than on a system wide one, this may be important if the PC is used by multiple users and more than one of them uses Lua in any form.<br />
<br />
Now create somewhere to work on the Mudlet source, assuming that other software coding with other pieces of software will be done, create a sub-directory in the home directory, and then make one just for Mudlet under that:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ mkdir ./src<br />
<br />
MINGW64 user@computer ~<br />
$ mkdir ./src/mudlet<br />
</syntaxhighlight><br />
<br />
Change to that directory and get the source code:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ cd ./src/mudlet<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git clone git://github.com/Mudlet/Mudlet.git .<br />
</syntaxhighlight><br />
<br />
If you are planning to contribute to the Mudlet code you will want to visit Github and create your own GitHub repository, you can then push commits (changes to the code) to there and raise a Pull Request for a Mudlet Maker to drag the changes over to the above repository. You will want to add your repository and perhaps those of some other contributors so you can track what they are doing and see/try/experiment with their PRs before they get merged. Therefore you will want to add some other repositories into the mix. The names you use to identify those other repositories will show up in any utility that works with the repository you have just created in the above "clone" operation and can be anything you like but it makes sense to have clear names. So to add "myName", and those of the leading active contributors to the Mudlet codebase you will use:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Mine https://github.com/myName/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Vadim https://github.com/vadi2/Mudlet.git <br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add SlySven https://github.com/SlySven/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Kebap https://github.com/Kebap/Mudlet.git<br />
</syntaxhighlight><br />
<br />
Now obtain ''all'' the versions of the code with:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git fetch --all<br />
</syntaxhighlight><br />
<br />
This will produce a lot of lines of output the first time and it might take a little while on a slow connection...<br />
<br />
{Section missing - it turns out that the default GUI git tools that the author of this section would normally use: "gitk" and "git gui" have some problems in the versions currently supplied from the MSYS2 system - and it was necessary to import them from the set that the Git4Win have patched - see https://github.com/git-for-windows/git/wiki/Install-inside-MSYS2-proper }<br />
<br />
Some modifications to the qmake/cmake project files are needed and these are now supported in the main ''development'' branch in the upstream {the Mudlet organisation's own GitHub repository} which requires that there is an environmental variable '''WITH_MAIN_BUILD_SYSTEM''' and it is set to the (case-insensitive) value '''NO''':<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export WITH_MAIN_BUILD_SYSTEM=NO<br />
</syntaxhighlight><br />
<br />
Also the '''MINGW_BASE_DIR''' environmental variable will need to be set to the root directory for the MINGW-W64 installation for the appropriate bitness of the target to be made. For building on a 64-Bit Host {the PC that is ''compiling'' the code} to make a 64-Bit application this will likely be '''C:/msys64/mingw64''' and for a 32-Bit application it will probably be '''C:/msys64/ming32'''.<br />
: E.g. <syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw64 # To build a 64-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
: Or: <syntaxhighlight lang="shell"><br />
MINGW32 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw32 # To build a 32-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
Now checkout a branch {ideally, if working on solving a new issue, or adding a feature or resolving a bug, one should create a new branch that is a copy of the current, upstream ''development'' branch} and then work on it with Qt Creator:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ qtcreator &<br />
</syntaxhighlight><br />
<br />
Load in the '''mudlet.pro''' ''qmake'' project file in the '''src''' subdirectory (e.g. for this example: '''c:/msys64/home/user/src/mudlet/src/mudlet.pro''') and get hacking...<br />
<br />
= Setting up IDEs =<br />
== CLion ==<br />
=== Qt not detected ===<br />
If you'd like to use CLion and it is giving the following error:<br />
<br />
<nowiki><br />
By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has<br />
asked CMake to find a package configuration file provided by "Qt5Core", but<br />
CMake did not find one.<br />
<br />
...<br />
</nowiki><br />
<br />
You can fix this by setting <code>-DCMAKE_PREFIX_PATH=<your Qt + version + compiler location></code>. For example: <code>-DCMAKE_PREFIX_PATH=/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code> [[File:CLion CMake settings - finidng Qt.png|700px|none]]<br />
<br />
=== CLion setup on Windows ===<br />
After running <code>setup-windows-sdk.ps1</code> make sure to set Cmake options to:<br />
-DCMAKE_PREFIX_PATH=C:\Qt\Tools\mingw730_32;C:\Qt\5.14.2\mingw73_32 -DBoost_INCLUDE_DIR=C:\Libraries\boost_1_77_0<br />
''Directories might vary slightly, when different Qt, Boost or MinGW version will be used.''<br />
<br />
[[File:Clion Settings - Cmake.png|frameless|700x700px]]<br />
<br />
<br />
<br />
You will need 32 bit version of MinGW. Set it in the <code>Toolset</code> field to:<br />
C:\Qt\Tools\mingw730_32<br />
<br />
''Directory may be slightly different if MinGW version used will change.''<br />
<br />
[[File:Toolchain.png|frameless|700x700px]]<br />
<br />
=== Clang Tidy ===<br />
Ensure that CLion is set to run the project's [https://www.jetbrains.com/help/clion/clang-tidy-checks-support.html#paticularcheck .clang-tidy checks] with the <code>Prefer .clang-tidy files over IDE settings</code> option:<br />
<br />
[[File:Clang Tidy CLIon.png|700px|none]]<br />
<br />
This helps us catch any issues just a bit earlier.<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in CLion, adjust the CMake settings:<br />
<br />
[[File:Clion_cmake_settings.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
=== Clang Format ===<br />
Ensure that [https://www.jetbrains.com/help/clion/clangformat-as-alternative-formatter.html#clion-support CLion is set to use] the <code>.clang-format</code> formatting style:<br />
<br />
[[File:Clang-format CLion.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
== Visual Studio Code ==<br />
<br />
To set the path in Visual Studio Code, open settings, search for <code>cmake environment</code> and set the <code>CMAKE_PREFIX_PATH</code> to your path, such as <code>/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code>:<br />
<br />
[[File:CMake path in Visual Studio Code.png|none]]<br />
<br />
===Clang Tidy===<br />
clang-tidy catches common programming issues, run it by selecting 'Analysis' from the command palette (Ctrl+Shift+P by default):<br />
<br />
[[File:Clang-tidy in vscode.png|none]]<br />
<br />
It is also possible [https://devblogs.microsoft.com/cppblog/visual-studio-code-c-december-2021-update-clang-tidy/ check status of analysis and cancel if needed].<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in VSCode, set the <code>cmake.configureSettings</code> variable:<br />
<br />
[[File:Cmake.configureSettings option in vscode.png|frameless|890x890px]]<br />
<br />
[[File:Choosing which sanitizers in vscode to use.png|frameless|891x891px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
== Qt Creator==<br />
===Clang Tidy and Clazy===<br />
<br />
Configure Mudlet-specific checks for [https://clang.llvm.org/extra/clang-tidy/ clang-tidy] and [https://github.com/KDE/clazy clazy] tools help catch any issues early on. See [https://doc.qt.io/qtcreator/creator-clang-tools.html Qt Creator's instructions] for setting this up - clang-tidy can use the <code>.clang-tidy</code> file that's available at the root of the repository, and for clazy enable <code>level0</code> and <code>level1</code> checks.<br />
<br />
[[File:Clang tidy configuration.png|frame|none]]<br />
[[File:Clazy configuration.png|frame|none]]<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in Qt creator, head to <code>Projects</code> - <code>Build</code>: <br />
<br />
[[File:Sanitisers in qt creator.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
==Clang Format==<br />
Ensure that Qt Creator is set to use the <code>.clang-format</code> formatting style in the C++ settings. Turn on <code>Format instead of indenting</code> for <code>Ctrl+I</code> to format code, and ensure <code>Override Clang Format configuration file</code> is disabled:<br />
<br />
[[File:Qt Creator clang format.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
<br />
=Building with multiple versions of Lua=<br />
Mudlet uses Lua 5.1 only, so if you are compiling on a system that also has later versions installed, you might get the following error: <code>‘LUA_GLOBALSINDEX’ was not declared in this scope</code>.<br />
<br />
To fix this, pass the path to Lua headers explicitly. For CMake: <code>-DLUA_INCLUDE_DIR=/usr/include/lua5.1</code> (adjust as needed).</div>Kebaphttps://wiki.mudlet.org/index.php?title=Compiling_Mudlet&diff=20636Compiling Mudlet2023-12-21T09:47:48Z<p>Kebap: /* Compiling on Windows */ Layout</p>
<hr />
<div>{{TOC right}}<br />
<br />
If you just want to use Mudlet, you can skip these steps, and use one of the already ready (pre-compiled) installers [https://www.mudlet.org/download ready for download].<br />
<br />
Otherwise, hop in for new adventure! <br />
<br />
[[File:Easy Mudlet code understanding.png|frame|none]]<br />
<br />
= Key contributing information =<br />
<br />
Clang format is used to automatically format code submissions using the [https://github.com/Mudlet/Mudlet/blob/development/src/.clang-format src/.clang-format] style. [http://doc.qt.io/qtcreator/creator-beautifier.html See here] how to enable clang-format with Qt Creator - and make sure to specify the 'File' option for the configuration style.<br />
<br />
Branches:<br />
<br />
'''development''' is the development branch where new features can go.<br />
<br />
Workflow:<br />
<br />
Fork and submit a PR with your changes ([https://guides.github.com/activities/forking/ Github tutorial]).<br />
<br />
Here is a list of package versions delivered with different Linux distros. You may want to upgrade these: <br />
https://repology.org/project/mudlet/versions<br />
<br />
= Lua & Luarocks =<br />
<br />
Mudlet includes a [https://en.wikipedia.org/wiki/Lua_(programming_language) Lua] (version 5.1) scripting system for the end-user, which you, as a reader of this Wiki, may already be aware of! If not, you might wish to (after you have got your hands on a working Mudlet) take a look at [https://wiki.mudlet.org/w/Manual:Lua_Functions Mudlet Lua API] as that is the recommended place to find out the details of all the functions that Mudlet provides on top of the core Lua functionality.<br />
<br />
Some of that ability comes from extra code that is not built-in to Lua but is in the form of external modules either in the form of script (text) files written in the Lua language itself or binary (library) files compiled from (usually but not exclusively [https://en.wikipedia.org/wiki/C_(programming_language) 'C']) source code. In order to have that functionality Mudlet makes use of several of these modules which can most readily (if not already available as "packages" for a particular Operating System) be obtained as '''rocks''' from the public [https://en.wikipedia.org/wiki/LuaRocks Luarocks] collection. Such a rock actually consists of a ''rockspec'' file that gives instructions to the Luarocks tool how to obtains the (source) code, compile it on any supported OS into the form that a Lua interpreter (including the one included in '''''each''''' running Mudlet ''profile'') can use, and where and what it will be placed and called when it has been made. After that it should be available to Lua via the ''require'' command.<br />
<br />
Anyone compiling Mudlet for themselves will find it desirable to ensure they have a usable Luarocks installation and have the ''lua-yajl'' module installed before commencing to compile Mudlet itself; this is because a Lua (version 5.1) interpreter and that module are used within the build process of making the executable code that is the Mudlet application.<br />
<br />
= Compiling =<br />
<br />
== Compiling on Ubuntu ==<br />
<br />
These instructions will get you setup compiling on Ubuntu. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
===Ubuntu 22.04===<br />
Following instructions will work on Ubuntu 22.04 as well as all its flavours and derivatives (such as KDE Neon, for example)<br />
Important thing is to have ''Universe'' repository enabled in your package manager. (on Ubuntu you will have all the repositories that you need already enabled by default.)<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo apt install ubuntu-restricted-extras qtcreator build-essential git zlib1g-dev libhunspell-dev \<br />
libpcre3-dev libzip-dev libboost-dev libboost-all-dev libyajl-dev libpulse-dev libpugixml-dev \<br />
liblua5.1-0-dev lua-filesystem lua-zip lua-sql-sqlite3 luarocks ccache lua5.1 \<br />
libglu1-mesa-dev mesa-common-dev libglib2.0-dev libgstreamer1.0-dev libqt5opengl5-dev \<br />
qtmultimedia5-dev qttools5-dev qt5keychain-dev libsecret-1-dev \<br />
libqt5texttospeech5-dev qtspeech5-flite-plugin qtspeech5-speechd-plugin \<br />
qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo luarocks install lcf<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
sudo luarocks install lrexlib-pcre<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
4. '''installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
5. '''optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo apt install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.<br />
Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybidings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
===Other Ubuntu Versions===<br />
<br />
Most of the installation instructions for 22.04 should work for older versions as well. Of note is the required version of Qt, which is 5.14. If your used version of Ubuntu only supplies older<br />
Qt versions, have a look at [https://launchpad.net/~beineri Stephan Binners PPAs], which supplies a whole range of packages for different Ubuntu versions. Be sure to read the installation and<br />
usage instructions as Qt is installed to /opt and requires sourcing a script to set up.<br />
<br />
== Compiling on Chrome OS ==<br />
<br />
These instructions will get you setup compiling on Chrome OS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Install dependencies'''<br />
<br />
sudo apt install git build-essential qt5-default qtmultimedia5-dev qttools5-dev \<br />
lua5.1 liblua5.1-0-dev libpcre3-dev libboost-dev zlib1g-dev cmake \<br />
libhunspell-dev lua-rex-pcre lua-sql-sqlite3 lua-filesystem lua-zip libyajl-dev \<br />
libzip-dev libglu1-mesa-dev ccache libpugixml-dev mesa-common-dev qtcreator \<br />
libpulse-dev libglib2.0-dev luarocks libboost-all-dev libsecret-1-dev \<br />
ninja-build libsecret-1-dev<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''3. Get Mudlet source'''<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''4. Create a build directory'''<br />
<br />
cd mudlet<br />
mkdir build && cd build<br />
<br />
'''5. Run the following command '''<br />
<br />
cmake .. -G Ninja<br />
<br />
'''then:'''<br />
<br />
ninja<br />
<br />
'''5. Start the application you have just compiled - enjoy'''<br />
<br />
src/mudlet<br />
{{Note}}Did <code>ninja</code> fail with <code>c++: fatal error: Killed signal terminated program cclplus</code>? Try again with <code>ninja -j 2</code><br />
<br />
== Compiling on macOS ==<br />
<br />
These instructions will get you setup compiling on macOS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums] otherwise.<br />
<br />
<br />
'''1. Install prerequisites'''<br />
<br />
Install [https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12 XCode], command line tools for XCode, and [http://brew.sh HomeBrew].<br />
<br />
Once everything is installed, do:<br />
<br />
brew doctor<br />
brew update<br />
brew install git<br />
<br />
'''2. Get Mudlet source'''<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git <br />
<br />
'''3. Go to the parent of the mudlet "src" folder and create (if necessary) a build subdirectory (this is so that we can build out of source which keeps the source code clean)'''<br />
cd Mudlet && mkdir build<br />
<br />
'''3. Setup your environment'''<br />
./CI/travis.osx.before_install.sh<br />
./CI/travis.osx.install.sh<br />
<br />
luarocks config lua_version 5.1<br />
eval `luarocks path --lua-version=5.1`<br />
For the following, one may have to add <code>''_DIR="/opt/homebrew/"''</code> such as <code>PCRE_DIR="/opt/homebrew/"</code> or <code>ZIP_DIR="/opt/homebrew/"</code> if the installation could not find header files.<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lrexlib-pcre PCRE_DIR=`brew --prefix pcre`<br />
brew install sqlite<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luasql-sqlite3 SQLITE_DIR=`brew --prefix sqlite` <br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luautf8<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-yajl YAJL_LIBDIR=`brew --prefix yajl`<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luafilesystem<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-zip ZIP_DIR=`brew --prefix libzip`<br />
<br />
brew install p7zip<br />
export BOOST_ROOT="$(pwd)/../Mudlet/3rdparty/boost"<br />
export BOOST_URL="https://sourceforge.net/projects/boost/files/boost/1.83.0/boost_1_83_0.tar.bz2/download"<br />
mkdir -p $BOOST_ROOT<br />
curl --progress-bar --location --output $BOOST_ROOT/download.tar.bz2 $BOOST_URL<br />
7z -o$BOOST_ROOT x $BOOST_ROOT/download.tar.bz2 -y -bd<br />
7z -o$BOOST_ROOT x $BOOST_ROOT/download.tar -y -bd<br />
cd $BOOST_ROOT && cp -r boost_*/* .<br />
rm -rf boost_*/* download.tar.bz2 download.tar<br />
OK to answer yes to delete files if prompted for the <code>rm</code> command above.<br />
<br />
'''4. Run the following commands'''<br />
<br />
cd ../../build<br />
cmake ../../Mudlet -DCMAKE_PREFIX_PATH=`brew --prefix qt5`<br />
make -j `sysctl -n hw.ncpu`<br />
<br />
<br />
'''5. Enjoy'''<br />
<br />
The mudlet.app is now available in <code>src/</code> for launching:<br />
<br />
open src/Mudlet.app<br />
<br />
'''6. Qt Creator setup'''<br />
<br />
No Lua installation is found, despite it existing on your system? Launch Qt Creator by doing <code>open /Applications/Qt Creator.app</code> (location depends on how you installed it).<br />
<br />
Receiving a <code>No rule to make target ... libQt5UiTools_debug.a</code> error? A workaround is to [https://bugreports.qt.io/browse/QTBUG-81251?focusedCommentId=538705&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-538705 symlink a file].<br />
<br />
Mudlet in Qt Creator is not launching due to <code>dyld: Symbol not found: __cg_jpeg_resync_to_restart</code>? See [https://stackoverflow.com/a/44851430/72944 here] for a workaround.<br />
<br />
====== 7. Troubleshooting ======<br />
If you exhaust all efforts to get YAJL to compile on your local system with homebrew, [https://github.com/lloyd/yajl/ clone from the YAJL repository] then <code>./configure && sudo make install</code>.<br />
<br />
== Compiling on Debian 'Sid' ==<br />
<br />
'''1. Install required packages from main repo.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev<br />
<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Grab latest Mudlet source.'''<br />
<br />
mkdir ~/projects && cd ~/projects && git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
cd ~/projects/mudlet/src<br />
<br />
qmake<br />
<br />
make<br />
<br />
sudo make install<br />
<br />
== Compiling on Debian 11 'Bullseye' ==<br />
<br />
'''1. Install required packages.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev \<br />
qttools5-dev luarocks ccache libpugixml-dev libqt5texttospeech5-dev qtspeech5-flite-plugin \<br />
qtspeech5-speechd-plugin libqt5opengl5-dev ninja-build cmake libsecret-1-dev<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Get Mudlet source.'''<br />
<br />
mkdir ~/source && cd ~/source<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git<br />
<br />
Note: the line above will check out `development` branch source code, and this might not always be stable. You can check out the latest release source code using this command:<br />
<br />
git clone --recursive --branch main https://github.com/Mudlet/Mudlet.git<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
mkdir ~/source/Mudlet/build && cd ~/source/Mudlet/build<br />
<br />
qmake ../src/mudlet.pro<br />
<br />
make -j `nproc`<br />
<br />
sudo make install<br />
<br />
After these steps you can run Mudlet by typing:<br />
<br />
mudlet<br />
<br />
'''4. (Optional) Discord library'''<br />
<br />
If you get the following error;<br />
<br />
Could not find Discord library - searched in:<br />
<br />
you need to specify the discord library in your build. Run the following, changing the path where necessary;<br />
<br />
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/mudlet-dev/Mudlet/3rdparty/discord/rpc/lib/<br />
<br />
and recompile. You should see<br />
<br />
Discord integration loaded. Using functions from: "libdiscord-rpc.so"<br />
<br />
== Compiling on Raspberry Pi OS ==<br />
<br />
These instructions will get you compiling and running Mudlet on Raspberry Pi OS (Buster). Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
''' 1.a Install apt dependencies '''<br />
<br />
sudo apt-get update<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-graph-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev cmake<br />
<br />
<br />
[[File:Apt-get-install-y-n.png|center|thumb|installing apt dependencies]]<br />
<br />
''' 1.b Install luarocks dependencies '''<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl YAJL_LIBDIR=`find /usr -name "libyajl.so" -printf '%h\n'` YAJL_INCDIR=/usr/include<br />
<br />
<br />
[[File:After-luarocks-dependencies.png|center|thumb|after luarocks dependencies]]<br />
<br />
''' 2. Get Mudlet source '''<br />
<br />
mkdir ~/source && cd ~/source <br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
<br />
[[File:After-get-mudlet-source.png|center|thumb|After cloning]]<br />
<br />
''' 3. Create a build directory '''<br />
<br />
cd Mudlet && mkdir build && cd build<br />
<br />
''' 4. Run the following commands to build '''<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake ../src/mudlet.pro<br />
<br />
:If you get a response along the lines of:<br />
<br />
qmake: could not find a Qt installation of ''<br />
<br />
:then you likely have ''qtchooser'' present in your system that allows for both Qt4 and Qt5 (or more than one Qt5 version) and it modifiers qmake and some other Qt development programs to take an additional argument to specify which version to use. In that case you should use:<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake -qt=qt5 ../src/mudlet.pro<br />
<br />
[[File:After-qmake.png|center|thumb|After qmake]]<br />
<br />
''' THEN: '''<br />
:For the fastest compile time while still being able to use the system at all (~35min on a RPi4 with 4GB of ram)<br />
make -j $(expr `nproc` - 1)<br />
<br />
''' OR: '''<br />
<br />
:Use this if you have an older Raspberry Pi. Be prepared for it to take a while (over an hour) - ''it is not recommended to try to more than one compilation task at a time on the older systems with the '''-j''' option as they will only have a system memory with enough space for one of some of those tasks'':<br />
make<br />
<br />
[[File:Success.png|center|thumb|Success!]]<br />
<br />
''' 4. Install the application you have just compiled '''<br />
<br />
sudo make install<br />
<br />
[[File:Installed.png|center|thumb|Installed now]]<br />
<br />
''' 5. Enjoy! '''<br />
<br />
# mudlet is in the path, can just run it<br />
mudlet<br />
<br />
== Compiling on Arch Linux ==<br />
<br />
===AUR Install and Compile===<br />
Mudlet is available in the [https://aur.archlinux.org Arch User Repository].<br />
(If the AUR has become unmaintained/orphaned, then skip below to [https://wiki.mudlet.org/w/Compiling_Mudlet#Manual_Install_and_Compile Manual install].)<br />
<br />
To install it use your favourite AUR helper (helper tool will automatically resove dependancies); example using ''yay'' :<br />
yay -S mudlet<br />
<br />
For more info on this process, visit [https://wiki.archlinux.org/index.php/Arch_User_Repository Arch User Repository - ArchWiki].<br />
<br />
''Note: For the most recent development version of Mudlet, replace 'mudlet' with 'mudlet-git' in the above commands and proceed as described.''<br />
<br />
''Built in fonts have been disabled, but are available in packages listed as optional dependancies.''<br />
<br />
''Discord support in Mudlet depends on an external library provided by discord-rpc-api, which is also available in AUR, choose whichever variant suits you best.''<br />
<br />
===Manual Install and Compile===<br />
These instructions will get you setup compiling on Arch. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo pacman -S --needed cmake qt5-multimedia hunspell libzip lua51-filesystem qt5-gamepad lua51-luautf8 pugixml \<br />
ttf-font qtkeychain-qt5 boost qt5-tools ttf-bitstream-vera ttf-ubuntu-font-family noto-fonts-emoji glu luarocks<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo lua5.1 /usr/bin/luarocks install lcf<br />
sudo lua5.1 /usr/bin/luarocks install luautf8<br />
sudo lua5.1 /usr/bin/luarocks install lua-yajl<br />
sudo lua5.1 /usr/bin/luarocks install lrexlib-pcre<br />
sudo lua5.1 /usr/bin/luarocks install luasql-sqlite3<br />
sudo lua5.1 /usr/bin/luarocks install lua-zip<br />
<br />
There is an optional dependency for discord integration:<br />
git clone https://github.com/discord/discord-rpc<br />
cd discord-rpc<br />
mkdir build<br />
cd build<br />
cmake .. -DCMAKE_INSTALL_PREFIX=/usr<br />
sudo cmake --build . --config Release --target install<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
'''4. installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''5. optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo pacman -S install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.↵Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybindings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
== Compiling on Fedora (aarch64) ==<br />
<br />
'''1. Install dependencies'''<br />
sudo dnf groupinstall "Development Tools" "Development Libraries"<br />
<br />
sudo dnf install compat-lua compat-lua-devel compat-lua-libs hunspell-devel lua5.1-filesystem luarocks pugixml-devel qtkeychain-qt5-devel bitstream-vera-fonts-all ccache qt-creator qt5-qtmultimedia-devel qt5-qtgamepad-devel yajl-devel qtchooser qt5-qttools-devel qt5-qttools-static zziplib-devel pcre-devel libzip-devel sqlite-devel<br />
<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luazip<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luasql-sqlite3<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lcf<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luautf8<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lua-yajl<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lrexlib-pcre<br />
In your user's home directory:<br />
<br />
If you use a bash shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .bashenv<br />
source .bashenv<br />
If you use a zsh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .zshenv<br />
source .zshenv<br />
If you use a csh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .cshenv<br />
source .cshenv<br />
This should cover paths, but you may want to reboot to be sure.<br />
<br />
'''2. Obtain the source code'''<br />
git clone --recursive --branch=development <nowiki>https://github.com/Mudlet/Mudlet.git</nowiki><br />
mkdir Mudlet/build<br />
cd Mudlet/src<br />
<br />
'''3. Make necessary compiling instruction adjustments'''<br />
<br />
Edit mudlet.pro - find these lines in mudlet.pro and make the following changes:<br />
linux {<br />
LIBS += \<br />
-llua5.1 \<br />
-lhunspell<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
We're adding a - between lua and 5.1 and adding -1.7 to hunspell under LIBS so that it becomes this:<br />
linux {<br />
LIBS += \<br />
-llua-5.1 \<br />
-lhunspell-1.7<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
Save and exit.<br />
<br />
'''4. Compile'''<br />
cd ../build<br />
Run this in the build directory:<br />
WITH_FONTS=NO WITH_OWN_QTKEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share qmake-qt5 PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1 LUA_SEARCH_OUT=lua-5.1 ../src/mudlet.pro<br />
An explanation of the qmake arguments -- we're passing these environment variables to mudlet.pro:<br />
WITH_FONTS=NO WITH_OWN_KEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share<br />
Adding build variables to mudlet.pro so that it finds the correct libraries:<br />
PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1<br />
And finally adding a build variable to translations/translated/updateqm.pri so that it uses the correct version of the Lua compiler (Fedora also comes with 5.4) to generate translation statistics.<br />
LUA_SEARCH_OUT=lua-5.1<br />
Once complete, run the following:<br />
<br />
If you have time to kill (About 10 minutes on an Apple M1 Max in Fedora):<br />
make<br />
If you want it done as fast as possible(Less than a minute on an Apple M1 Max in Fedora):<br />
make -j `nproc`<br />
Or if you want something in between, make -j `nproc` tells it to use all available processor cores. If you want to use a specific number instead (ie 2), you can use:<br />
make -j 2<br />
<br />
'''5. Install'''<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
'''6. Hang onto the cloned git repo '''<br />
If you need to uninstall, you can go back into the /build directory and 'sudo make uninstall'.<br />
<br />
== Compiling on Gentoo ==<br />
An [https://github.com/toaster/gentoo-overlay overlay containing Mudlet is available] for compiling Mudlet on Gentoo.<br />
<br />
== Compiling on Windows ==<br />
<br />
These instructions will get you setup compiling on Windows. <br />
<br />
Need a hand? Join us on the Mudlet [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Download Mudlet source code'''<br />
<br />
# Install [https://desktop.github.com/ Github Desktop].<br />
# Clone ([https://help.github.com/desktop/guides/contributing-to-projects/cloning-a-repository-from-github-to-github-desktop/#platform-windows instructions]) Mudlet's [https://github.com/mudlet/mudlet repository] to your local drive.<br />
{{note}} You must use a location on <code>C:\</code> without any spaces in folder names! <br />
<br />
'''2. Perform a one-time setup'''<br />
<br />
# Right-click on <code>setup-windows-sdk.ps1</code> and select <code>Run with PowerShell</code>. <br />
<br />
This will automatically download all of the requires tools (including Python 2) and libraries, set them up for you, build Mudlet, and launch it! <br />
<br />
{{note}} If this script exits immediately, please [https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/install/installing-windows-powershell?view=powershell-7.1#upgrading-existing-windows-powershell upgrade your PowerShell version] first.<br />
<br />
{{note}} Depending on your Internet connection and computer speed, this one-time setup will take 30 minutes or more - so grab a cup of tea or coffee.<br />
<br />
[[File:Start-of-installation.gif|frame|none|Sometimes the output will get stuck and not progress - just press Enter to make it continue. This is a well-known [https://serverfault.com/questions/204150/sometimes-powershell-stops-sending-output-until-i-press-enter-why Powershell bug.]]]<br />
<br />
During the installation, you'll see the Qt installer window pop-up - this is normal:<br />
<br />
[[File:Qt-installer.gif|thumb|none]]<br />
<br />
The Qt installer might ask you about your data collection preferences - answer as you wish and the automated install will continue:<br />
<br />
[[File:Qt-installer-data-collection.png|thumb|none]]<br />
<br />
The installer's final step will be compiling all of the source code, which looks like this:<br />
<br />
[[File:Compiling-step.gif|thumb|none]]<br />
<br />
After it's all done, a Mudlet version ending in "-dev" will launch automatically:<br />
<br />
[[File:Mudlet-launching.gif|frame|none]]<br />
<br />
If something didn't work right, you can check out the verbose log that is available at <code>C:\src\verbose_output.log</code>.<br />
<br />
=== Coding on Mudlet ===<br />
<br />
Open <code>C:\<path to repository>\src\mudlet.pro</code> in Qt Creator, which resides here: <code>C:\Qt\Tools\QtCreator\bin\qtcreator.exe</code>. Then enable Debug and Release builds and hit ''Configure Project'':<br />
<br />
[[File:Selection_173.png|frame|none]]<br />
<br />
Press <code>Ctrl+5</code> and update project settings. Check how many logical processors are available in your system with the Task Manager:<br />
<br />
[[File:Task-manager.png|thumb|none|2 processors are available in this example]]<br />
<br />
And set this amount in Qt Creator:<br />
<br />
[[File:Change Qt Creator to use many cores.gif|frame|none]]<br />
<br />
Hit run:<br />
<br />
[[File:Selection 176.png|frame|none]]<br />
<br />
Click on '''Compile Output''' to see progress on compiling:<br />
<br />
[[File:Selection 177.png|frame|none]]<br />
<br />
When it's all ready, the new Mudlet with your changes will launch. '''You're all done'''!<br />
<br />
=== Contributing changes ===<br />
<br />
Once you're all done with your changes, contribute them to Mudlet using a [https://help.github.com/desktop/guides/contributing-to-projects/creating-a-pull-request/#platform-windows pull request]. Thanks for improving open-source!<br />
<br />
=== Uninstalling ===<br />
To get rid of everything, remove the following folders:<br />
<br />
C:\Libraries<br />
C:\LuaRocks<br />
C:\MinGW<br />
C:\Python27<br />
C:\Qt<br />
C:\src<br />
<br />
== Compiling on Github Codespaces ==<br />
<br />
[https://github.com/features/codespaces/ Github Codespaces] allow you to code and run Mudlet all from the browser - makes it a lot easier to get started. It also allows you to code Mudlet itself from any computer in the world! <br />
<br />
'''1. Create a new codespace'''<br />
<br />
Create a new Codespace by going to https://github.com/Mudlet/Mudlet using Google Chrome or Microsoft Edge (Firefox at the time of the writing doesn't have working copy/paste). There, click the green "Code" button, select the "Codespaces" tab and click "New codespace".<br />
<br />
[[File:New codespace.png|alt=New codespace screenshot|frameless]]<br />
<br />
'''2. Wait for it to load'''<br />
<br />
This will take a while (~5min) so grab a tea:<br />
<br />
[[File:Building Visual Studio Codespace.png|frameless]]<br />
<br />
'''3. Connect to the environment'''<br />
<br />
Go to the <code>Ports</code> section at the bottom and change the Port Privacy of the Open Mudlet port to Public:<br />
<br />
[[File:Port privacy in Github Codespaces.png|900x900px]]<br />
<br />
<br />
Then connect to your online Linux desktop with <code>mudlet</code> as the password by clicking on the web icon. <br />
<br />
[[File:Connect to remote machine.png|frameless]]<br />
<br />
<br />
In case it can't connect, make sure the port privacy is set to <code>Public</code>. If it still can't connect, try 4-5 more times - eventually it'll work.<br />
<br />
<br />
<br />
We chose a retro 90's look here to fit with the whole hacking theme, so if you see this you're good 😉<br />
<br />
[[File:Github_codespaces_desktop.png|alt=|frameless|400x400px]]<br />
<br />
'''4. Build Mudlet'''<br />
<br />
In Codespaces, hit <code>F7</code> and select <code>Let CMake guess...</code><br />
<br />
[[File:CMake configuration.png|none]]<br />
<br />
It will then start building Mudlet automatically. Using the [https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/about-billing-for-codespaces Basic instance] (only kind available in beta) the first-time build will take ~25min, so take a break here - you've made excellent progress. All follow-up compiles after this will be quicker, by the way.<br />
<br />
[[File:Building Mudlet in codespaces.png|none]]<br />
<br />
'''5. Run Mudlet'''<br />
<br />
[[File:Launch Mudlet.png|none]]<br />
<br />
Hit the little play button at the bottom of the screen, and Mudlet will now launch in the remote connection tab. Not working? [https://discord.gg/kuYvMQ9 We can help]. Otherwise, enjoy!<br />
<br />
[[File:Mudlet running remotely.png |500px]]<br />
<br />
Note: When the codespace is unused for a while, it will disconnect. It'll never disconnect while you're actively using it. See [https://github.com/microsoft/vscode-dev-containers/issues/588 Github issue] for details.<br />
<br />
== Developing with Docker ==<br />
<br />
Docker is a system designed for more reproducible and isolated builds. A docker setup exists and has been tested using Pop OS! 20.04 (which is derived from Ubuntu 20.04). First, follow the instructions to install both [https://docs.docker.com/get-docker/ docker] and [https://docs.docker.com/compose/install/ docker-compose].<br />
<br />
Clone the development branch<br />
<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
cd Mudlet/docker<br />
<br />
Make a local copy of the .env.template file:<br />
<br />
cp .env.template .env<br />
<br />
If you wish to customize things like the number of cores to use for building mudlet, feel free to change the corresponding values in the .env file.<br />
<br />
To run Qt-Creator and develop Mudlet, run <code>docker-compose up dev</code>.<br />
<br />
To run Mudlet, run <code>docker-compose up mudlet</code>. Note: At the moment, the mudlet build will not persist settings past container rebuilds.<br />
<br />
== Compiling on Windows 7+ (MSYS2 Alternative)==<br />
<br />
''INCOMPLETE, IN PROGRESS''<br />
<br />
Go to http://www.msys2.org/ to download the 64 bit MSYS2 installer (as of 2020/05/24 32 bit hosts - for '''compiling''' software, but ''not'' for using code built with it have been deprecated, the last installer for that 32-bit systems is held at: http://repo.msys2.org/distrib/i686/msys2-i686-20200517.exe) and follow the installation instructions (Steps 1 to 8 on that page), these instructions assume that "C:\msys64" or "C:\msys32" is used depending on the bitness of the system it is being installed on.<br />
<br />
Install the following packages (using "pacman -S ''packageName''"), the ones with a '''-i686-''' in the middle are the ones for 32-bit (i686) targets and '''-x86_64-''' are the ones for 64-bit targets - it is possible to install both for building Mudlet for target PCs of both bitnesses on a 64-bit host, it is not clear whether the reverse is true with a 32-bit host. These will pull in a number of other required packages as well (the ''--needed'' option prevents the re-installation of packages that have already been installed by MSYS2/Mingw-w64's own setup/installation process) - as some of the packages, e.g. ''base-devel'' are actually ''groups'' you will be requested to select which members of that group are actually required, it is easiest to just go with the default which is to install ALL of the packages in that group!<br />
<br />
: For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-i686-toolchain mingw-w64-i686-qt-creator mingw-w64-i686-qt5-multimedia mingw-w64-i686-libzip mingw-w64-i686-pugixml mingw-w64-i686-lua51 mingw-w64-i686-lua51-lpeg mingw-w64-i686-lua51-lsqlite3 mingw-w64-i686-hunspell mingw-w64-i686-boost mingw-w64-i686-yajl mingw-w64-i686-clang mingw-w64-i686-cmake mingw-w64-i686-SDL unzip<br />
</syntaxhighlight><br />
<br />
: For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-x86_64-toolchain mingw-w64-x86_64-qt-creator mingw-w64-x86_64-qt5-multimedia mingw-w64-x86_64-libzip mingw-w64-x86_64-pugixml mingw-w64-x86_64-lua51 mingw-w64-x86_64-lua51-lpeg mingw-w64-x86_64-lua51-lsqlite3 mingw-w64-x86_64-hunspell mingw-w64-x86_64-boost mingw-w64-x86_64-yajl mingw-w64-x86_64-clang mingw-w64-x86_64-cmake mingw-w64-x86_64-SDL unzip<br />
</syntaxhighlight><br />
<br />
::The ''*-zziplib'' libraries are used by the ''luazip'' luarock {from the Kepler project} but Mudlet will work perfectly well with the alternative ''lua-zip'' {from the brimworks GitHub repository - which also provides the ''lua-yajl'' rock} which does not require this library - although it is possible that it might still be pulled into the system as a dependency of another MSYS2 package.<br />
<br />
:Note that this will install the MSYS2 builds of the Qt Libraries and Creator IDE - ''THE ON/OFF-LINE INSTALLER OF THE QT LIBRARIES AND CREATOR VIA DOWNLOADS FROM QT ARE NOT USEFUL IN THIS SETUP!''<br />
<br />
:{| class="wikitable"<br />
|-<br />
|'''Attention - Luarocks packages problem'''<br />
|-<br />
| Recently the Luarocks project attempted to adopt the MSYS2/Mingw-w64 platform as one it would supported natively and the MSYS2/Mingw-w64 project went and upgraded its luarocks packages to make use of the changes and also on-board other improvements (and the version number increased from ''2.4.4-2'' to ''3.5.0-1'') unfortunately this completely broke them and although the issue has been reported ([https://github.com/msys2/MINGW-packages/issues/9037 MSYS2 Issue 9037]) a fix has not yet materialised. The only way to work around this in the meantime is to download the older package (with '''wget''') and install it manually (with '''pacman -U):<br />
|-<br />
|For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:19:09-- https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97905 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-i686-lua51-luarocks-2.4.4-2- 100%[===========================================================================>] 95.61K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:19:10 (1.43 MB/s) - ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97905/97905]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-i686-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-i686-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|-<br />
|For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:17:32-- https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97935 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-x86_64-lua51-luarocks-2.4.4- 100%[===========================================================================>] 95.64K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:17:32 (1.28 MB/s) - ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97935/97935]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-x86_64-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-x86_64-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|}<br />
<br />
::{| class="wikitable"<br />
|-<br />
|'''Warning for those planning to build ''both'' 32 and 64 bit versions'''<br />
|-<br />
|If one is planning to build ''both'' bitness binaries an additional step is necessary as, by default, the MSYS2/Mingw-w64 ''luarocks'' setup seems to place any ''.lua'' or ''.dll'' modules it builds/installs on a per user (the so-called ''local'' basis) into the same directories with the same names. This is no good for two reasons:<br />
* It is difficult to work out which bitness a particular module is for and whilst 32-bit modules ''might'' work in a 64-bit environment the reverse is definitely not the case<br />
* It confuses the Luarocks package management systems (as effectively there will be two different luarocks systems operated side-by-side)<br />
<br />
This can be worked around by:<br />
* Editing the '''.\etc\luarocks\config-5.1.lua''' for each bitness so that the ''rocks_trees'' table entry for the ''user'' key is changed from this in '''both''' files:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks]] },</syntaxhighlight><br />
to something different for each of them, say, for example, for the the 64-bit one:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks-x64]] },</syntaxhighlight><br />
* Then by specifying the ''rocktree'' name ('''user''') on the command line when '''installing''' or '''building''' a luarock with the ''--tree user'' argument - note that for some inexplicable reason the ''--local'' argument that '''''should''''' do the same thing does not seem to work for these two actions, it is not clear whether this is a MSYS2/Mingw-w64 specific issue or it goes further upstream to Luarocks in general. Thus, in the next step it will be necessary to change from using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --local rockname<br />
</syntaxhighlight><br />
to, for the example given:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --tree user rockname<br />
</syntaxhighlight><br />
where ''user'' is the literal string "user" to match the Lua table key in the rock_trees and not, in this case, a representation of the user-name/account of the person performing the action.<br />
|}<br />
<br />
From the Windows ''Start menu'' start a shell appropriate for the target with the bitness to be built for i.e. '''"MSYS2 Mingw 32-Bit"''' or '''"MSYS2 Mingw 64-Bit"'''. This will likely position the current directory to the root directory of the MSYS2 environment, the text about the prompt line (the one with the "$") will contain three different bits of colored text '''username@computername'''; one of '''MSYS2'''/'''MINGW32'''/'''MINGW''' depending on the type of shell you currently in use and '''/''' representing the root directory (which will actually be the directory MSYS2 was installed to, for example on the author's system this is "C:/msys64"). Change to the home directory in MYSY by entering "cd" on its own with no argument (it will show up as '''~''' and it would work out to be, for '''user''' to be '''c:/msys64/home/user''' or '''c:/msys32/home/user''' (if both bitnessess are to be built it will be necessary to repeat the following step twice, one for each and also observe the steps in the above warning) install the following luarocks:<br />
<br />
:{| class="wikitable sortable"<br />
|-<br />
! rockname<br />
|-<br />
| lrexlib-pcre<br />
|-<br />
| lua-yajl<br />
|-<br />
| luafilesystem<br />
|-<br />
| luasql-sqlite3<br />
|-<br />
| luautf8<br />
|-<br />
| luazip or lua-zip<br />
|}<br />
by using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install [--local] rockname<br />
</syntaxhighlight><br />
The ''--local'' argument is an optional one that causes the luarock and the lua module to be installed on a per-user basis rather than on a system wide one, this may be important if the PC is used by multiple users and more than one of them uses Lua in any form.<br />
<br />
Now create somewhere to work on the Mudlet source, assuming that other software coding with other pieces of software will be done, create a sub-directory in the home directory, and then make one just for Mudlet under that:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ mkdir ./src<br />
<br />
MINGW64 user@computer ~<br />
$ mkdir ./src/mudlet<br />
</syntaxhighlight><br />
<br />
Change to that directory and get the source code:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ cd ./src/mudlet<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git clone git://github.com/Mudlet/Mudlet.git .<br />
</syntaxhighlight><br />
<br />
If you are planning to contribute to the Mudlet code you will want to visit Github and create your own GitHub repository, you can then push commits (changes to the code) to there and raise a Pull Request for a Mudlet Maker to drag the changes over to the above repository. You will want to add your repository and perhaps those of some other contributors so you can track what they are doing and see/try/experiment with their PRs before they get merged. Therefore you will want to add some other repositories into the mix. The names you use to identify those other repositories will show up in any utility that works with the repository you have just created in the above "clone" operation and can be anything you like but it makes sense to have clear names. So to add "myName", and those of the leading active contributors to the Mudlet codebase you will use:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Mine https://github.com/myName/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Vadim https://github.com/vadi2/Mudlet.git <br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add SlySven https://github.com/SlySven/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Kebap https://github.com/Kebap/Mudlet.git<br />
</syntaxhighlight><br />
<br />
Now obtain ''all'' the versions of the code with:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git fetch --all<br />
</syntaxhighlight><br />
<br />
This will produce a lot of lines of output the first time and it might take a little while on a slow connection...<br />
<br />
{Section missing - it turns out that the default GUI git tools that the author of this section would normally use: "gitk" and "git gui" have some problems in the versions currently supplied from the MSYS2 system - and it was necessary to import them from the set that the Git4Win have patched - see https://github.com/git-for-windows/git/wiki/Install-inside-MSYS2-proper }<br />
<br />
Some modifications to the qmake/cmake project files are needed and these are now supported in the main ''development'' branch in the upstream {the Mudlet organisation's own GitHub repository} which requires that there is an environmental variable '''WITH_MAIN_BUILD_SYSTEM''' and it is set to the (case-insensitive) value '''NO''':<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export WITH_MAIN_BUILD_SYSTEM=NO<br />
</syntaxhighlight><br />
<br />
Also the '''MINGW_BASE_DIR''' environmental variable will need to be set to the root directory for the MINGW-W64 installation for the appropriate bitness of the target to be made. For building on a 64-Bit Host {the PC that is ''compiling'' the code} to make a 64-Bit application this will likely be '''C:/msys64/mingw64''' and for a 32-Bit application it will probably be '''C:/msys64/ming32'''.<br />
: E.g. <syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw64 # To build a 64-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
: Or: <syntaxhighlight lang="shell"><br />
MINGW32 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw32 # To build a 32-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
Now checkout a branch {ideally, if working on solving a new issue, or adding a feature or resolving a bug, one should create a new branch that is a copy of the current, upstream ''development'' branch} and then work on it with Qt Creator:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ qtcreator &<br />
</syntaxhighlight><br />
<br />
Load in the '''mudlet.pro''' ''qmake'' project file in the '''src''' subdirectory (e.g. for this example: '''c:/msys64/home/user/src/mudlet/src/mudlet.pro''') and get hacking...<br />
<br />
= Setting up IDEs =<br />
== CLion ==<br />
=== Qt not detected ===<br />
If you'd like to use CLion and it is giving the following error:<br />
<br />
<nowiki><br />
By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has<br />
asked CMake to find a package configuration file provided by "Qt5Core", but<br />
CMake did not find one.<br />
<br />
...<br />
</nowiki><br />
<br />
You can fix this by setting <code>-DCMAKE_PREFIX_PATH=<your Qt + version + compiler location></code>. For example: <code>-DCMAKE_PREFIX_PATH=/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code> [[File:CLion CMake settings - finidng Qt.png|700px|none]]<br />
<br />
=== CLion setup on Windows ===<br />
After running <code>setup-windows-sdk.ps1</code> make sure to set Cmake options to:<br />
-DCMAKE_PREFIX_PATH=C:\Qt\Tools\mingw730_32;C:\Qt\5.14.2\mingw73_32 -DBoost_INCLUDE_DIR=C:\Libraries\boost_1_77_0<br />
''Directories might vary slightly, when different Qt, Boost or MinGW version will be used.''<br />
<br />
[[File:Clion Settings - Cmake.png|frameless|700x700px]]<br />
<br />
<br />
<br />
You will need 32 bit version of MinGW. Set it in the <code>Toolset</code> field to:<br />
C:\Qt\Tools\mingw730_32<br />
<br />
''Directory may be slightly different if MinGW version used will change.''<br />
<br />
[[File:Toolchain.png|frameless|700x700px]]<br />
<br />
=== Clang Tidy ===<br />
Ensure that CLion is set to run the project's [https://www.jetbrains.com/help/clion/clang-tidy-checks-support.html#paticularcheck .clang-tidy checks] with the <code>Prefer .clang-tidy files over IDE settings</code> option:<br />
<br />
[[File:Clang Tidy CLIon.png|700px|none]]<br />
<br />
This helps us catch any issues just a bit earlier.<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in CLion, adjust the CMake settings:<br />
<br />
[[File:Clion_cmake_settings.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
=== Clang Format ===<br />
Ensure that [https://www.jetbrains.com/help/clion/clangformat-as-alternative-formatter.html#clion-support CLion is set to use] the <code>.clang-format</code> formatting style:<br />
<br />
[[File:Clang-format CLion.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
== Visual Studio Code ==<br />
<br />
To set the path in Visual Studio Code, open settings, search for <code>cmake environment</code> and set the <code>CMAKE_PREFIX_PATH</code> to your path, such as <code>/media/vadi/SSDer/Programs/Qt/5.14.2/gcc_64/</code>:<br />
<br />
[[File:CMake path in Visual Studio Code.png|none]]<br />
<br />
===Clang Tidy===<br />
clang-tidy catches common programming issues, run it by selecting 'Analysis' from the command palette (Ctrl+Shift+P by default):<br />
<br />
[[File:Clang-tidy in vscode.png|none]]<br />
<br />
It is also possible [https://devblogs.microsoft.com/cppblog/visual-studio-code-c-december-2021-update-clang-tidy/ check status of analysis and cancel if needed].<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in VSCode, set the <code>cmake.configureSettings</code> variable:<br />
<br />
[[File:Cmake.configureSettings option in vscode.png|frameless|890x890px]]<br />
<br />
[[File:Choosing which sanitizers in vscode to use.png|frameless|891x891px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
== Qt Creator==<br />
===Clang Tidy and Clazy===<br />
<br />
Configure Mudlet-specific checks for [https://clang.llvm.org/extra/clang-tidy/ clang-tidy] and [https://github.com/KDE/clazy clazy] tools help catch any issues early on. See [https://doc.qt.io/qtcreator/creator-clang-tools.html Qt Creator's instructions] for setting this up - clang-tidy can use the <code>.clang-tidy</code> file that's available at the root of the repository, and for clazy enable <code>level0</code> and <code>level1</code> checks.<br />
<br />
[[File:Clang tidy configuration.png|frame|none]]<br />
[[File:Clazy configuration.png|frame|none]]<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in Qt creator, head to <code>Projects</code> - <code>Build</code>: <br />
<br />
[[File:Sanitisers in qt creator.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
==Clang Format==<br />
Ensure that Qt Creator is set to use the <code>.clang-format</code> formatting style in the C++ settings. Turn on <code>Format instead of indenting</code> for <code>Ctrl+I</code> to format code, and ensure <code>Override Clang Format configuration file</code> is disabled:<br />
<br />
[[File:Qt Creator clang format.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
<br />
=Building with multiple versions of Lua=<br />
Mudlet uses Lua 5.1 only, so if you are compiling on a system that also has later versions installed, you might get the following error: <code>‘LUA_GLOBALSINDEX’ was not declared in this scope</code>.<br />
<br />
To fix this, pass the path to Lua headers explicitly. For CMake: <code>-DLUA_INCLUDE_DIR=/usr/include/lua5.1</code> (adjust as needed).</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Table_Functions&diff=20402Manual:Table Functions2023-04-02T17:00:44Z<p>Kebap: /* table.contains */ Layout</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Mudlet API documentation for functions to manipulate tables. Through them you can add to tables, remove values, check if a value is present in the table, check the size of a table, and more.}}<br />
= Table Functions =<br />
These functions are used to manipulate tables. Through them you can add to tables, remove values, check if a value is present in the table, check the size of a table, and more.<br />
<br />
==spairs==<br />
; spairs(tbl, sortFunction)<br />
: Returns an iterator similar to pairs(tbl) but sorts the keys before iterating through them. <br />
<br />
; Parameters<br />
* ''tbl:''<br />
: The table to iterate over<br />
* ''sortFunction:''<br />
: The function to use for determining what order to iterate the items in the table. Defaults to alphanumeric sorting by key. Similar to [[Manual:Lua_Functions#table.sort|table.sort]]. See example for more info.<br />
<br />
{{MudletVersion|4.10}}<br />
; Example:<br />
<syntaxhighlight lang=lua><br />
local tbl = { Tom = 40, Mary = 50, Joe = 23 }<br />
<br />
-- This iterates, sorting based on the key (which is the name in this case)<br />
for name, thingies in spairs(tbl) do<br />
echo(string.format("%s has %d thingies\n", name, thingies))<br />
end<br />
--[[<br />
Joe has 23 thingies<br />
Mary has 50 thingies<br />
Tom has 40 thingies<br />
--]]<br />
<br />
-- The function used below sorts based on the value. <br />
for name, thingies in spairs(tbl, function(t,a,b) return t[a] < t[b] end) do --iterate from lowest value to highest<br />
echo(string.format("%s has %d thingies\n", name, thingies))<br />
end<br />
--[[<br />
Joe has 23 thingies<br />
Tom has 40 thingies<br />
Mary has 50 thingies<br />
--]]<br />
<br />
-- This function can be used to sort a group of Geyser gauges based on their value (what percentage of the gauge is filled)<br />
local gaugeSort = function(t,a,b)<br />
local avalue = t[a].value or 100 -- treat non-gauges as though they are full gauges. If you know for -sure- the table only has gauges the 'or 100' is not needed.<br />
local bvalue = t[b].value or 100<br />
return avalue < bvalue<br />
end<br />
for _,gauge in spairs(tblOfGauges, gaugeSort) do<br />
-- do what you want with the gauges. First one will be the least full, then the next least full, until the last which will be the most full. <br />
-- If you replace the < with a > it will go from most full to least full instead.<br />
end<br />
</syntaxhighlight><br />
<br />
==table.collect==<br />
; table.collect(tbl, func)<br />
: Returns a table that is every key-value pair from tbl for which func(key,value) returns true<br />
<br />
; Parameters<br />
* ''tbl:''<br />
: The table to collect items from<br />
* ''func:''<br />
: the function to use for testing if an item should be collected or not<br />
<br />
{{MudletVersion|4.8}}<br />
; Example:<br />
<syntaxhighlight lang=lua><br />
local vitals = { hp = 3482, maxhp = 5000, mana = 3785, maxmana = 5000 }<br />
local pullHpKeys = function(key, value)<br />
if string.match(key, "hp") then return true end<br />
end<br />
local hp_values = table.collect(vitals, pullHpKeys)<br />
display(hp_values)<br />
</syntaxhighlight><br />
This prints the following:<br />
{<br />
hp = 3482,<br />
maxhp = 5000<br />
}<br />
; Returns<br />
: A table containing all the key/value pairs from tbl that cause func(key,value) to return true<br />
<br />
==table.complement==<br />
; table.complement (set1, set2)<br />
: Returns a table that is the relative complement of the first table with respect to the second table. Returns a complement of key/value pairs.<br />
<br />
; Parameters<br />
* ''table1:''<br />
* ''table2:''<br />
<br />
; Example:<br />
<syntaxhighlight lang=lua>local t1 = {key = 1,1,2,3}<br />
local t2 = {key = 2,1,1,1}<br />
local comp = table.complement(t1,t2)<br />
display(comp)</syntaxhighlight><br />
This prints the following:<br />
key = 1,<br />
[2] = 2,<br />
[3] = 3<br />
<br />
; Returns<br />
: A table containing all the key/value pairs from table1 that do not match the key/value pairs from table2.<br />
<br />
==table.concat==<br />
;table.concat(table, delimiter, startingindex, endingindex)<br />
: Joins a table into a string. Each item must be something which can be transformed into a string. <br />
: Returns the joined string.<br />
: See also: [[Manual:Lua_Functions#string.split|string.split]]<br />
<br />
; Parameters<br />
* '''table:'''<br />
: The table to concatenate into a string. Passed as a table.<br />
* '''delimiter:'''<br />
: Optional string to use to separate each element in the joined string. Passed as a string.<br />
* '''startingindex:'''<br />
: Optional parameter to specify which index to begin the joining at. Passed as an integer.<br />
* '''endingindex:'''<br />
: Optional parameter to specify the last index to join. Passed as an integer.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
--This shows a basic concat with none of the optional arguments<br />
testTable = {1,2,"hi","blah",}<br />
testString = table.concat(testTable)<br />
--testString would be equal to "12hiblah"<br />
<br />
--This example shows the concat using the optional delimiter<br />
testString = table.concat(testTable, ", ")<br />
--testString would be equal to "1, 2, hi, blah"<br />
<br />
--This example shows the concat using the delimiter and the optional starting index<br />
testString = table.concat(testTable, ", ", 2)<br />
--testString would be equal to "2, hi, blah"<br />
<br />
--And finally, one which uses all of the arguments<br />
testString = table.concat(testTable, ", ", 2, 3)<br />
--testString would be equal to "2, hi"<br />
</syntaxhighlight><br />
<br />
==table.contains==<br />
; table.contains (t, value)<br />
: Determines if a table contains a value as a key or as a value (recursive as of Mudlet 4.8+).<br />
: Returns true or false<br />
<br />
; See also: [[Manual:Lua_Functions#table.index_of|table.index_of]]<br />
{{note}} This tests for the 'value' parameter as either a '''key''' or '''value''' in the table. That means this will return true: table.contains({"Bob"}, 1)<br />
<br />
; Parameters<br />
* '''t:''' <br />
: The table in which you are checking for the presence of the item as key or value..<br />
* '''value:''' <br />
: The value you are checking for within the table.<br />
<br />
; Example:<br />
<syntaxhighlight lang="lua">local test_table = {"value1", "value2", "value3", "value4", "value5", "value6", "value7"}<br />
if table.contains(test_table, "value1") then <br />
print("Got value 1!")<br />
else<br />
print("Don't have it. Sorry!")<br />
end<br />
<br />
-- if the table has just a few values, you can skip making a local, named table:<br />
if table.contains({"Anna", "Alanna", "Hanna"}, "Anna") then <br />
print("Have 'Anna' in the list!")<br />
else<br />
print("Don't have the name. Sorry!")<br />
end<br />
<br />
-- don't forget, it will return true if the item is a key in the table as well<br />
display(table.contains({"bob"}, 1) -- displays true, as 1 is the key/index for "bob"<br />
-- If you really only want to check values, try table.index_of, which returns the key a value is found at, or nil if it is not found.<br />
</syntaxhighlight><br />
<br />
==table.deepcopy==<br />
; table.deepcopy (table)<br />
: Returns a complete copy of the table.<br />
<br />
; Parameters<br />
* '''table:''' <br />
: The table which you'd like to get a copy of.<br />
<br />
; Example:<br />
<syntaxhighlight lang="lua">local test_table = { "value1", "value2", "value3", "value4" }<br />
<br />
-- by just doing:<br />
local newtable = test_table<br />
-- you're linking newtable to test_table. Any change in test_table will be reflected in newtable.<br />
<br />
-- however, by doing:<br />
local newtable = table.deepcopy(test_table)<br />
-- the two tables are completely separate now.<br />
</syntaxhighlight><br />
<br />
==table.intersection==<br />
; table.intersection (set1, set2)<br />
: Returns a table that is the relative intersection of the first table with respect to the second table. Returns a intersection of key/value pairs.<br />
<br />
; Parameters<br />
* ''table1:''<br />
* ''table2:''<br />
<br />
; Example:<br />
<syntaxhighlight lang=lua>local t1 = {key = 1,1,2,3}<br />
local t2 = {key = 1,1,1,1}<br />
local intersect = table.intersection(t1,t2)<br />
display(intersect)</syntaxhighlight><br />
This prints the following:<br />
key = 1,<br />
1<br />
<br />
; Returns<br />
: A table containing all the key/value pairs from table1 that match the key/value pairs from table2.<br />
<br />
==table.insert==<br />
; table.insert(table, [pos,] value)<br />
: Inserts element '''value''' at position '''pos''' in '''table''', shifting up other elements to open space, if necessary. The default '''value''' for '''pos''' is n+1, where n is the length of the table, so that a call table.insert(t,x) inserts x at the end of table t.<br />
: See also: [[Manual:Lua_Functions#table.remove|table.remove]]<br />
<br />
; Parameters<br />
* '''table:'''<br />
: The table in which you are inserting the value<br />
* '''pos:'''<br />
: Optional argument, determining where the value will be inserted. <br />
* '''value:'''<br />
: The variable that you are inserting into the table. Can be a regular variable, or even a table or function*.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
--it will inserts what inside the variable of matches[2] into at the end of table of 'test_db_name'. <br />
table.insert(test_db_name, matches[2])<br />
--it will inserts other thing at the first position of this table.<br />
table.insert(test_db_name, 1, "jgcampbell300")<br />
<br />
--[=[<br />
<br />
This results:<br />
<br />
test_db_name = {<br />
"jgcampbell300",<br />
"SlySven"<br />
}<br />
]=]<br />
<br />
</syntaxhighlight><br />
<br />
==table.index_of==<br />
; table.index_of(table, value)<br />
Returns the index (location) of an item in an indexed table, or '''nil''' if it's not found.<br />
<br />
; Parameters<br />
* '''table:'''<br />
: The table in which you are inserting the value<br />
* '''value:'''<br />
: The variable that you are searching for in the table.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- will return 1, because 'hi' is the first item in the list<br />
table.index_of({"hi", "bye", "greetings"}, "hi")<br />
<br />
-- will return 3, because 'greetings' is third in the list<br />
table.index_of({"hi", "bye", "greetings"}, "greetings")<br />
<br />
-- you can also use this in combination with table.remove(), which requires the location of the item to delete<br />
local words = {"hi", "bye", "greetings"}<br />
table.remove(words, table.index_of(words, "greetings"))<br />
<br />
-- however that won't work if the word isn't present, table.remove(mytable, nil (from table.index_of)) will give an error<br />
-- so if you're unsure, confirm with table.contains first<br />
local words = {"hi", "bye", "greetings"}<br />
if table.contains(words, "greetings") then<br />
table.remove(words, table.index_of(words, "greetings"))<br />
end<br />
</syntaxhighlight><br />
<br />
==table.is_empty==<br />
; table.is_empty(table)<br />
: Check if a table is devoid of any values.<br />
<br />
; Parameters<br />
* '''table:'''<br />
: The table you are checking for values.<br />
<br />
==table.keys==<br />
; table.keys(table)<br />
: return a table that is the collection of the keys in use by the table passed in<br />
<br />
; Parameters<br />
* '''table:'''<br />
: The table you are collecting keys from.<br />
<br />
{{MudletVersion|4.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local testTable = {<br />
name = "thing",<br />
type = "test",<br />
malfunction = "major"<br />
}<br />
local keys = table.keys(testTable)<br />
-- key is now a table { "name", "type", "malfunction" } but the order cannot be guaranteed<br />
-- as pairs() does not iterate in a guaranteed order. If you want the keys in alphabetical<br />
-- run table.sort(keys) and keys == { "malfunction", "name", "type" }<br />
</syntaxhighlight><br />
<br />
==table.load==<br />
; table.load(location, table)<br />
: Load a table from an external file into mudlet.<br />
: See also: [[Manual:Lua_Functions#table.save|table.save]]<br />
<br />
Tip: you can load a table from anywhere on your computer, but it's preferable to have them consolidated somewhere connected to Mudlet, such as the [[Manual:Lua_Functions#getMudletHomeDir|current profile]].<br />
<br />
; Parameters:<br />
* '''location:'''<br />
: Where you are loading the table from. Can be anywhere on your computer.<br />
* '''table:'''<br />
: The table that you are loading into - it must exist already.<br />
<br />
: Example:<br />
<syntaxhighlight lang="lua"><br />
-- This will load the table mytable from the lua file mytable present in your Mudlet Home Directory.<br />
mytable = mytable or {}<br />
if io.exists(getMudletHomeDir().."/mytable.lua") then<br />
table.load(getMudletHomeDir().."/mytable.lua", mytable) -- using / is OK on Windows too.<br />
end<br />
</syntaxhighlight><br />
<br />
==table.matches==<br />
;table.matches(tbl, pattern, [pattern2], [pattern_n], [check_keys])<br />
:Returns a table of key-value pairs from tbl which match one of the supplied patterns when checked via string.match. This function is not recursive - nested tables within tbl will not be checked, only the top-level.<br />
<br />
; Parameters<br />
* ''tbl:''<br />
: the table you want to check over using string.match<br />
* ''pattern:''<br />
: the pattern you want to use to check each key-value pair. You may specify multiple patterns, separated by commas<br />
* ''check_keys:''<br />
: boolean argument, set to true if you want to include a key-value pair if the key or value string.matches. If you do not set this, only the value will be checked<br />
<br />
{{MudletVersion|4.8}}<br />
; Example<br />
<syntaxhighlight lang="lua"><br />
local items = { this = "that", hp = 400, [4] = "toast", something = "else", more = "keypairs" }<br />
local matches = table.matches(items, "%d")<br />
-- here matches will be { hp = 400 }<br />
local matches = table.matches(items, "%d", "that", true)<br />
-- here matches will be { hp = 400, this = "that", [4] = "toast" }<br />
</syntaxhighlight><br />
<br />
==table.maxn==<br />
;table.maxn(table)<br />
:Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.)<br />
<br />
==table.n_collect==<br />
; table.n_collect(tbl, func(value))<br />
: returns a table which contains every unique value from tbl for which func(value) returns true. Ignores keys. Table returned is ipairs iterable.<br />
<br />
; Parameters<br />
* ''tbl:''<br />
: the table you want to collect values from<br />
* ''func(value):''<br />
: the function to check each value against<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
; Example<br />
<syntaxhighlight lang="lua"><br />
local items = { <br />
this = "that",<br />
other = "thing",<br />
otter = "potato",<br />
honey = "bee"<br />
}<br />
local beginsWithTH = function(value)<br />
if string.match(value, "^th") then return true end<br />
end<br />
local nmatches = table.n_collect(items, beginsWithTH)<br />
-- nmatches will be { "that", "thing" }<br />
-- the order will not necessarily be preserved<br />
</syntaxhighlight><br />
<br />
==table.n_filter==<br />
; table.n_filter(table, function(element[, index[, table]]))<br />
: Returns a new table with all elements that pass the test implemented by the provided function. If no elements pass the test, an empty table will be returned.<br />
<br />
; Parameters<br />
* ''table:'' the table you wish to filter values out of.<br />
* ''function:'' the function to test each element of the array. Return true to keep the element, false otherwise. It accepts three arguments:<br />
** ''element:'' The current element being processed in the table.<br />
** ''index:'' (optional) The index of the current element being processed in the table.<br />
** ''table:'' (optional) The table '''n_filter''' was called upon.<br />
<br />
; Examples:<br />
Filter out small values:<br />
<syntaxhighlight lang="lua"><br />
local function isBigEnough(value) return value >= 10 end<br />
local filtered = table.n_filter({12, 5, 8, 130, 44}, isBigEnough)<br />
-- filtered: {12, 130, 44}<br />
</syntaxhighlight><br />
Filter out invalid entries:<br />
<syntaxhighlight lang="lua"><br />
local invalidEntries = 0<br />
local entries = {<br />
{ id = 15 }, { id = -1 }, { id = 0 }, { id = 3 },<br />
{ id = 12.2 }, { }, { id = nil }, { id = false },<br />
{ id = 'not a number' }<br />
}<br />
<br />
local function isNumber(t) return t and type(t) == 'number' end<br />
local function filterByID(item)<br />
if isNumber(item.id) and item.id ~= 0 then<br />
return true<br />
end<br />
invalidEntries = invalidEntries + 1<br />
return false<br />
end<br />
<br />
local entriesByID = table.n_filter(entries, filterByID)<br />
-- invalidEntries: 5<br />
-- entriesByID: { { id = 15 }, { id = -1 }, { id = 3 }, { id = 12.2 } }<br />
</syntaxhighlight><br />
Filter out content based on search criteria:<br />
<syntaxhighlight lang="lua"><br />
local fruits = {'apple', 'banana', 'grapes', 'mango', 'orange'}<br />
local function filterItems(t, query)<br />
return table.n_filter(t, function(item)<br />
return item:lower():find(query:lower())<br />
end)<br />
end<br />
filterItems(fruits, 'ap') -- {'apple', 'grapes'}<br />
filterItems(fruits, 'an') -- {'banana', 'mango', 'orange'}<br />
</syntaxhighlight><br />
<br />
==table.n_flatten==<br />
; table.n_flatten(table)<br />
: Returns a new table with the sub-table elements concatenated into it.<br />
<br />
; Parameters<br />
* ''table:'' A table of nested sub-tables you wish to flatten.<br />
<br />
; Example:<br />
<syntaxhighlight lang="lua"><br />
local t1 = {1, 2, {3, 4}};<br />
local t2 = {1, 2, {3, 4, {5, 6}}};<br />
local t3 = {1, 2, {3, 4, {5, 6, {7, 8, {9, 10}}}}};<br />
table.n_flatten(t1) -- {1, 2, 3, 4}<br />
table.n_flatten(t2) -- {1, 2, 3, 4, 5, 6}<br />
table.n_flatten(t3) -- {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}<br />
</syntaxhighlight><br />
<br />
==table.n_matches==<br />
; table.n_matches(tbl, pattern, [pattern2], [patternN])<br />
: Returns a table of unique values within tbl which one of the supplied patterns matches using string.match<br />
<br />
; Parameters<br />
* ''tbl:''<br />
: The table you want to search for values<br />
* ''pattern:''<br />
: The pattern you want to check each value with, using string.match. You can supply multiple patterns, separated by commas<br />
{{MudletVersion|4.8}}<br />
<br />
; Example<br />
<syntaxhighlight lang="lua"><br />
local items = { this = "that", [4] = "other", hp = 500, mana = 40 }<br />
local matches = table.n_matches(items, "%a")<br />
-- matches will be { "that", "other" }<br />
-- order is not preserved/guaranteed<br />
</syntaxhighlight><br />
<br />
==table.n_union==<br />
; table.n_union (table1, table2)<br />
: Returns a numerically indexed table that is the union of the provided tables (that is - merges two indexed lists together). This is a union of unique values. The order and keys of the input tables are not preserved.<br />
<br />
; Parameters<br />
* ''table1:'' the first table as an indexed list.<br />
* ''table2:'' the second table as an indexed list.<br />
<br />
; Example:<br />
<syntaxhighlight lang="lua"><br />
display(table.n_union({"bob", "mary"}, {"august", "justinian"}))<br />
<br />
{<br />
"bob",<br />
"mary",<br />
"august",<br />
"justinian"<br />
}<br />
</syntaxhighlight><br />
<br />
==table.n_complement==<br />
; table.n_complement (set1, set2)<br />
: Returns a table that is the relative complement of the first numerically indexed table with respect to the second numerically indexed table. Returns a numerically indexed complement of values.<br />
<br />
; Parameters<br />
* ''table1:''<br />
* ''table2:''<br />
<br />
; Example:<br />
<syntaxhighlight lang=lua>local t1 = {1,2,3,4,5,6}<br />
local t2 = {2,4,6}<br />
local comp = table.n_complement(t1,t2)<br />
display(comp)</syntaxhighlight><br />
This prints the following:<br />
1,<br />
3,<br />
5<br />
<br />
; Returns<br />
: A table containing all the values from table1 that do not match the values from table2.<br />
<br />
==table.n_intersection==<br />
; table.n_intersection (...)<br />
: Returns a numerically indexed table that is the intersection of the provided tables. This is an intersection of unique values. The order and keys of the input tables are not preserved<br />
<br />
; Example:<br />
<syntaxhighlight lang=lua>local t1 = {1,2,3,4,5,6}<br />
local t2 = {2,4,6}<br />
local intersect = table.n_intersection(t1,t2)<br />
display(intersect)</syntaxhighlight><br />
This prints the following:<br />
2,<br />
4,<br />
6<br />
<br />
; Returns<br />
: A table containing the values that are found in every one of the tables.<br />
<br />
==table.pickle==<br />
;table.pickle( t, file, tables, lookup )<br />
: Internal function used by table.save() for serializing data.<br />
<br />
==table.remove==<br />
; table.remove(table, value_position)<br />
: Remove a value from an indexed table, by the values position in the table.<br />
: See also: [[Manual:Lua_Functions#table.insert|table.insert]]<br />
<br />
; Parameters:<br />
* '''table'''<br />
: The indexed table you are removing the value from.<br />
* '''value_position'''<br />
: The indexed number for the value you are removing.<br />
<br />
; Example:<br />
<syntaxhighlight lang="lua"><br />
testTable = { "hi", "bye", "cry", "why" }<br />
table.remove(testTable, 1) -- will remove hi from the table<br />
-- new testTable after the remove<br />
testTable = { "bye", "cry", "why" }<br />
-- original position of hi was 1, after the remove, position 1 has become bye<br />
-- any values under the removed value are moved up, 5 becomes 4, 4 becomes 3, etc<br />
</syntaxhighlight> <br />
{{note}} To remove a value from a key-value table, it's best to simply change the value to nil.<br />
<syntaxhighlight lang="lua"><br />
testTable = { test = "testing", go = "boom", frown = "glow" }<br />
table.remove(testTable, test) -- this will error<br />
testTable.test = nil -- won't error<br />
testTable["test"] = nil -- won't error<br />
</syntaxhighlight><br />
<br />
==table.save==<br />
; table.save(location, table)<br />
: Save a table into an external file in '''location'''.<br />
: See also: [[Manual:Lua_Functions#table.load|table.load]]<br />
<br />
; Parameters:<br />
* '''location:'''<br />
: Where you want the table file to be saved. Can be anywhere on your computer.<br />
* '''table:'''<br />
: The table that you are saving to the file.<br />
<br />
: Example:<br />
<syntaxhighlight lang="lua"><br />
-- Saves the table mytable to the lua file mytable in your Mudlet Home Directory<br />
table.save(getMudletHomeDir().."/mytable.lua", mytable)<br />
</syntaxhighlight><br />
==table.sort==<br />
;table.sort(Table [, comp])<br />
:Sorts table elements in a given order, in-place, from <code>Table[1]</code> to <code>Table[n]</code>, where <code>n</code> is the length of the table. <br />
<br />
:If <code>comp</code> is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not <code>comp(a[i+1],a[i])</code> will be true after the sort). If <code>comp</code> is not given, then the standard Lua operator <code><</code> is used instead.<br />
<br />
:The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.<br />
<br />
:See https://www.lua.org/pil/19.3.html for more info<br />
<br />
==table.size==<br />
; table.size (t)<br />
: Returns the size of a key-value table (this function has to iterate through all of the table to count all elements).<br />
: Returns a number.<br />
<br />
; Parameters<br />
* ''t:'' <br />
: The table you are checking the size of.<br />
{{note}}<br />
For index based tables you can get the size with the # operator:<br />
This is the standard Lua way of getting the size of index tables i.e. ipairs() type of tables with numerical indices. <br />
To get the size of tables that use user defined keys instead of automatic indices (pairs() type) you need to use the function table.size() referenced above.<br />
<syntaxhighlight lang="lua"><br />
local test_table = { "value1", "value2", "value3", "value4" }<br />
myTableSize = #test_table<br />
-- This would return 4.<br />
local myTable = { 1 = "hello", "key2" = "bye", "key3" = "time to go" }<br />
table.size(myTable)<br />
-- This would return 3.<br />
</syntaxhighlight><br />
<br />
==table.unpickle==<br />
;table.unpickle( t, tables, tcopy, pickled )<br />
: Internal function used by table.load() for deserialization.<br />
<br />
==table.update==<br />
;table.update(table1, table2)<br />
: Returns a table in which key/value pairs from table2 are added to table1, and any keys present in both tables are assigned the value from table2, so that the resulting table is table1 updated with information from table2.<br />
<br />
;Example<br />
<syntaxhighlight lang=lua>display(table.update({a = 1, b = 2, c = 3}, {b = 4, d = 5}))<br />
{<br />
a = 1,<br />
b = 4,<br />
c = 3,<br />
d = 5<br />
}<br />
<br />
-- to just set a table to new values, assign it directly:<br />
mytable = {key1 = "newvalue"}<br />
</syntaxhighlight><br />
<br />
==table.union==<br />
;table.union(...)<br />
: Returns a table that is the union of the provided tables. This is a union of key/value pairs. If two or more tables contain different values associated with the same key, that key in the returned table will contain a subtable containing all relevant values. See table.n_union() for a union of values. Note that the resulting table may not be reliably traversable with ipairs() due to the fact that it preserves keys. If there is a gap in numerical indices, ipairs() will cease traversal.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
tableA = {<br />
[1] = 123,<br />
[2] = 456,<br />
["test"] = "test",<br />
}<br />
---<br />
tableB = {<br />
[1] = 23,<br />
[3] = 7,<br />
["test2"] = function() return true end,<br />
}<br />
---<br />
tableC = {<br />
[5] = "c",<br />
}<br />
---<br />
table.union(tableA, tableB, tableC)<br />
-- will return the following:<br />
{<br />
[1] = {<br />
123,<br />
23,<br />
},<br />
[2] = 456,<br />
[3] = 7,<br />
[5] = "c",<br />
["test"] = "test",<br />
["test2"] = function() return true end,<br />
}<br />
</syntaxhighlight><br />
<br />
[[Category:Mudlet Manual]]<br />
[[Category:Mudlet API]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Miscellaneous_Functions&diff=20397Manual:Miscellaneous Functions2023-04-02T01:30:08Z<p>Kebap: /* setConfig */ extract default values into own column</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Mudlet API documentation for miscellaneous functions.}}<br />
= Miscellaneous Functions =<br />
<br />
==addFileWatch==<br />
;addFileWatch(path)<br />
:Adds file watch on directory or file. Every change in that file (or directory) will raise [[Manual:Event_Engine#sysPathChanged|sysPathChanged]] event.<br />
<br />
:See also: [[#removeFileWatch|removeFileWatch()]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", "herbsChangedHandler")<br />
</syntaxhighlight><br />
<br />
==addSupportedTelnetOption==<br />
;addSupportedTelnetOption(option)<br />
:Adds a telnet option, which when queried by a game server, Mudlet will return DO (253) on. Use this to register the telnet option that you will be adding support for with Mudlet - see [[Manual:Supported_Protocols#Adding_support_for_a_telnet_protocol|additional protocols]] section for more.<br />
<br />
;Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
<event handlers that add support for MSDP... see http://www.mudbytes.net/forum/comment/63920/#c63920 for an example><br />
<br />
-- register with Mudlet that it should not decline the request of MSDP support<br />
local TN_MSDP = 69<br />
addSupportedTelnetOption(TN_MSDP)<br />
</syntaxhighlight><br />
<br />
==alert==<br />
;alert([seconds])<br />
:alerts the user to something happening - makes Mudlet flash in the Windows window bar, bounce in the macOS dock, or flash on Linux.<br />
<br />
{{MudletVersion|3.2}}<br />
<br />
;Parameters<br />
* ''seconds:''<br />
:(optional) number of seconds to have the alert for. If not provided, Mudlet will flash until the user opens Mudlet again.<br />
<br />
;Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- flash indefinitely until Mudlet is open<br />
alert()<br />
<br />
-- flash for just 3 seconds<br />
alert(3)<br />
</syntaxhighlight><br />
<br />
==cfeedTriggers==<br />
;cfeedTriggers(text)<br />
:Like feedTriggers, but you can add color information using color names, similar to cecho.<br />
<br />
;Parameters<br />
* ''text'': The string to feed to the trigger engine. Include colors by name as black,red,green,yellow,blue,magenta,cyan,white and light_* versions of same. You can also use a number to get the ansi color corresponding to that number.<br />
:See also: [[#feedTriggers|feedTriggers]]<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
cfeedTriggers("<green:red>green on red<r> reset <124:100> foreground of ANSI124 and background of ANSI100<r>\n")<br />
</syntaxhighlight><br />
<br />
==closeMudlet==<br />
;closeMudlet()<br />
<br />
:Closes Mudlet and all profiles immediately.<br />
:See also: [[Manual:Lua_Functions#saveProfile|saveProfile()]]<br />
<br />
{{note}} Use with care. This potentially lead to data loss, if "save on close" is not activated and the user didn't save the profile manually as this will NOT ask for confirmation nor will the profile be saved. Also it does not consider if there are ''other'' profiles open if multi-playing: they '''all''' will be closed!<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
closeMudlet()<br />
</syntaxhighlight><br />
<br />
==deleteAllNamedEventHandlers==<br />
; deleteAllNamedEventHandlers(userName)<br />
<br />
:Deletes all named event handlers for userName and prevents them from firing any more. Information is deleted and cannot be retrieved.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteAllNamedEventHandlers("Demonnic") -- emergency stop or debugging situation, most likely.<br />
</syntaxhighlight><br />
<br />
==deleteNamedEventHandler==<br />
; success = deleteNamedEventHandler(userName, handlerName)<br />
<br />
:Deletes a named event handler with name handlerName and prevents it from firing any more. Information is deleted and cannot be retrieved.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to stop. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local deleted = deleteNamedEventHandler("Demonnic", "Vitals")<br />
if deleted then<br />
cecho("Vitals deleted forever!!")<br />
else<br />
cecho("Vitals doesn't exist and so could not be deleted.")<br />
end<br />
</syntaxhighlight><br />
<br />
==denyCurrentSend==<br />
;denyCurrentSend()<br />
<br />
:Cancels a [[Manual:Lua_Functions#send|send()]] or user-entered command, but only if used within a [[Manual:Event_Engine#sysDataSendRequest|sysDataSendRequest]] event.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- cancels all "eat hambuger" commands<br />
function cancelEatHamburger(event, command)<br />
if command == "eat hamburger" then<br />
denyCurrentSend()<br />
cecho("<red>Denied! Didn't let the command through.\n")<br />
end<br />
end<br />
<br />
registerAnonymousEventHandler("sysDataSendRequest", "cancelEatHamburger")<br />
</syntaxhighlight><br />
<br />
==dfeedTriggers==<br />
;dfeedTriggers(str)<br />
:Like feedTriggers, but you can add color information using <r,g,b>, similar to decho.<br />
<br />
;Parameters<br />
* ''str'': The string to feed to the trigger engine. Include color information inside tags like decho.<br />
;See also: [[Manual:Lua_Functions#cfeedTriggers|cfeedTriggers]], [[Manual:Lua_Functions#decho|decho]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
dfeedTriggers("<0,128,0:128,0,0>green on red<r> reset\n")<br />
</syntaxhighlight><br />
<br />
==disableModuleSync==<br />
;disableModuleSync(name)<br />
: Stops syncing the given module.<br />
<br />
;Parameter<br />
* ''name'': name of the module.<br />
<br />
:See also: [[Manual:Lua_Functions#enableModuleSync|enableModuleSync()]], [[Manual:Lua_Functions#getModuleSync|getModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==enableModuleSync==<br />
;enableModuleSync(name)<br />
: Enables the sync for the given module name - any changes done to it will be saved to disk and if the module is installed in any other profile(s), it'll be updated in them as well on profile save.<br />
<br />
;Parameter<br />
* ''name'': name of the module to enable sync on.<br />
<br />
:See also: [[Manual:Lua_Functions#disableModuleSync|disableModuleSync()]], [[Manual:Lua_Functions#getModuleSync|getModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==expandAlias==<br />
;expandAlias(command, [echoBackToBuffer])<br />
:Runs the command as if it was from the command line - so aliases are checked and if none match, it's sent to the game unchanged. <br />
<br />
;Parameters<br />
* ''command''<br />
: Text of the command you want to send to the game. Will be checked for aliases.<br />
* ''echoBackToBuffer''<br />
: (optional) If ''false'', the command will not be echoed back in your buffer. Defaults to ''true'' if omitted.<br />
<br />
{{note}} Using expandAlias is not recommended anymore as it is not very robust and may lead to problems down the road. The recommendation is to use lua functions instead. See [[Manual:Functions_vs_expandAlias]] for details and examples.<br />
<br />
{{note}} If you want to be using the ''matches'' table after calling ''expandAlias'', you should save it first, as, e.g. ''local oldmatches = matches'' before calling ''expandAlias'', since ''expandAlias'' will overwrite it after using it again.<br />
<br />
{{note}} Since '''Mudlet 3.17.1''' the optional second argument to echo the command on screen will be ineffective whilst the game server has negotiated the telnet ECHO option to provide the echoing of text we ''send'' to him.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
expandAlias("t rat")<br />
<br />
-- don't echo the command<br />
expandAlias("t rat", false)<br />
</syntaxhighlight><br />
<br />
==feedTriggers==<br />
;feedTriggers(text[, dataIsUtf8Encoded = true])<br />
:This function will have Mudlet parse the given text as if it came from the game - one great application is trigger testing. The built-in '''`echo''' alias provides this functionality as well.<br />
<br />
;Parameters<br />
* ''text:''<br />
:string which is sent to the trigger processing system almost as if it came from the game server. This string must be byte encoded in a manner to match the currently selected ''Server Encoding''. <br />
* ''dataIsUtf8Encoded'' (available in Mudlet 4.2+):<br />
:Set this to false, if you need pre-Mudlet 4.0 behavior. Most players won't need this.<br />
:(Before Mudlet 4.0 the text had to be encoded directly in whatever encoding the setting in the preferences was set to. <br />
:(Encoding could involve using the Lua string character escaping mechanism of \ and a base 10 number for character codes from \1 up to \255 at maximum)<br />
:Since Mudlet 4.0 it is assumed that the text is UTF-8 encoded. It will then be automatically converted to the currently selected game server encoding.<br />
:Preventing the automatic conversion can be useful to Mudlet developers testing things, or possibly to those who are creating handlers for Telnet protocols within the Lua subsystem, who need to avoid the transcoding of individual protocol bytes, when they might otherwise be seen as extended ASCII characters.)<br />
<br />
;Returns (available in Mudlet 4.2+):<br />
* ''true'' on success, ''nil'' and an error message if the text contains characters that cannot be conveyed by the current Game Server encoding.<br />
<br />
{{note}} It is important to ensure that in Mudlet 4.0.0 and beyond the text data only contains characters that can be encoded in the current Game Server encoding, from 4.2.0 the content is checked that it can successfully be converted from the UTF-8 that the Mudlet Lua subsystem uses internally into that particular encoding and if it cannot the function call will fail and not pass any of the data, this will be significant if the text component contains any characters that are not plain ASCII.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- try using this on the command line<br />
`echo This is a sample line from the game<br />
<br />
-- You can use \n to represent a new line - you also want to use it before and after the text you’re testing, like so:<br />
feedTriggers("\nYou sit yourself down.\n")<br />
<br />
-- The function also accept ANSI color codes that are used in games. A sample table can be found http://codeworld.wikidot.com/ansicolorcodes<br />
feedTriggers("\nThis is \27[1;32mgreen\27[0;37m, \27[1;31mred\27[0;37m, \27[46mcyan background\27[0;37m," ..<br />
"\27[32;47mwhite background and green foreground\27[0;37m.\n")<br />
</syntaxhighlight><br />
<br />
==getCharacterName==<br />
;getCharacterName()<br />
<br />
:Returns the name entered into the "Character name" field on the Connection Preferences form. Can be used to find out the name that might need to be handled specially in scripts or anything that needs to be personalized to the player. If there is nothing set in that entry will return an empty string.<br />
<br />
:See also: [[#getProfileName|getProfileName()]]<br />
<br />
{{MudletVersion|4.16}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- cast glamor on yourself<br />
<br />
send("cast 'glamor' " .. getCharacterName())<br />
</syntaxhighlight><br />
<br />
==getConfig ==<br />
;getConfig([option])<br />
<br />
: Returns configuration options similar to those that can be set with setConfig. One could use this to decide if a script should notify the user of suggested changes.<br />
See also: [[Manual:Miscellaneous_Functions#setConfig|setConfig()]]<br />
<br />
{{MudletVersion|4.17}}<br />
<br />
;Parameters<br />
*''option:''<br />
:Particular option to retrieve - see list below for available ones. This may be a string or an array of strings.<br />
<br />
{| class="wikitable sortable"<br />
|+General options<br />
|-<br />
!Option!!Description!!Available in Mudlet<br />
|-<br />
|enableGMCP||Enable GMCP||4.17<br />
|-<br />
|enableMSDP||Enable MSDP||4.17<br />
|-<br />
|enableMSSP||Enable MSSP||4.17<br />
|-<br />
|enableMSP|| Enable MSP||4.17<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+Input line<br />
|-<br />
!Option!!Description!!Available in Mudlet<br />
|-<br />
|inputLineStrictUnixEndings||Workaround option to use strict UNIX line endings for sending commands||4.17<br />
|-<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+Main display<br />
|-<br />
!Option!!Description!!Available in Mudlet<br />
|-<br />
|fixUnnecessaryLinebreaks||Remove extra linebreaks from output (mostly for IRE servers) || 4.17<br />
|-<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+Mapper options<br />
|-<br />
!Option!!Description!!Available in Mudlet<br />
|-<br />
|mapRoomSize||Size of rooms on map||4.17<br />
|-<br />
|mapExitSize||Size of exits on map||4.17<br />
|-<br />
|mapRoundRooms||Draw rooms round or square||4.17<br />
|-<br />
|showRoomIdsOnMap||Show room IDs on all rooms||4.17<br />
|-<br />
|show3dMapView||Show map as 3D||4.17<br />
|-<br />
|mapperPanelVisible||Map controls at the bottom||4.17<br />
|-<br />
|mapShowRoomBorders|| Draw a thin border for every room||4.17<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+Special options<br />
|-<br />
!Option!!Description!!Available in Mudlet<br />
|-<br />
|specialForceCompressionOff|| Workaround option to disable MCCP compression, in case the game server is not working correctly||4.17<br />
|-<br />
|specialForceGAOff||Workaround option to disable Telnet Go-Ahead, in case the game server is not working correctly||4.17<br />
|-<br />
|specialForceCharsetNegotiationOff||Workaround option to disable automatically setting the correct encoding, in case the game server is not working correctly||4.17<br />
|-<br />
|specialForceMxpNegotiationOff|| Workaround option to disable MXP, in case the game server is not working correctly ||4.17<br />
|-<br />
|caretShortcut||For visually-impaired players - get the key to switch between input line and main window (can be "none", "tab", "ctrltab", "f6")|| 4.17<br />
|-<br />
|blankLinesBehaviour||For visually impaired players options for dealing with blank lines (can be "show", "hide", "replacewithspace")||4.17<br />
|}<br />
<br />
;Returns<br />
*It returns a table of options or the value of a single option requested. They are only the configuration options, for example "enableGMCP" means that the "Enable GMCP" box is checked and does not mean that it has been negotiated with the server.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getConfig()<br />
<br />
-- Suggest enabling GMCP if it is unchecked<br />
if not getConfig("enableGMCP") then<br />
echo("\nMy script works best with GMCP enabled. You may ")<br />
cechoLink("<red>click here", function() setConfig("enableGMCP",true) echo("GMCP enabled\n") end, "Enable GMCP", true)<br />
echo(" to enable it.\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==getModulePath==<br />
;path = getModulePath(module name)<br />
<br />
:Returns the location of a module on the disk. If the given name does not correspond to an installed module, it'll return <code>nil</code><br />
:See also: [[Manual:Lua_Functions#installModule|installModule()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModulePath("mudlet-mapper")<br />
</syntaxhighlight><br />
<br />
==getModulePriority==<br />
;priority = getModulePriority(module name)<br />
<br />
:Returns the priority of a module as an integer. This determines the order modules will be loaded in - default is 0. Useful if you have a module that depends on another module being loaded first, for example.<br />
:Modules with priority <code>-1</code> will be loaded before scripts (Mudlet 4.11+).<br />
<br />
:See also: [[Manual:Lua_Functions#setModulePriority|setModulePriority()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModulePriority("mudlet-mapper")<br />
</syntaxhighlight><br />
<br />
==getModules==<br />
;getModules()<br />
<br />
:Returns installed modules as table.<br />
<br />
:See also: [[#getPackages|getPackages]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Check if the module myTabChat is installed and if it isn't install it and enable sync on it<br />
if not table.contains(getModules(),"myTabChat") then<br />
installModule(getMudletHomeDir().."/modules/myTabChat.xml")<br />
enableModuleSync("myTabChat")<br />
end<br />
<br />
</syntaxhighlight><br />
<br />
==getModuleInfo==<br />
;getModuleInfo(moduleName, [info])<br />
<br />
:Returns table with meta information for a package<br />
<br />
;Parameters<br />
* ''moduleName:''<br />
:Name of the package<br />
* ''info:''<br />
:(optional) specific info wanted to get, if not given all available meta-info is returned<br />
<br />
:See also: [[#getPackageInfo|getPackageInfo]], [[#setModuleInfo|setModuleInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModuleInfo("myModule","author")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==getModuleSync==<br />
;getModuleSync(name)<br />
: returns false if module sync is not active, true if it is active and nil if module is not found.<br />
<br />
;Parameter<br />
* ''name'': name of the module<br />
<br />
:See also: [[Manual:Lua_Functions#enableModuleSync|enableModuleSync()]], [[Manual:Lua_Functions#disableModuleSync|disableModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==getMudletHomeDir==<br />
;getMudletHomeDir()<br />
:Returns the current home directory of the current profile. This can be used to store data, save statistical information, or load resource files from packages.<br />
<br />
{{note}} intentionally uses forward slashes <code>/</code> as separators on Windows since [[Manual:UI_Functions#setLabelStyleSheet|stylesheets]] require them.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- save a table<br />
table.save(getMudletHomeDir().."/myinfo.dat", myinfo)<br />
<br />
-- or access package data. The forward slash works even on Windows fine<br />
local path = getMudletHomeDir().."/mypackagename"<br />
</syntaxhighlight><br />
<br />
==getMudletInfo==<br />
;getMudletInfo()<br />
:Prints debugging information about the Mudlet that you're running - this can come in handy for diagnostics.<br />
<br />
Don't use this command in your scripts to find out if certain features are supported in Mudlet - there are better functions available for this.<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getMudletInfo()<br />
</syntaxhighlight><br />
<br />
==getMudletVersion==<br />
;getMudletVersion(style)<br />
:Returns the current Mudlet version. Note that you shouldn't hardcode against a specific Mudlet version if you'd like to see if a function is present - instead, check for the existence of the function itself. Otherwise, checking for the version can come in handy if you'd like to test for a broken function or so on.<br />
<br />
See also: [[#mudletOlderThan|mudletOlderThan()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Parameters<br />
* ''style:''<br />
:(optional) allows you to choose what you'd like returned. By default, if you don't specify it, a key-value table with all the values will be returned: major version, minor version, revision number and the optional build name.<br />
<br />
;Values you can choose<br />
* ''"string"'':<br />
:Returns the full Mudlet version as text.<br />
* ''"table"'':<br />
:Returns the full Mudlet version as four values (multi-return)<br />
* ''"major"'':<br />
:Returns the major version number (the first one).<br />
* ''"minor"'':<br />
:Returns the minor version number (the second one).<br />
* ''"revision"'':<br />
:Returns the revision version number (the third one).<br />
* ''"build"'':<br />
:Returns the build of Mudlet (the ending suffix, if any).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- see the full Mudlet version as text:<br />
getMudletVersion("string")<br />
-- returns for example "3.0.0-alpha"<br />
<br />
-- check that the major Mudlet version is at least 3:<br />
if getMudletVersion("major") >= 3 then echo("You're running on Mudlet 3+!") end<br />
-- but mudletOlderThan() is much better for this:<br />
if mudletOlderThan(3) then echo("You're running on Mudlet 3+!") end <br />
<br />
-- if you'd like to see if a function is available however, test for it explicitly instead:<br />
if setAppStyleSheet then<br />
-- example credit to http://qt-project.org/doc/qt-4.8/stylesheet-examples.html#customizing-qscrollbar<br />
setAppStyleSheet[[<br />
QScrollBar:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
width: 15px;<br />
margin: 22px 0 22px 0;<br />
}<br />
QScrollBar::handle:vertical {<br />
background: white;<br />
min-height: 20px;<br />
}<br />
QScrollBar::add-line:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
height: 20px;<br />
subcontrol-position: bottom;<br />
subcontrol-origin: margin;<br />
}<br />
QScrollBar::sub-line:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
height: 20px;<br />
subcontrol-position: top;<br />
subcontrol-origin: margin;<br />
}<br />
QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {<br />
border: 2px solid grey;<br />
width: 3px;<br />
height: 3px;<br />
background: white;<br />
}<br />
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {<br />
background: none;<br />
}<br />
]]<br />
end<br />
</syntaxhighlight><br />
<br />
==getNewIDManager==<br />
; getNewIDManager()<br />
<br />
:Returns an IDManager object, for manager your own set of named events and timers isolated from the rest of the profile.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
{{note}} Full IDManager usage can be found at [[Manual:IDManager|IDManager]]<br />
<br />
;Returns<br />
* an IDManager for managing your own named events and timers<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
demonnic = demonnic or {}<br />
demonnic.IDManager = getNewIDManager()<br />
local idm = demonnic.IDManager<br />
-- assumes you have defined demonnic.vitalsUpdate and demonnic.balanceChecker as functions<br />
idm:registerEvent("DemonVitals", "gmcp.Char.Vitals", demonnic.vitalsUpdate)<br />
idm:registerTimer("Balance Check", 1, demonnic.balanceChecker)<br />
idm:stopEvent("DemonVitals")<br />
</syntaxhighlight><br />
<br />
==getNamedEventHandlers==<br />
; handlers = getNamedEventHandlers(userName)<br />
<br />
:Returns a list of all userName's named event handlers' names as a table.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Returns <br />
* a table of handler names. { "DemonVitals", "DemonInv" } for example. {} if none are registered<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local handlers = getNamedEventHandlers()<br />
display(handlers)<br />
-- {}<br />
registerNamedEventHandler("Test1", "testEvent", "testFunction")<br />
registerNamedEventHandler("Test2", "someOtherEvent", myHandlerFunction)<br />
handlers = getNamedEventHandlers()<br />
display(handlers)<br />
-- { "Test1", "Test2" }<br />
</syntaxhighlight><br />
<br />
==getOS==<br />
;getOS()<br />
<br />
:Returns the name of the Operating System (OS). Useful for applying particular scripts only under particular operating systems, such as applying a stylesheet only when the OS is Windows. <br />
:Returned text will be one of these: "windows", "mac", "linux", as well as "cygwin", "hurd", "freebsd", "kfreebsd", "openbsd", "netbsd", "bsd4", "unix" or "unknown" otherwise.<br />
:Additionally returns the version of the OS, and if using Linux, the distribution in use (as of Mudlet 4.12+).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getOS())<br />
<br />
if getOS() == "windows" then<br />
echo("\nWindows OS detected.\n")<br />
else<br />
echo("\nDetected Operating system is NOT windows.\n")<br />
end<br />
<br />
if mudlet.supports.osVersion then<br />
local os, osversion = getOS()<br />
print(f"Running {os} {osversion}")<br />
end<br />
</syntaxhighlight><br />
<br />
==getPackages==<br />
;getPackages()<br />
<br />
:Returns installed packages as table.<br />
<br />
:See also: [[#getModules|getModules]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Check if the generic_mapper package is installed and if so uninstall it<br />
if table.contains(getPackages(),"generic_mapper") then<br />
uninstallPackage("generic_mapper")<br />
end<br />
<br />
</syntaxhighlight><br />
<br />
==getPackageInfo==<br />
;getPackageInfo(packageName, [info])<br />
<br />
:Returns table with meta information for a package<br />
<br />
;Parameters<br />
* ''packageName:''<br />
:Name of the package<br />
* ''info:''<br />
:(optional) specific info wanted to get, if not given all available meta-info is returned<br />
<br />
:See also: [[#getModuleInfo|getModuleInfo]], [[#setPackageInfo|setPackageInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getPackageInfo("myPackage", "version")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==getProfileName==<br />
;getProfileName()<br />
<br />
:Returns the name of the profile. Useful when combined with [[Manual:Mudlet_Object_Functions#raiseGlobalEvent|raiseGlobalEvent()]] to know which profile a global event came from.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- if connected to the Achaea profile, will print Achaea to the main console<br />
echo(getProfileName())<br />
</syntaxhighlight><br />
<br />
==getCommandSeparator==<br />
;getCommandSeparator()<br />
<br />
:Returns the command separator in use by the profile.<br />
<br />
{{MudletVersion|3.18}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- if your command separator is ;;, the following would send("do thing 1;;do thing 2"). <br />
-- This way you can determine what it is set to and use that and share this script with <br />
-- someone who has changed their command separator.<br />
-- Note: This is not really the preferred way to send this, using sendAll("do thing 1", "do thing 2") is,<br />
-- but this illustates the use case.<br />
local s = getCommandSeparator()<br />
expandAlias("do thing 1" .. s .. "do thing 2")<br />
</syntaxhighlight><br />
<br />
==getServerEncoding==<br />
;getServerEncoding()<br />
:Returns the current server [https://www.w3.org/International/questions/qa-what-is-encoding data encoding] in use.<br />
<br />
:See also: [[#setServerEncoding|setServerEncoding()]], [[#getServerEncodingsList|getServerEncodingsList()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getServerEncoding()<br />
</syntaxhighlight><br />
<br />
==getServerEncodingsList==<br />
;getServerEncodingsList()<br />
:Returns an indexed list of the server [https://www.w3.org/International/questions/qa-what-is-encoding data encodings] that Mudlet knows. This is not the list of encodings the servers knows - there's unfortunately no agreed standard for checking that. See [[Manual:Unicode#Changing_encoding|encodings in Mudlet]] for the list of which encodings are available in which Mudlet version.<br />
<br />
:See also: [[#setServerEncoding|setServerEncoding()]], [[#getServerEncoding|getServerEncoding()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- check if UTF-8 is available:<br />
if table.contains(getServerEncodingsList(), "UTF-8") then<br />
print("UTF-8 is available!")<br />
end<br />
</syntaxhighlight><br />
<br />
==getWindowsCodepage==<br />
;getWindowsCodepage()<br />
:Returns the current [https://docs.microsoft.com/en-us/windows/desktop/Intl/code-page-identifiers codepage] of your Windows system.<br />
<br />
{{MudletVersion|3.22}}<br />
{{Note}} This function only works on Windows - It is only needed internally in Mudlet to enable Lua to work with non-ASCII usernames (e.g. Iksiński, Jäger) for the purposes of IO. Linux and macOS work fine with with these out of the box.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
print(getWindowsCodepage())<br />
</syntaxhighlight><br />
<br />
==hfeedTriggers==<br />
;hfeedTriggers(str)<br />
:Like feedTriggers, but you can add color information using #RRGGBB in hex, similar to hecho.<br />
<br />
;Parameters<br />
* ''str'': The string to feed to the trigger engine. Include color information in the same manner as hecho.<br />
:See also: [[Manual:Lua_Functions#dfeedTriggers|dfeedTriggers]]<br />
:See also: [[Manual:Lua_Functions#hecho|hecho]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
hfeedTriggers("#008000,800000green on red#r reset\n")<br />
</syntaxhighlight><br />
<br />
==installModule==<br />
;installModule(location)<br />
:Installs a Mudlet XML, zip, or mpackage as a module.<br />
<br />
;Parameters<br />
* ''location:''<br />
:Exact location of the file install.<br />
<br />
:See also: [[#uninstallModule | uninstallModule()]], [[Manual:Event_Engine#sysLuaInstallModule | Event: sysLuaInstallModule]], [[#setModulePriority | setModulePriority()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
installModule([[C:\Documents and Settings\bub\Desktop\myalias.xml]])<br />
</syntaxhighlight><br />
<br />
==installPackage==<br />
;installPackage(location or url)<br />
:Installs a Mudlet XML or package. Since Mudlet 4.11+ returns <code>true</code> if it worked, or <code>false</code>.<br />
<br />
;Parameters<br />
* ''location:''<br />
:Exact location of the xml or package to install.<br />
Since Mudlet 4.11+ it is possible to pass download link to a package (must start with <code>http</code> or <code>https</code> and end with <code>.xml</code>, <code>.zip</code>, <code>.mpackage</code> or <code>.trigger</code>)<br />
<br />
:See also: [[#uninstallPackage | uninstallPackage()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
installPackage([[C:\Documents and Settings\bub\Desktop\myalias.xml]])<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
installPackage([[https://github.com/Mudlet/Mudlet/blob/development/src/run-lua-code-v4.xml]])<br />
</syntaxhighlight><br />
<br />
==killAnonymousEventHandler==<br />
;killAnonymousEventHandler(handler id)<br />
:Disables and removes the given event handler.<br />
<br />
;Parameters<br />
* ''handler id''<br />
:ID of the event handler to remove as returned by the [[ #registerAnonymousEventHandler | registerAnonymousEventHandler ]] function.<br />
<br />
:See also: [[ #registerAnonymousEventHandler | registerAnonymousEventHandler ]]<br />
<br />
{{MudletVersion|3.5}}<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- registers an event handler that prints the first 5 GMCP events and then terminates itself<br />
<br />
local counter = 0<br />
local handlerId = registerAnonymousEventHandler("gmcp", function(_, origEvent)<br />
print(origEvent)<br />
counter = counter + 1<br />
if counter == 5 then<br />
killAnonymousEventHandler(handlerId)<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
==loadMusicFile==<br />
;loadMusicFile(settings table) or loadMusicFile(name, [url])<br />
:Loads music files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]] and [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]]. Although files could be loaded directly at playing time from [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], loadMusicFile() provides the advantage of loading files in advance. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if file to load is not part of the profile or on the local file system.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#playMusicFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Download from the Internet<br />
loadMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
<br />
-- OR download from the profile<br />
loadMusicFile({name = getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
<br />
-- OR download from the local file system<br />
loadMusicFile({name = "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of loadMusicFile(name[, url]) ----<br />
<br />
-- Download from the Internet<br />
loadMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
)<br />
<br />
-- OR download from the profile<br />
loadMusicFile(getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
<br />
-- OR download from the local file system<br />
loadMusicFile("C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
</syntaxhighlight><br />
<br />
==loadSoundFile==<br />
;loadSoundFile(settings table) or loadSoundFile(name, [url])<br />
:Loads sound files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]] and [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]]. Although files could be loaded directly at playing time from [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], loadSoundFile() provides the advantage of loading files in advance. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if file to load is not part of the profile or on the local file system.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Download from the Internet<br />
loadSoundFile({<br />
name = "cow.wav"<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
<br />
-- OR download from the profile<br />
loadSoundFile({name = getMudletHomeDir().. "/cow.wav"})<br />
<br />
-- OR download from the local file system<br />
loadSoundFile({name = "C:/Users/Tamarindo/Documents/cow.wav"})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of loadSoundFile(name[,url]) ----<br />
<br />
-- Download from the Internet<br />
loadSoundFile("cow.wav", "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/")<br />
<br />
-- OR download from the profile<br />
loadSoundFile(getMudletHomeDir().. "/cow.wav")<br />
<br />
-- OR download from the local file system<br />
loadSoundFile("C:/Users/Tamarindo/Documents/cow.wav")<br />
</syntaxhighlight><br />
<br />
==mudletOlderThan==<br />
;mudletOlderThan(major, [minor], [patch])<br />
:Returns true if Mudlet is older than the given version to check. This is useful if you'd like to use a feature that you can't check for easily, such as coroutines support. However, if you'd like to check if a certain function exists, do not use this and use <code>if mudletfunction then</code> - it'll be much more readable and reliable.<br />
<br />
See also: [[#getMudletVersion|getMudletVersion()]]<br />
<br />
;Parameters<br />
* ''major:''<br />
:Mudlet major version to check. Given a Mudlet version 3.0.1, 3 is the major version, second 0 is the minor version, and third 1 is the patch version.<br />
* ''minor:''<br />
:(optional) minor version to check.<br />
* ''patch:''<br />
:(optional) patch version to check.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- stop doing the script of Mudlet is older than 3.2<br />
if mudletOlderThan(3,2) then return end<br />
<br />
-- or older than 2.1.3<br />
if mudletOlderThan(2, 1, 3) then return end<br />
<br />
-- however, if you'd like to check that a certain function is available, like getMousePosition(), do this instead:<br />
if not getMousePosition then return end<br />
<br />
-- if you'd like to check that coroutines are supported, do this instead:<br />
if not mudlet.supportscoroutines then return end<br />
</syntaxhighlight><br />
<br />
==openWebPage==<br />
;openWebPage(URL)<br />
:Opens the browser to the given webpage.<br />
<br />
;Parameters<br />
* ''URL:''<br />
:Exact URL to open.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
openWebPage("http://google.com")<br />
</syntaxhighlight><br />
<br />
Note: This function can be used to open a local file or file folder as well by using "file:///" and the file path instead of "http://".<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
openWebPage("file:///"..getMudletHomeDir().."file.txt")<br />
</syntaxhighlight><br />
<br />
==playMusicFile==<br />
;playMusicFile(settings table)<br />
:Plays music files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|-<br />
| style="text-align:center;"| No<br />
| volume<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| fadein<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
| fadeout<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| start<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
|-<br />
| style="text-align:center;" |No<br />
| loops<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the media to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| continue <br />
| true or false<br />
| true<br />
| style="text-align:left;" |<br />
*Continues playing matching new music files when true.<br />
*Restarts matching new music files when false.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{Note}} on Windows and certain files are not playing? Try installing the 3rd party [https://codecguide.com/download_k-lite_codec_pack_standard.htm K-lite codec pack].<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Play a music file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
})<br />
<br />
-- OR copy once from the game's profile, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile({<br />
name = getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = 75<br />
})<br />
<br />
-- OR copy once from the local file system, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile({<br />
name = "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = 75<br />
})<br />
<br />
-- OR download once from the Internet, and play music stored in the profile's media directory<br />
---- [fadein] and increase the volume from 1 at the start position to default volume up until the position of 20 seconds<br />
---- [fadeout] and decrease the volume from default volume to one, 53 seconds from the end of the music<br />
---- [start] 10 seconds after position 0 (fadein scales its volume increase over a shorter duration, too)<br />
---- [key] reference of "rugby" for stopping this unique music later<br />
---- [tag] reference of "ambience" to stop and music later with the same tag<br />
---- [continue] playing this music if another request for the same music comes in (false restarts it) <br />
---- [url] to download once from the Internet if the music does not exist in the profile's media directory<br />
playMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = nil -- nil lines are optional, no need to use<br />
, fadein = 20000<br />
, fadeout = 53000<br />
, start = 10000<br />
, loops = nil -- nil lines are optional, no need to use<br />
, key = "rugby"<br />
, tag = "ambience"<br />
, continue = true<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of playMusicFile(name[,volume][,fadein][,fadeout][,loops][,key][,tag][,continue][,url]) ----<br />
<br />
-- Play a music file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
)<br />
<br />
-- OR copy once from the game's profile, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile(<br />
getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR copy once from the local file system, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile(<br />
"C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR download once from the Internet, and play music stored in the profile's media directory<br />
---- [fadein] and increase the volume from 1 at the start position to default volume up until the position of 20 seconds<br />
---- [fadeout] and decrease the volume from default volume to one, 53 seconds from the end of the music<br />
---- [start] 10 seconds after position 0 (fadein scales its volume increase over a shorter duration, too)<br />
---- [key] reference of "rugby" for stopping this unique music later<br />
---- [tag] reference of "ambience" to stop and music later with the same tag<br />
---- [continue] playing this music if another request for the same music comes in (false restarts it) <br />
---- [url] to download once from the Internet if the music does not exist in the profile's media directory<br />
playMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, nil -- volume<br />
, 20000 -- fadein<br />
, 53000 -- fadeout<br />
, 10000 -- start<br />
, nil -- loops<br />
, "rugby" -- key <br />
, "ambience" -- tag<br />
, true -- continue<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/" -- url<br />
)<br />
</syntaxhighlight><br />
<br />
==playSoundFile==<br />
;playSoundFile(settings table)<br />
:Plays sound files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|-<br />
| style="text-align:center;"| No<br />
| volume<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| fadein<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
| fadeout<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| start<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
|-<br />
| style="text-align:center;" |No<br />
| loops<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the media to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| priority<br />
| 1 to 100<br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a lower priority while this media plays.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{Note}} on Windows and certain files are not playing? Try installing the 3rd party [https://codecguide.com/download_k-lite_codec_pack_standard.htm K-lite codec pack].<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Play a sound file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playSoundFile({<br />
name = "cow.wav"<br />
})<br />
<br />
-- OR copy once from the game's profile, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile({<br />
name = getMudletHomeDir().. "/cow.wav"<br />
, volume = 75<br />
})<br />
<br />
-- OR copy once from the local file system, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile({<br />
name = "C:/Users/Tamarindo/Documents/cow.wav"<br />
, volume = 75<br />
})<br />
<br />
-- OR download once from the Internet, and play a sound stored in the profile's media directory<br />
---- [volume] of 75<br />
---- [loops] of 2 (-1 for indefinite repeats, 1+ for finite repeats)<br />
---- [key] reference of "cow" for stopping this unique sound later<br />
---- [tag] reference of "animals" to stop a group of sounds later with the same tag<br />
---- [priority] of 25 (1 to 100, 50 default, a sound with a higher priority would stop this one)<br />
---- [url] to download once from the Internet if the sound does not exist in the profile's media directory<br />
playSoundFile({<br />
name = "cow.wav"<br />
, volume = 75<br />
, fadein = nil -- nil lines are optional, no need to use<br />
, fadeout = nil -- nil lines are optional, no need to use<br />
, start = nil -- nil lines are optional, no need to use<br />
, loops = 2<br />
, key = "cow"<br />
, tag = "animals"<br />
, priority = 25<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of playSoundFile(name[,volume][,fadein][,fadeout][,loops][,key][,tag][,priority][,url]) ----<br />
<br />
-- Play a sound file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playSoundFile(<br />
"cow.wav" -- name<br />
)<br />
<br />
-- OR copy once from the game's profile, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile(<br />
getMudletHomeDir().. "/cow.wav" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR copy once from the local file system, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile(<br />
"C:/Users/Tamarindo/Documents/cow.wav" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR download once from the Internet, and play a sound stored in the profile's media directory<br />
---- [volume] of 75<br />
---- [loops] of 2 (-1 for indefinite repeats, 1+ for finite repeats)<br />
---- [key] reference of "cow" for stopping this unique sound later<br />
---- [tag] reference of "animals" to stop a group of sounds later with the same tag<br />
---- [priority] of 25 (1 to 100, 50 default, a sound with a higher priority would stop this one)<br />
---- [url] to download once from the Internet if the sound does not exist in the profile's media directory<br />
playSoundFile(<br />
"cow.wav" -- name<br />
, 75 -- volume<br />
, nil -- fadein<br />
, nil -- fadeout<br />
, nil -- start<br />
, 2 -- loops<br />
, "cow" -- key <br />
, "animals" -- tag<br />
, 25 -- priority<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/" -- url<br />
)<br />
</syntaxhighlight><br />
<br />
==purgeMediaCache==<br />
;purgeMediaCache()<br />
: Purge all media file stored in the media cache within a given Mudlet profile (media used with MCMP and MSP protocols). As game developers update the media files on their games, this enables the media folder inside the profile to be cleared so that the media files could be refreshed to the latest update(s).<br />
<br />
;Guidance:<br />
<br />
* Instruct a player to type ''lua purgeMediaCache()'' on the command line, or<br />
* Distribute a trigger, button or other scriptable feature for the given profile to call ''purgeMediaCache()''<br />
<br />
: See also: [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]], [[Manual:Scripting#MUD_Client_Media_Protocol|Scripting MCMP]]<br />
<br />
==receiveMSP==<br />
;receiveMSP(command)<br />
: Receives a well-formed Mud Sound Protocol (MSP) message to be processed by the Mudlet client. Reference the [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]] manual for more information on about what can be sent and example triggers.<br />
<br />
: See also: [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Play a cow.wav media file stored in the media folder of the current profile. The sound would play twice at a normal volume.<br />
receiveMSP("!!SOUND(cow.wav L=2 V=50)")<br />
<br />
--Stop any SOUND media files playing stored in the media folder of the current profile.<br />
receiveMSP("!!SOUND(Off)")<br />
<br />
--Play a city.mp3 media file stored in the media folder of the current profile. The music would play once at a low volume.<br />
--The music would continue playing if it was triggered earlier by another room, perhaps in the same area.<br />
receiveMSP([[!!MUSIC(city.mp3 L=1 V=25 C=1)]])<br />
<br />
--Stop any MUSIC media files playing stored in the media folder of the current profile.<br />
receiveMSP("!!MUSIC(Off)")<br />
</syntaxhighlight><br />
<br />
==registerAnonymousEventHandler==<br />
;registerAnonymousEventHandler(event name, functionReference, [one shot])<br />
:Registers a function to an event handler, not requiring you to set one up via script. [[Manual:Event_Engine#Mudlet-raised_events|See here]] for a list of Mudlet-raised events. The function may be refered to either by name as a string containing a global function name, or with the lua function object itself.<br />
<br />
:The optional <code>one shot</code> parameter allows you to automatically kill an event handler after it is done by giving a true value. If the event you waited for did not occur yet, return <code>true</code> from the function to keep it registered.<br />
<br />
:The function returns an ID that can be used in [[Manual:Lua_Functions#killAnonymousEventHandler|killAnonymousEventHandler()]] to unregister the handler again.<br />
<br />
:If you use an asterisk ''("*")'' as the event name, your code will capture all events. Useful for debugging, or integration with external programs.<br />
<br />
{{note}} The ability to refer lua functions directly, the <code>one shot</code> parameter and the returned ID are features of Mudlet 3.5 and above.<br />
<br />
{{note}} The ''"*"'' all-events capture was added in Mudlet 4.10.<br />
<br />
;See also<br />
:[[Manual:Lua_Functions#killAnonymousEventHandler|killAnonymousEventHandler()]], [[Manual:Lua_Functions#raiseEvent|raiseEvent()]], [[Manual:Event_Engine#Mudlet-raised_events|list of Mudlet-raised events]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size<br />
function keepStaticSize()<br />
setMainWindowSize(1280,720)<br />
end -- keepStaticSize<br />
<br />
if keepStaticSizeEventHandlerID then killAnonymousEventHandler(keepStaticSizeEventHandlerID) end -- clean up any already registered handlers for this function<br />
keepStatisSizeEventHandlerID = registerAnonymousEventHandler("sysWindowResizeEvent", "keepStaticSize") -- register the event handler and save the ID for later killing<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- simple inventory tracker for GMCP enabled games. This version does not leak any of the methods<br />
-- or tables into the global namespace. If you want to access it, you should export the inventory<br />
-- table via an own namespace.<br />
local inventory = {}<br />
<br />
local function inventoryAdd()<br />
if gmcp.Char.Items.Add.location == "inv" then<br />
inventory[#inventory + 1] = table.deepcopy(gmcp.Char.Items.Add.item)<br />
end<br />
end<br />
if inventoryAddHandlerID then killAnonymousEventHandler(inventoryAddHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryAddHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Add", inventoryAdd) -- register the event handler and save the ID for later killing<br />
<br />
local function inventoryList()<br />
if gmcp.Char.Items.List.location == "inv" then<br />
inventory = table.deepcopy(gmcp.Char.Items.List.items)<br />
end<br />
end<br />
if inventoryListHandlerID then killAnonymousEventHandler(inventoryListHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryListHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.List", inventoryList) -- register the event handler and save the ID for later killing<br />
<br />
local function inventoryUpdate()<br />
if gmcp.Char.Items.Remove.location == "inv" then<br />
local found<br />
local updatedItem = gmcp.Char.Items.Update.item<br />
for index, item in ipairs(inventory) do<br />
if item.id == updatedItem.id then<br />
found = index<br />
break<br />
end<br />
end<br />
if found then<br />
inventory[found] = table.deepcopy(updatedItem)<br />
end<br />
end<br />
end<br />
if inventoryUpdateHandlerID then killAnonymousEventHandler(inventoryUpdateHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryUpdateHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Update", inventoryUpdate)<br />
<br />
local function inventoryRemove()<br />
if gmcp.Char.Items.Remove.location == "inv" then<br />
local found<br />
local removedItem = gmcp.Char.Items.Remove.item<br />
for index, item in ipairs(inventory) do<br />
if item.id == removedItem.id then<br />
found = index<br />
break<br />
end<br />
end<br />
if found then<br />
table.remove(inventory, found)<br />
end<br />
end<br />
end<br />
if inventoryRemoveHandlerID then killAnonymousEventHandler(inventoryRemoveHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryRemoveHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Remove", inventoryRemove)<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- downloads a package from the internet and kills itself after it is installed.<br />
local saveto = getMudletHomeDir().."/dark-theme-mudlet.zip"<br />
local url = "http://www.mudlet.org/wp-content/files/dark-theme-mudlet.zip"<br />
<br />
if myPackageInstallHandler then killAnonymousEventHandler(myPackageInstallHandler) end<br />
myPackageInstallHandler = registerAnonymousEventHandler(<br />
"sysDownloadDone",<br />
function(_, filename)<br />
if filename ~= saveto then<br />
return true -- keep the event handler since this was not our file<br />
end<br />
installPackage(saveto)<br />
os.remove(b)<br />
end,<br />
true<br />
)<br />
<br />
downloadFile(saveto, url)<br />
cecho("<white>Downloading <green>"..url.."<white> to <green>"..saveto.."\n")<br />
</syntaxhighlight><br />
<br />
==registerNamedEventHandler==<br />
; success = registerNamedEventHandler(userName, handlerName, eventName, functionReference, [oneShot])<br />
<br />
:Registers a named event handler with name handlerName. Named event handlers are protected from duplication and can be stopped and resumed, unlike anonymous event handlers. A separate list is kept per userName<br />
<br />
;See also: [[Manual:Lua_Functions#registerAnonymousEventHandler|registerAnonymousEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]], [[Manual:Lua_Functions#deleteNamedEventHandler|deleteNamedEventHandler()]], [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler. Used to reference the handler in other functions and prevent duplicates. Recommended you use descriptive names, "hp" is likely to collide with something else, "DemonVitals" less so.<br />
* ''eventName:''<br />
: The name of the event the handler responds to. [[Manual:Event_Engine#Mudlet-raised_events|See here]] for a list of Mudlet-raised events.<br />
* ''functionReference:''<br />
: The function reference to run when the event comes in. Can be the name of a function, "handlerFuncion", or the lua function itself. <br />
* ''oneShot:''<br />
: (optional) if true, the event handler will only fire once when the event is raised. If you need to extend a one shot event handler for "one more check" you can have the handler return true, and it will keep firing until the function does not return true.<br />
<br />
;Returns <br />
* true if successful, otherwise errors.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- register a named event handler. Will call demonVitalsHandler(eventName, ...) when gmcp.Char.Vitals is raised.<br />
local ok = registerNamedEventHandler("Demonnic", "DemonVitals", "gmcp.Char.Vitals", "demonVitalsHandler")<br />
if ok then<br />
cecho("Vitals handler switched to demonVitalsHandler")<br />
end<br />
<br />
-- something changes later, and we want to handle vitals with another function, demonBlackoutHandler()<br />
-- note we do not use "" around demonBlackoutHandler but instead pass the function itself. Both work.<br />
-- using the same handlerName ("DemonVitals") means it will automatically unregister the old handler<br />
-- and reregister it using the new information.<br />
local ok = registerNamedEventHandler("Demonnic", "DemonVitals", "gmcp.Char.Vitals", demonBlackoutHandler)<br />
if ok then<br />
cecho("Vitals handler switched to demonBlackoutHandler")<br />
end<br />
<br />
-- Now you want to check your inventory, but you only want to do it once, so you pass the optional oneShot as true<br />
local function handleInv()<br />
local list = gmcp.Char.Items.List<br />
if list.location ~= "inventory" then<br />
return true -- if list.location is, say "room" then we need to keep responding until it's "inventory"<br />
end<br />
display(list.items) -- you would probably store values and update displays or something, but here I'll just show the data as it comes in<br />
end<br />
<br />
-- you can ignore the response from registerNamedEventHandler if you want, it's always going to be true<br />
-- unless there is an error, in which case it throws the error and halts execution anyway. The return is<br />
-- in part for feedback when using the lua alias or other REPL window.<br />
registerNamedEventHandler("Demonnic", "DemonInvCheck", "gmcp.Char.Items.List", handleInv, true)<br />
</syntaxhighlight><br />
<br />
==reloadModule==<br />
;reloadModule(module name)<br />
:Reload a module (by uninstalling and reinstalling).<br />
<br />
:See also: [[#installModule|installModule()]], [[#uninstallModule|uninstallModule()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
reloadModule("3k-mapper")<br />
</syntaxhighlight><br />
<br />
<br />
==removeFileWatch==<br />
;removeFileWatch(path)<br />
:Remove file watch on directory or file. Every change in that file will no longer raise [[Manual:Event_Engine#sysPathChanged|sysPathChanged]] event.<br />
<br />
:See also: [[#addFileWatch|addFileWatch()]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", "herbsChangedHandler")<br />
</syntaxhighlight><br />
<br />
==resetProfile==<br />
;resetProfile()<br />
<br />
:Reloads your entire Mudlet profile - as if you've just opened it. All UI elements will be cleared, so this useful when you're coding your UI.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
resetProfile()<br />
</syntaxhighlight><br />
<br />
The function used to require input from the game to work, but as of Mudlet 3.20 that is no longer the case.<br />
<br />
<br />
{{note}} Don't put resetProfile() in the a script-item in the script editor as the script will be reloaded by resetProfile() as well better use <br />
<syntaxhighlight lang="lua"><br />
lua resetProfile()<br />
</syntaxhighlight><br />
in your commandline or make an Alias containing resetProfile().<br />
<br />
==resumeNamedEventHandler==<br />
; success = resumeNamedEventHandler(userName, handlerName)<br />
<br />
:Resumes a named event handler with name handlerName and causes it to start firing once more.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to resume. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local resumed = resumeNamedEventHandler("Demonnic", "DemonVitals")<br />
if resumed then<br />
cecho("DemonVitals resumed!")<br />
else<br />
cecho("DemonVitals doesn't exist, cannot resume it")<br />
end<br />
</syntaxhighlight><br />
<br />
==saveProfile==<br />
;saveProfile(location)<br />
<br />
:Saves the current Mudlet profile to disk, which is equivalent to pressing the "Save Profile" button.<br />
<br />
;Parameters<br />
* ''location:''<br />
:(optional) folder to save the profile to. If not given, the profile will go into the [[Mudlet_File_Locations|default location]].<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
saveProfile()<br />
<br />
-- save to the desktop on Windows:<br />
saveProfile([[C:\Users\yourusername\Desktop]])<br />
</syntaxhighlight><br />
<br />
==sendSocket==<br />
;sendSocket(data)<br />
<br />
:Sends given binary data as-is to the game. You can use this to implement support for a [[Manual:Supported_Protocols#Adding_support_for_a_telnet_protocol|new telnet protocol]], [http://forums.mudlet.org/viewtopic.php?f=5&t=2272 simultronics] [http://forums.mudlet.org/viewtopic.php?f=5&t=2213#p9810 login] or etcetera.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
TN_IAC = 255<br />
TN_WILL = 251<br />
TN_DO = 253<br />
TN_SB = 250<br />
TN_SE = 240<br />
TN_MSDP = 69<br />
<br />
MSDP_VAL = 1<br />
MSDP_VAR = 2<br />
<br />
sendSocket( string.char( TN_IAC, TN_DO, TN_MSDP ) ) -- sends IAC DO MSDP<br />
<br />
--sends: IAC SB MSDP MSDP_VAR "LIST" MSDP_VAL "COMMANDS" IAC SE<br />
local msg = string.char( TN_IAC, TN_SB, TN_MSDP, MSDP_VAR ) .. " LIST " ..string.char( MSDP_VAL ) .. " COMMANDS " .. string.char( TN_IAC, TN_SE )<br />
sendSocket( msg )<br />
</syntaxhighlight><br />
<br />
{{Note}} Remember that should it be necessary to send the byte value of 255 as a ''data'' byte and not as the Telnet '''IAC''' value it is required to repeat it for Telnet to ignore it and not treat it as the latter.<br />
<br />
==setConfig==<br />
; setConfig(option, value)<br />
<br />
:Sets a Mudlet option to a certain value. This comes in handy for scripts that want to customise Mudlet settings to their preferences - for example, setting up mapper room and exit size to one that works for a certain map, or enabling MSDP for a certain game. For transparency reasons, the Debug window (when open) will show which options were modified by scripts.<br />
:To set many options at once, pass in a table of options. More options will be added over time / per request.<br />
<br />
;See also: [[Manual:Lua_Functions#enableMapInfo|enableMapInfo()]], [[Manual:Lua_Functions#disableMapInfo|disableMapInfo()]]<br />
<br />
{{MudletVersion|4.16}}<br />
<br />
;Parameters<br />
* ''option:''<br />
: Particular option to change - see list below for available ones.<br />
* ''value:''<br />
: Value to set - can be a boolean, number, or text depending on the option.<br />
<br />
{| class="wikitable sortable"<br />
|+ General options<br />
|-<br />
! Option !! Default !! Description !! Available in Mudlet<br />
|-<br />
| enableGMCP || true || Enable GMCP (Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSDP || false || Enable MSDP (Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSSP || true || Enable MSSP (Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSP || true || Enable MSP (Reconnect after changing) || 4.16 <br />
|-<br />
| compactInputLine || false || Hide search, timestamp, other buttons and labels bottom-right of input line || 4.17<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Input line<br />
|-<br />
! Option !! Default !! Description !! Available in Mudlet<br />
|-<br />
| inputLineStrictUnixEndings || false || Workaround option to use strict UNIX line endings for sending commands || 4.16 <br />
|-<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Main display<br />
|-<br />
! Option !! Default !! Description !! Available in Mudlet<br />
|-<br />
| fixUnnecessaryLinebreaks || false || Remove extra linebreaks from output (mostly for IRE servers) || 4.16 <br />
|-<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Mapper options<br />
|-<br />
! Option !! Default !! Description !! Available in Mudlet<br />
|-<br />
| mapRoomSize || 5 || Size of rooms on map (a good value is 5) || 4.16<br />
|-<br />
| mapExitSize || 10 || Size of exits on map (a good value is 10) || 4.16<br />
|-<br />
| mapRoundRooms || false || Draw rooms round or square || 4.16<br />
|-<br />
| showRoomIdsOnMap || false || Show room IDs on all rooms (if zoom permits) || 4.16<br />
|-<br />
| showMapInfo || - || Map overlay text ('Full', 'Short', or any custom made. Map can show multiple at once) || 4.16<br />
|-<br />
| hideMapInfo || - || Map overlay text ('Full', 'Short', or any custom made. Hide each info separately to hide all) || 4.16<br />
|-<br />
| show3dMapView || false || Show map as 3D || 4.16<br />
|-<br />
| mapperPanelVisible || true || Map controls at the bottom || 4.16<br />
|-<br />
| mapShowRoomBorders || true || Draw a thin border for every room || 4.16<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Special options<br />
|-<br />
! Option !! Default !! Description !! Available in Mudlet<br />
|-<br />
| specialForceCompressionOff || false || Workaround option to disable MCCP compression, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceGAOff || false || Workaround option to disable Telnet Go-Ahead, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceCharsetNegotiationOff || false || Workaround option to disable automatically setting the correct encoding, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceMxpNegotiationOff || false || Workaround option to disable MXP, in case the game server is not working correctly || 4.16 <br />
|-<br />
| caretShortcut || "none" || For visually-impaired players - set the key to switch between input line and main window (can be "none", "tab", "ctrltab", "f6") || 4.17<br />
|-<br />
| blankLinesBehaviour || "show" || For visually impaired players options for dealing with blank lines (can be "show", "hide", "replacewithspace") || 4.17<br />
|}<br />
<br />
;Returns <br />
* true if successful, or nil+msg if the option doesn't exist. Setting mapper options requires the mapper being open first.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setConfig("mapRoomSize", 5)<br />
<br />
setConfig({mapRoomSize = 6, mapExitSize = 12})<br />
</syntaxhighlight><br />
<br />
==setMergeTables==<br />
;setMergeTables(module)<br />
:Makes Mudlet merge the table of the given GMCP or MSDP module instead of overwriting the data. This is useful if the game sends only partial updates which need combining for the full data. By default "Char.Status" is the only merged module.<br />
<br />
;Parameters<br />
* ''module:''<br />
:Name(s) of the GMCP or MSDP module(s) that should be merged as a string - this will add it to the existing list.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setMergeTables("Char.Skills", "Char.Vitals")<br />
</syntaxhighlight><br />
<br />
==setModuleInfo==<br />
;setModuleInfo(moduleName, info, value)<br />
<br />
:Sets a specific meta info value for a module<br />
<br />
;Parameters<br />
* ''moduleName:''<br />
:Name of the module<br />
* ''info:''<br />
: specific info to set (for example "version")<br />
* ''value:''<br />
: specific value to set (for example "1.0")<br />
<br />
:See also: [[#getModuleInfo|getModuleInfo]], [[#setPackageInfo|getPackageInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setModuleInfo("myModule", "version", "1.0")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==setModulePriority==<br />
;setModulePriority(moduleName, priority)<br />
<br />
:Sets the module priority on a given module as a number - the module priority determines the order modules are loaded in, which can be helpful if you have ones dependent on each other. This can also be set from the module manager window.<br />
: Modules with priority <code>-1</code> will be loaded before scripts (Mudlet 4.11+).<br />
<br />
: See also: [[#getModulePriority|getModulePriority()]]<br />
<br />
<syntaxhighlight lang="lua"><br />
setModulePriority("mudlet-mapper", 1)<br />
</syntaxhighlight><br />
<br />
==setPackageInfo==<br />
;setPackageInfo(packageName, info, value)<br />
<br />
:Sets a specific meta info value for a package<br />
<br />
;Parameters<br />
* ''packageName:''<br />
:Name of the module<br />
* ''info:''<br />
: specific info to set (for example "version")<br />
* ''value:''<br />
: specific value to set (for example "1.0")<br />
<br />
:See also: [[#getPackageInfo|getPackageInfo]], [[#setModuleInfo|setModuleInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setPackageInfo("myPackage", "title", "This is my test package")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==setServerEncoding==<br />
;setServerEncoding(encoding)<br />
:Makes Mudlet use the specified [https://www.w3.org/International/questions/qa-what-is-encoding encoding] for communicating with the game.<br />
<br />
;Parameters<br />
* ''encoding:''<br />
:Encoding to use.<br />
<br />
:See also: [[#getServerEncodingsList|getServerEncodingsList()]], [[#getServerEncoding|getServerEncoding()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- use UTF-8 if Mudlet knows it. Unfortunately there's no way to check if the game's server knows it too.<br />
if table.contains(getServerEncodingsList(), "UTF-8") then<br />
setServerEncoding("UTF-8")<br />
end<br />
</syntaxhighlight><br />
<br />
==showNotification==<br />
;showNotification(title, [content], [expiryTimeInSeconds])<br />
<br />
:Shows a native (system) notification.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
{{Note}} This might not work on all systems, this depends on the system.<br />
<br />
;Parameters<br />
* ''title'' - plain text notification title<br />
* ''content'' - optional argument, plain text notification content, if omitted title argument will be used as content as well<br />
* ''expiryTimeInSeconds'' - optional argument, sets expiration time in seconds for notification, very often ignored by OS<br />
<br />
<syntaxhighlight lang="lua"><br />
showNotification("Notification title", "Notification content", 5)<br />
</syntaxhighlight><br />
<br />
==spawn==<br />
;spawn(readFunction, processToSpawn[, ...arguments])<br />
<br />
:Spawns a process and opens a communicatable link with it - ''read function'' is the function you'd like to use for reading output from the process, and ''t'' is a table containing functions specific to this connection - ''send(data)'', ''true/false = isRunning()'', and ''close()''.<br />
<br />
:This allows you to setup RPC communication with another process.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- simple example on a program that quits right away, but prints whatever it gets using the 'display' function<br />
local f = spawn(display, "ls")<br />
display(f.isRunning())<br />
f.close()<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
local f = spawn(display, "ls", "-la")<br />
display(f.isRunning())<br />
f.close()<br />
</syntaxhighlight><br />
<br />
==startLogging==<br />
;startLogging(state)<br />
<br />
:Control logging of the main console text as text or HTML (as specified by the "Save log files in HTML format instead of plain text" setting on the "General" tab of the "Profile preferences" or "Settings" dialog). Despite being called startLogging it can also stop the process and correctly close the file being created. The file will have an extension of type ".txt" or ".html" as appropriate and the name will be in the form of a date/time "yyyy-MM-dd#hh-mm-ss" using the time/date of when logging started. Note that this control parallels the corresponding icon in the "bottom buttons" for the profile and that button can also start and stop the same logging process and will reflect the state as well.<br />
<br />
;Parameters<br />
* ''state:''<br />
:Required: logging state. Passed as a boolean<br />
<br />
;Returns (4 values)<br />
* ''successful (bool)''<br />
:''true'' if the logging state actually changed; if, for instance, logging was already active and ''true'' was supplied then no change in logging state actually occurred and ''nil'' will be returned (and logging will continue).<br />
* ''message (string)''<br />
:A displayable message given one of four messages depending on the current and previous logging states, this will include the file name except for the case when logging was not taking place and the supplied argument was also ''false''.<br />
* ''fileName (string)''<br />
:The log will be/is being written to the path/file name returned.<br />
* ''code (number)''<br />
:A value indicating the response to the system to this instruction:<br />
* 0 = logging has just stopped<br />
* 1 = logging has just started<br />
* -1 = logging was already in progress so no change in logging state<br />
* -2 = logging was already not in progress so no change in logging state<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- start logging<br />
local success, message, filename, code = startLogging(true)<br />
if code == 1 or code == -1 then print(f"Started logging to {filename}") end<br />
<br />
-- stop logging<br />
startLogging(false)<br />
</syntaxhighlight><br />
<br />
==stopAllNamedEventHandlers==<br />
; stopAllNamedEventHandlers(userName)<br />
<br />
:Stops all named event handlers and prevents them from firing any more. Information is retained and handlers can be resumed.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameter<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
stopAllNamedEventHandlers() -- emergency stop situation, most likely.<br />
</syntaxhighlight><br />
<br />
==stopMusic==<br />
;stopMusic(settings table)<br />
:Stop all music (no filter), or music that meets a combination of filters (name, key, and tag) intended to be paired with [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|-<br />
| style="text-align:center;"| No<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Stop all playing music files for this profile associated with the API<br />
stopMusic()<br />
<br />
-- Stop playing the rugby mp3 by name<br />
stopMusic({name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
<br />
-- Stop playing the unique sound identified as "rugby"<br />
stopMusic({<br />
name = nil -- nil lines are optional, no need to use<br />
, key = "rugby" -- key<br />
, tag = nil -- nil lines are optional, no need to use<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of stopMusic([name][,key][,tag]) ----<br />
<br />
-- Stop all playing music files for this profile associated with the API<br />
stopMusic()<br />
<br />
-- Stop playing the rugby mp3 by name<br />
stopMusic("167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
<br />
-- Stop playing the unique sound identified as "rugby"<br />
stopMusic(<br />
nil -- name<br />
, "rugby" -- key<br />
, nil -- tag<br />
)<br />
</syntaxhighlight><br />
<br />
==stopNamedEventHandler==<br />
; success = stopNamedEventHandler(userName, handlerName)<br />
<br />
:Stops a named event handler with name handlerName and prevents it from firing any more. Information is stored so it can be resumed later if desired.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to stop. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist or was already stopped<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local stopped = stopNamedEventHandler("DemonVitals")<br />
if stopped then<br />
cecho("DemonVitals stopped!")<br />
else<br />
cecho("DemonVitals doesn't exist or already stopped; either way it won't fire any more.")<br />
end<br />
</syntaxhighlight><br />
<br />
==stopSounds==<br />
;stopSounds(settings table)<br />
:Stop all sounds (no filter), or sounds that meets a combination of filters (name, key, tag, and priority) intended to be paired with [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|-<br />
| style="text-align:center;"| No<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| priority<br />
| 1 to 100<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a matching or lower priority.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Stop all playing sound files for this profile associated with the API<br />
stopSounds()<br />
<br />
-- Stop playing the cow sound<br />
stopSounds({name = "cow.wav"})<br />
<br />
-- Stop playing any sounds tagged as "animals" with a priority less than or equal to 50<br />
---- This would not stop sounds tagged as "animals" greater than priority 50. This is an "AND" and not an "OR".<br />
stopSounds({<br />
name = nil -- nil lines are optional, no need to use<br />
, key = nil -- nil lines are optional, no need to use<br />
, tag = "animals"<br />
, priority = 50<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of stopSounds([name][,key][,tag][,priority]) ----<br />
<br />
-- Stop all playing sound files for this profile associated with the API<br />
stopSounds()<br />
<br />
-- Stop playing the cow sound<br />
stopSounds("cow.wav")<br />
<br />
-- Stop playing any sounds tagged as "animals" with a priority less than or equal to 50<br />
---- This would not stop sounds tagged as "animals" greater than priority 50. This is an "AND" and not an "OR".<br />
stopSounds(<br />
nil -- name<br />
, nil -- key<br />
, "animals" -- tag<br />
, 50 -- priority<br />
)<br />
</syntaxhighlight><br />
<br />
==timeframe==<br />
;timeframe(vname, true_time, nil_time, ...)<br />
<br />
:A utility function that helps you change and track variable states without using a lot of tempTimers.<br />
<br />
{{MudletVersion|3.6}}<br />
<br />
;Parameters<br />
* ''vname:''<br />
:A string or function to use as the variable placeholder.<br />
* ''true_time:''<br />
:Time before setting the variable to true. Can be a number or a table in the format: <code>{time, value}</code><br />
* ''nil_time:''<br />
:(optional) Number of seconds until <code>vname</code> is set back to nil. Leaving it undefined will leave it at whatever it was set to last. Can be a number of a table in the format: <code>{time, value}</code><br />
* ''...:''<br />
:(optional) Further list of times and values to set the variable to, in the following format: <code>{time, value}</code><br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- sets the global 'limiter' variable to true immediately (see the 0) and back to nil in one second (that's the 1).<br />
timeframe("limiter", 0, 1)<br />
<br />
-- An angry variable 'giant' immediately set to "fee", followed every second after by "fi", "fo", and "fum" before being reset to nil at four seconds.<br />
timeframe("giant", {0, "fee"}, 4, {1, "fi"}, {2, "fo"}, {3, "fum"})<br />
<br />
-- sets the local 'width' variable to true immediately and back to nil in one second.<br />
local width<br />
timeframe(function(value) width = value end, 0, 1)<br />
</syntaxhighlight><br />
<br />
==translateTable==<br />
;translateTable(directions, [languagecode])<br />
<br />
:Given a table of directions (such as <code>speedWalkDir</code>), translates directions to another language for you. Right now, it can only translate it into the language of Mudlet's user interface - but [https://github.com/Mudlet/Mudlet/issues/new let us know if you need more].<br />
<br />
{{MudletVersion|3.22}}<br />
<br />
;Parameters<br />
* ''directions:''<br />
:An indexed table of directions (eg. <code>{"sw", "w", "nw", "s"}</code>).<br />
* ''languagecode:''<br />
:(optional) Language code (eg <code>ru_RU</code> or <code>it_IT</code>) - by default, <code>mudlet.translations.interfacelanguage</code> is used.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- get the path from room 2 to room 5 and translate directions<br />
if getPath(2, 5) then<br />
speedWalkDir = translateTable(speedWalkDir)<br />
print("Translated directions:")<br />
display(speedWalkDir)<br />
</syntaxhighlight><br />
<br />
==uninstallModule==<br />
;uninstallModule(name)<br />
<br />
:Uninstalls a Mudlet module with the given name.<br />
<br />
:See also: [[#installModule | installModule()]], [[Manual:Event_Engine#sysLuaUninstallModule | Event: sysLuaUninstallModule]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
uninstallModule("myalias")<br />
</syntaxhighlight><br />
<br />
==uninstallPackage==<br />
;uninstallPackage(name)<br />
<br />
:Uninstalls a Mudlet package with the given name.<br />
<br />
:See also: [[#installPackage | installPackage()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
uninstallPackage("myalias")<br />
</syntaxhighlight><br />
<br />
==unzipAsync==<br />
;unzipAsync(path, location)<br />
<br />
:Unzips the zip file at path, extracting the contents to the location provided. Returns true if it is able to start unzipping, or nil+message if it cannot.<br />
Raises the <code>sysUnzipDone</code> event with the zip file location and location unzipped to as arguments if unzipping is successful, and <code>sysUnzipError</code> with the same arguments if it is not.<br />
<br />
Do not use the <code>unzip()</code> function as it is synchronous and will impact Mudlet's performance (ie, freeze Mudlet while unzipping).<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function handleUnzipEvents(event, ...)<br />
local args = {...}<br />
local zipName = args[1]<br />
local unzipLocation = args[2]<br />
if event == "sysUnzipDone" then<br />
cecho(string.format("<green>Unzip successful! Unzipped %s to %s\n", zipName, unzipLocation))<br />
elseif event == "sysUnzipError" then<br />
cecho(string.format("<firebrick>Unzip failed! Tried to unzip %s to %s\n", zipName, unzipLocation))<br />
end<br />
end<br />
if unzipSuccessHandler then killAnonymousEventHandler(unzipSuccessHandler) end<br />
if unzipFailureHandler then killAnonymousEventHandler(unzipFailureHandler) end<br />
unzipSuccessHandler = registerAnonymousEventHandler("sysUnzipDone", "handleUnzipEvents")<br />
unzipFailureHandler = registerAnonymousEventHandler("sysUnzipError", "handleUnzipEvents")<br />
--use the path to your zip file for this, not mine<br />
local zipFileLocation = "/home/demonnic/Downloads/Junkyard_Orc.zip" <br />
--directory to unzip to, it does not need to exist but you do need to be able to create it<br />
local unzipLocation = "/home/demonnic/Downloads/Junkyard_Orcs" <br />
unzipAsync(zipFileLocation, unzipLocation) -- this will work<br />
unzipAsync(zipFileLocation .. "s", unzipLocation) --demonstrate error, will happen first because unzipping takes time</syntaxhighlight><br />
<br />
==yajl.to_string==<br />
;yajl.to_string(data)<br />
<br />
:Encodes a Lua table into JSON data and returns it as a string. This function is very efficient - if you need to encode into JSON, use this.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- on IRE MUD games, you can send a GMCP request to request the skills in a particular skillset. Here's an example:<br />
sendGMCP("Char.Skills.Get "..yajl.to_string{group = "combat"})<br />
<br />
-- you can also use it to convert a Lua table into a string, so you can, for example, store it as room's userdata<br />
local toserialize = yajl.to_string(continents)<br />
setRoomUserData(1, "areaContinents", toserialize)<br />
</syntaxhighlight><br />
<br />
<br />
==yajl.to_value==<br />
;yajl.to_value(data)<br />
<br />
:Decodes JSON data (as a string) into a Lua table. This function is very efficient - if you need to dencode into JSON, use this.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- given the serialization example above with yajl.to_string, you can deserialize room userdata back into a table<br />
local tmp = getRoomUserData(1, "areaContinents")<br />
if tmp == "" then return end<br />
<br />
local continents = yajl.to_value(tmp)<br />
display(continents)<br />
</syntaxhighlight><br />
<br />
[[Category:Mudlet Manual]]<br />
[[Category:Mudlet API]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Area_51/Template&diff=20396Area 51/Template2023-04-02T01:25:54Z<p>Kebap: /* See also */ add () brackets to the displayed name</p>
<hr />
<div>This template should be followed when creating new entries in documentation. <br />
<br />
Its source code can be copied and pasted and used as a framework for a new entry.<br />
<br />
It is heavily commented. Each comments line starts with "--" (as Lua comments that won't work on a Wiki page!) <br />
<br />
Remember to generally strip out each comment line before publishing a new documentation!<br />
<br />
You are encouraged to use the [[Area_51]] documentation page to prepare documentation for not-yet-published functionality.<br />
<br />
<< Back to [[Area_51]]<br />
<br />
== Contents of a documentation entry ==<br />
<br />
In the past, we did not always honor the same order. It is important to unify so reader's expectations are met and important information is found quickly.<br />
<br />
The following example uses this order of information:<br />
# headline<br />
# function signature<br />
# description<br />
# see also<br />
# mudlet version<br />
# note<br />
# parameters<br />
# returns<br />
# example<br />
# additional notes for developers, etc.<br />
<br />
==functionName==<br />
<br />
The headline will be the function name. That is the only part of the headline that will be transferred to main documentation. However during Area 51 stay, please also add the number of the pull request where it came from, plus the PR's current status (open, merged (to development versions), closed (i.e. not merged), etc.)<br />
<br />
; returnValue = functionName(mandatoryParameter, [optionalParameter])<br />
<br />
-- This function signature shows how to use the function named "functionName", which parameters to give, etc. More details follow below.<br />
<br />
-- The above first line will get scraped to form the auto completion text in Mudlet's editor - Therefore it should try and show the most possible parameters. Sometimes though this may be awkward to do when there are significant alternative forms available. A better method is still to be found.<br />
<br />
-- If the function returns no relevant values, drop the equal sign and anything before, otherwise give it a meaningful brief name.<br />
<br />
<br />
:Description of what this function will do. In this case, it is just a non-existing function with the only purpose to show how to write documentation for functions.<br />
<br />
-- This will be the second line after the function signature in the first line. (Remember to delete comment lines starting with "--" before publishing this template elsewhere.)<br />
<br />
-- The description can be multi-line, but please don't go overboard. You don't need to link to other functions, or explain all parameters in detail, as this will be part of the next sections. <br />
<br />
<br />
;See also: [[Manual:Lua_Functions#copy|copy()]], [[Manual:Lua_Functions#paste|paste()]]<br />
<br />
-- List a few related functions, so users can cyber around. <br />
<br />
-- Make sure to mark the internal links without space characters and with no brackets in the end, whereas the displayed name (after the | sign) should indeed end in () brackets<br />
<br />
-- Keep the list curated and don't add every single possible function. Maybe link to one central function hub which itself links to all other variants. Mix existing and new, closely and more loosely related functions. For example, creation / editing / deletion of same items, but only creation of other items (which itself link to their editing & deleting variants)<br />
<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
-- The version when the functionality is to be introduced should be given (if already known) using this template (assuming a major.minor version number - though a major.minor.patch format may be possible)<br />
-- If the code has not been merged yet when documentation begins, please link to the pending PR instead for future reference.<br />
<br />
<br />
{{note}} This is an important information<br />
<br />
-- You may add several notes if necessary, but please take care not to mark everything as important<br />
<br />
<br />
;Parameters<br />
* ''mandatoryParameter:''<br />
: Type and description of this parameter.<br />
* ''optionalParameter:''<br />
: (optional) Type and description of this parameter..<br />
<br />
-- The optional parameter'S name needn't be telling of its optional status. Relevant is to mark optional parameters at the start of this line (with text "optional" in brackets) and in the function definition line (with [these] brackets)<br />
<br />
<br />
;Returns <br />
* Type and description of whatever the function returns <br />
<br />
-- Only keep this section if it does indeed return relevant values<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- a comment explaining what is going on, if there is multiple functionalities (or optional parameters) the examples should start simple and progress in complexity if needed!<br />
-- the examples should be small, but self-contained so new users can copy & paste immediately without going diving in lots other function examples first.<br />
-- comments up top should introduce / explain what it does<br />
<br />
local something = function(exampleValue)<br />
if something then<br />
-- do something with something (assuming there is a meaningful return value)<br />
end<br />
<br />
-- maybe another example for the optional second case<br />
local somethingElse = function(exampleValue, anotherValue)<br />
<br />
-- lastly, include an example with error handling to give an idea of good practice<br />
local ok, err = function()<br />
if not ok then<br />
debugc(f"Error: unable to do <particular thing> because {err}\n")<br />
return<br />
end<br />
</syntaxhighlight><br />
<br />
; Additional development notes<br />
-- This section is not for inclusion when item transferred to final location.<br />
<br />
-- It could include revisions or input from other people<br />
<br />
-- Please use a [https://en.wikipedia.org/wiki/Wikipedia:Signatures#How_to_sign_your_posts signature with timestamp] when commenting here. To do that, just type two hyphens '-' followed by four tildes '~' after your comment like so: <syntaxhighlight lang="cpp">Good idea! --~~~~</syntaxhighlight> which will automatically render your user name and current date & time for later reference in the discussion flow.</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Event_Engine&diff=20358Manual:Event Engine2023-03-17T01:53:13Z<p>Kebap: /* sysInstallModule */ fix crosslink</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Manual on events, which events exist, how to raise events, how to handle them.}}<br />
=Event System=<br />
<br />
Events in Mudlet allow a paradigm of system-building that is easy to maintain (because if you’d like to restructure something, you’d have to do less work), enables interoperability (making a collection of scripts that work with each other is easier) and enables an event-based way of programming.<br />
<br />
The essentials of it are as such: you use Scripts to define which events a function should listen to, and when the event is raised, the said function(s) will be called. Events can also have function parameters with them, which’ll be passed onto the receiving functions.<br />
<br />
== Registering an event handler via UI ==<br />
Registering an event handler means that you’ll be telling Mudlet what function it should call for you when an event is raised, so it’s a two step process - you need to tell it both what function you’d like to have called, and on what event it should be called.<br />
<br />
To tell it what function should be called, create a new script, and give the script the name of the function you’d like to be called. This is the only time where an items name matters in Mudlet. You can define the function right inside the script as well, if you’d like.<br />
<br />
Next, we tell it what event or events this function should be called on - you can add multiple entries. To do that, enter the events name in the Add User Defined Event Handler: field, press enter, and it’ll go into the list - and that is all.<br />
<br />
== Registering an event from a script ==<br />
You can also register your event with the ''[[Manual:Miscellaneous_Functions#registerAnonymousEventHandler|registerAnonymousEventHandler(event name, function reference, [one shot])]]'' function inside your scripts:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size<br />
function keepStaticSize()<br />
setMainWindowSize(1280,720)<br />
end -- keepStaticSize<br />
<br />
registerAnonymousEventHandler("sysWindowResizeEvent", keepStaticSize, false)<br />
</syntaxhighlight><br />
<br />
{{note}} Mudlet also uses the event system in-game protocols (like ATCP, GMCP and others).<br />
<br />
== Raising a custom event== <br />
To raise an event, you'd use the [[Manual:Lua_Functions#raiseEvent|raiseEvent()]] function:<br />
<br />
<syntaxhighlight lang="lua">raiseEvent(name, [arguments...])</syntaxhighlight><br />
<br />
It takes an event name as the first argument, and then any amount of arguments after it which will be passed onto the receiving functions.<br />
<br />
== Example of registering and raising an event == <br />
Add a script to each profile you need the event.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
-- This is the function that will be called when the event is raised.<br />
-- "event" is set to the event name.<br />
-- "arg" is the argument(s) provided with raiseEvent/rasieGlobalEvent.<br />
-- "profile" - Is the profile name from where the raiseGlobalEvent where triggered from<br />
-- It is 'nil' if raiseEvent() was used.<br />
function onMyEvent(event, arg, profile)<br />
echo("Event: " .. event .. "\n")<br />
echo("Arg : " .. arg .. "\n")<br />
-- If the event is not raised with raiseGlobalEvent() profile will be 'nil'<br />
echo("Profile: " .. (profile or "Local") .. "\n")<br />
end<br />
<br />
-- Register the event handler.<br />
registerAnonymousEventHandler("my_event", onMyEvent)<br />
</syntaxhighlight><br />
<br />
To raise the event you can call:<br />
<syntaxhighlight lang="lua"><br />
-- Trigger only in the current profile:<br />
raiseEvent("my_event", "Hello world!")<br />
<br />
-- Trigger the event in all OTHER profiles:<br />
raiseGlobalEvent("my_event", "Hello World!")<br />
</syntaxhighlight><br />
<br />
To review, count and extract from an unknown number of arguments received by an event:<br />
<br />
<syntaxhighlight lang="lua"><br />
function eventArgs(...)<br />
local args = {...}<br />
local amount = #args<br />
local first = args[1]<br />
echo("Number of arguments: " .. amount)<br />
echo("\nTable of all arguments: ")<br />
display(args)<br />
echo("First argument: " .. first)<br />
echo("\n\n")<br />
end<br />
</syntaxhighlight><br />
<br />
== Gamepad functionality ==<br />
Gamepad functions are not fully supported with all operating systems and hardware. Windows supports XInput devices like Xbox 360 and Xbox One controllers. DirectInput controllers like a PlayStation 4 controller can be translated to XInput with third party software. Mudlet on Linux can support gamepads but only if you compile it yourself. The automated builds are made using the oldest supported version of Ubuntu, and the [https://doc.qt.io/qt-5/qtgamepad-index.html Qt5 gamepad module] was [https://packages.ubuntu.com/search?keywords=libqt5gamepad5-dev not available on Ubuntu 18.04 LTS].<br />
<br />
==Mudlet-raised events==<br />
Mudlet itself also creates events for your scripts to hook on. The following events are generated currently:<br />
<br />
===AdjustableContainerReposition===<br />
Raised while a [[Manual:Geyser#Adjustable.Container|adjustable container]] is re-positioned. <br />
<br />
<syntaxhighlight lang="lua"><br />
function repositioningContainer(eventName, containerName, width, height, x, y, mouseAction)<br />
print(f"{containerName}: {x}x, {y}y, {width}x{height}, using mouse? {mouseAction}")<br />
end<br />
<br />
registerAnonymousEventHandler("AdjustableContainerReposition", repositioningContainer)<br />
</syntaxhighlight><br />
<br />
===AdjustableContainerRepositionFinish===<br />
Raised when an [[Manual:Geyser#Adjustable.Container|adjustable container]] done being re-positioned.<br />
<br />
<syntaxhighlight lang="lua"><br />
function finishedRepositioning(eventName, containerName, width, height, x, y)<br />
print(f"{containerName}: {x}x, {y}y, {width}x{height}")<br />
end<br />
<br />
registerAnonymousEventHandler("AdjustableContainerRepositionFinish", finishedRepositioning)<br />
</syntaxhighlight><br />
<br />
===channel102Message===<br />
<br />
Raised when a telnet sub-option 102 message is received (which comprises of two numbers passed in the event). This is of particular use with the [http://www.aardwolf.com Aardwolf MUD] who originated this protocol. See [http://forums.mudlet.org/viewtopic.php?f=6&t=1471 this] forum topic for more about the Mudlet Aardwolf GUI that makes use of this.<br />
<br />
===mapModeChangeEvent===<br />
<br />
Raised when the mapper is switching between "view-only" and "editing" mode of the [[Manual:Mapper#Visual_Map_Editor|Visual Map Editor]]. A value of "editing" or "viewing" will be given as argument to indicate which mode was entered.<br />
<br />
===mapOpenEvent===<br />
<br />
Raised when the mapper is opened - either the floating dock or the in-Mudlet widget.<br />
<br />
===sysAppStyleSheetChange===<br />
<br />
Raised when [[Manual:UI_Functions#setAppStyleSheet|setAppStyleSheet]] is called and a new stylesheet applied to Mudlet.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- This will respond to a future (as yet unpublished) addition to the Mudlet code that will allow some<br />
-- of a default application style sheet to be supplied with Mudlet to compensate for some text colors<br />
-- that do not show up equally well in both light and dark desktop themes. That, perhaps, might finally<br />
-- allow different colored texts to be uses again for the trigger item types!<br />
function appStyleSheetChangeEvent( event, tag, source )<br />
if source == "system" then<br />
colorTable = colorTable or {}<br />
if tag == "mudlet-dark-theme" then<br />
colorTable.blue = {64, 64, 255}<br />
colorTable.green = {0, 255, 0}<br />
elseif tag == "mudlet-light-theme" then<br />
colorTable.blue = {0, 0, 255}<br />
colorTable.green = {64, 255, 64}<br />
end<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.19}}<br />
<br />
===sysBufferShrinkEvent===<br />
<br />
Raised when the oldest lines are removed from the back of any console or buffer belonging to a profile because it has reached the limit (either the default or that set by [[Manual:Mudlet_Object_Functions#setConsoleBufferSize|setConsoleBufferSize]]). The two additional arguments within the event are: the name of the console or buffer and the number of lines removed from the beginning of the buffer. This information will be useful for any situation where a line number is being stored as it will need to be decremented by that number of lines in order to continue to refer to the same line (assuming that it is still present - indicated by the number remaining positive) after the oldest ones have been removed.<br />
<br />
{{MudletVersion|4.17}}<br />
<br />
===sysConnectionEvent===<br />
<br />
Raised when the profile becomes connected to a MUD.<br />
<br />
===sysCustomHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#customHTTP|customHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters) and HTTP method.<br />
<br />
See also [[#sysCustomHttpError|sysCustomHttpError]].<br />
<br />
===sysCustomHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#customHTTP|customHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to and HTTP method.<br />
<br />
See also [[#sysCustomHttpDone|sysCustomHttpDone]].<br />
<br />
===sysDataSendRequest===<br />
<br />
Raised right before a command from the send(), sendAll() functions or the command line is sent to the game - useful for keeping track of what your last command was, manipulating input or even denying the command to be sent if necessary with [[Manual:Miscellaneous_Functions#denyCurrentSend|denyCurrentSend()]].<br />
<br />
sysDataSendRequest will send the event name and the command sent (in string form) to the functions registered to it. IE: commandSent in the example below will be "eat hambuger" if the user entered only that into command line and pressed enter, send("eat hamburger"), sendAll("eat humburger", "eat fish") or sendAll("eat fish", "eat humburger")<br />
<br />
Note: if you'll be making use of denyCurrentSend(), you ''really should'' notify the user that you denied their command - unexperienced ones might conclude that your script or Mudlet is buggy if they don't see visual feedback. Do not mis-use this and use it as [http://en.wikipedia.org/wiki/Keylogger keylogger] either.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- cancels all "eat hambuger" commands<br />
function cancelEatHamburger(eventName, commandSent)<br />
if commandSent == "eat hamburger" then<br />
denyCurrentSend() --cancels the command sent.<br />
cecho("<red>Denied! You can't do "..commandSent.." right now.\n")<br />
end --if commandSent == eat hamburger<br />
end<br />
<br />
registerAnonymousEventHandler("sysDataSendRequest", cancelEatHamburger)<br />
</syntaxhighlight><br />
<br />
If you wanted to control input you could set a bool after a trigger.<br />
This is useful if you want alias like control, do not know what text will be entered, but do know a trigger that WILL occur just before the user enters the command.<br />
<br />
<syntaxhighlight lang="lua"><br />
function controlInput(_, command) <br />
if changeCMDInput then<br />
changeCMDInput = false --set this if check to false to it doesn't occur every input<br />
--Also set the bool check BEFORE any send() functions within a sysDataSendRequest function<br />
sendAll(command .. "some target", command .. "some other target", true) --Duplicate and unknown command<br />
denyCurrentSend() --Deny the original command, not the commands sent with sendAll.<br />
end<br />
end<br />
registerAnonymousEventHandler("sysDataSendRequest", controlInput)<br />
</syntaxhighlight><br />
<br />
Take note that functions registered under sysDataSendRequest WILL trigger with ALL commands that are sent.<br />
<br />
===sysDeleteHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#deleteHTTP|deleteHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysDeleteHttpError|sysDeleteHttpError]].<br />
<br />
===sysDeleteHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#deleteHTTP|deleteHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysDeleteHttpDone|sysDeleteHttpDone]].<br />
<br />
===sysDisconnectionEvent===<br />
<br />
Raised when the profile becomes disconnected, either manually or by the game.<br />
<br />
If you'd like to automatically reconnect when you get disconnected, make a new <code>Script</code> and add this inside:<br />
<br />
<syntaxhighlight lang="lua"><br />
registerAnonymousEventHandler("sysDisconnectionEvent", reconnect)<br />
</syntaxhighlight><br />
<br />
===sysDownloadDone===<br />
<br />
Raised when Mudlet is finished downloading a file successfully - the location of the downloaded file is passed as a second argument.<br />
<br />
Example - put it into a new script and save it to run:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create a function to parse the downloaded webpage and display a result<br />
function downloaded_file(_, filename)<br />
-- is the file that downloaded ours?<br />
if not filename:find("achaea-who-count.html", 1, true) then return end<br />
<br />
-- read the contents of the webpage in<br />
local f, s, webpage = io.open(filename)<br />
if f then webpage = f:read("*a"); io.close(f) end<br />
-- delete the file on disk, don't clutter<br />
os.remove(filename)<br />
<br />
-- parse our downloaded file for the player count<br />
local pc = webpage:match([[Total: (%d+) players online]])<br />
display("Achaea has "..tostring(pc).." players on right now.")<br />
end<br />
<br />
-- register our function to run on the event that something was downloaded<br />
registerAnonymousEventHandler("sysDownloadDone", downloaded_file)<br />
<br />
-- download a list of fake users for a demo<br />
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")<br />
</syntaxhighlight><br />
<br />
You should see a result like this:<br />
<br />
[[File:DownloadFile_demo.png|frameless|800px]]<br />
<br />
===sysDownloadError===<br />
<br />
Raised when downloading a file failed - the second argument contains the error message, the third the local filename that was to be used and the actual URL used (might not be the same as what was given if redirection took place).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--if a download fails notify the player.<br />
function downloadErrorEventHandler(event, errorFound, localFilename, usedUrl)<br />
cecho("fuction downloadErrorEventHandler, "..errorFound)<br />
debugc("fuction downloadErrorEventHandler, "..errorFound) --display to error screen in editor<br />
end --function downloadErrorEventHandler<br />
registerAnonymousEventHandler("sysDownloadError", downloadErrorEventHandler)<br />
</syntaxhighlight><br />
<br />
===sysDownloadFileProgress===<br />
<br />
Raised while file is being downloaded to indicate progess of download.<br />
<br />
The arguments passed areː: event name, url of download, bytes downloaded, total bytes (if available).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- will show progress bar while download file and hide it after file download is complete<br />
local progressBar = Geyser.Gauge:new({<br />
name="downloadProgressBar",<br />
x="25%", y="10%",<br />
width="50%", height="5%",<br />
})<br />
progressBar:setFontSize(13)<br />
progressBar:setAlignment("center")<br />
progressBar:hide()<br />
<br />
<br />
local fileUrl = "https://www.mudlet.org/download/Mudlet-4.10.1-linux-x64.AppImage.tar"<br />
local targetFile = getMudletHomeDir() .. "/Mudlet.tar"<br />
function handleProgress(_, url, bytesDownloaded, totalBytes)<br />
if url ~= fileUrl then<br />
return<br />
end<br />
<br />
progressBar:show()<br />
<br />
if not totalBytes then<br />
bytesDownloaded = 0<br />
totalBytes = 1<br />
end<br />
<br />
progressBar:setValue(bytesDownloaded, totalBytes, math.floor((bytesDownloaded / totalBytes) * 100) .. "%")<br />
end<br />
<br />
registerAnonymousEventHandler("sysDownloadFileProgress", handleProgress)<br />
<br />
function hideProgressBar()<br />
tempTimer(3, function() progressBar:hide() end)<br />
end <br />
<br />
registerAnonymousEventHandler("sysDownloadDone", hideProgressBar)<br />
registerAnonymousEventHandler("sysDownloadError", hideProgressBar)<br />
<br />
downloadFile(targetFile, fileUrl)<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.11}}<br />
<br />
===sysDropEvent===<br />
<br />
Raised when a file is dropped on the Mudlet main window or a userwindow.<br />
The arguments passed areː filepath, suffix, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function onDragAndDrop(_, filepath, suffix, xpos, ypos, consolename)<br />
print(string.format("Dropped new file into %s: %s (suffix: %s)", consolename, filepath, suffix))<br />
end<br />
registerAnonymousEventHandler("sysDropEvent", onDragAndDrop)<br />
</syntaxhighlight><br />
<br />
===sysDropUrlEvent===<br />
<br />
Raised when a url is dropped on the Mudlet main window or a userwindow.<br />
As an url at the moment Mudlet understands<br />
The arguments passed areː url, schema, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function onDragAndDropUrl(_, url, schema, xpos, ypos, consolename)<br />
print(string.format("Dropped new url into %s: %s (suffix: %s)", consolename, filepath, suffix))<br />
if schema == "http" or schema == "https" then<br />
print("\nOh boy... this might be a link to some website")<br />
end<br />
end<br />
registerAnonymousEventHandler("sysDropUrlEvent", onDragAndDropUrl)<br />
</syntaxhighlight><br />
<br />
===sysExitEvent===<br />
<br />
Raised when Mudlet is shutting down the profile - a good event to hook onto for saving all of your data.<br />
<br />
===sysGamepadAxisMove===<br />
<br />
Raised when an axis on a gamepad is moved.<br />
<br />
Event handlers receive the device ID, axis number, and the new value as a number.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadButtonPress===<br />
<br />
Raised when a button on a gamepad is pressed down.<br />
<br />
Event handlers receive the device ID, button number, and the new value as a number.<br />
<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadButtonRelease===<br />
<br />
Raised when a button on a gamepad is released.<br />
<br />
Event handlers receive the device ID, button number, and the new value as a number.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadConnected===<br />
<br />
Raised when a [https://en.wikipedia.org/wiki/Gamepad gamepad] is connected. On Windows, this uses the XInput backend.<br />
<br />
Event handlers receive device ID as an argument.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
function noticeConnection(deviceID)<br />
local output = string.format("New gamepad connected: %s\n", deviceID)<br />
echo(output)<br />
end<br />
<br />
function noticeDisconnection(deviceID)<br />
local output = string.format("Gamepad disconnected: %s\n", deviceID)<br />
echo(output)<br />
end<br />
<br />
function noticeButtonPress(deviceID, buttonNumber, valueNumber)<br />
local output = string.format("Button pressed: gamepad %s, button %s, value %s\n", deviceID, buttonNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
function noticeButtonRelease(deviceID, buttonNumber, valueNumber)<br />
local output = string.format("Button released: gamepad %s, button %s, value %s\n", deviceID, buttonNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
function noticeAxis(deviceID, axisNumber, valueNumber)<br />
local output = string.format("Axis moved: gamepad %s, axis %s, value %s\n", deviceID, axisNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
registerAnonymousEventHandler("sysGamepadConnected", noticeConnection)<br />
registerAnonymousEventHandler("sysGamepadDisconnected", noticeDisconnection)<br />
registerAnonymousEventHandler("sysGamepadButtonPress", noticeButtonPress)<br />
registerAnonymousEventHandler("sysGamepadButtonRelease", noticeButtonRelease)<br />
registerAnonymousEventHandler("sysGamepadAxisMove", noticeAxis)<br />
</syntaxhighlight><br />
<br />
===sysGamepadDisconnected===<br />
<br />
Raised when a [https://en.wikipedia.org/wiki/Gamepad gamepad] is disconnected<br />
<br />
Event handlers receive device ID as an argument.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGetHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking Functions#getHTTP|getHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
This event is also raised when a post/put/delete request redirects to a ''GET''.<br />
<br />
See also [[#sysGetHttpError|sysGetHttpError]].<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
===sysGetHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#getHTTP|getHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysGetHttpDone|sysGetHttpDone]].<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
===sysInstall===<br />
<br />
Raised right after a module or package is installed by any means. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed package or module as additional argument.<br />
<br />
{{note}}Installed modules will raise this event handler each time the synced profile is opened. [[#sysInstallModule|sysInstallModule]] and [[#sysInstallPackage|sysInstallPackage]] are not raised by opening profiles.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function myScriptInstalled(_, name)<br />
-- stop if what got installed isn't my thing<br />
if name ~= "my script name here" then return end<br />
<br />
print("Hey, thanks for installing my thing!")<br />
end<br />
registerAnonymousEventHandler("sysInstallPackage", myScriptInstalled)<br />
</syntaxhighlight><br />
<br />
===sysInstallModule===<br />
<br />
Raised right after a module is installed through the module dialog. This can be used to display post-installation information or setup things.<br />
<br />
See also [[#sysLuaInstallModule|sysLuaInstallModule]] for when a module is installed via Lua.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysInstallPackage===<br />
<br />
Raised right after a package is installed by any means. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed package as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysIrcMessage===<br />
<br />
Raised when the IRC client receives an IRC message. The sender's name, channel name, and their message are passed as arguments to this event. <br />
<br />
Starting with Mudlet 3.3, this event changes slightly to provide more information from IRC network messages. Data such as status codes, command responses, or error messages sent by the IRC Server may be formatted as plain text by the client and posted to lua via this event. <br />
<br />
* sender: may be the nick name of an IRC user or the name of the IRC server host, as retrievable by [[Manual:Networking_Functions#getIrcConnectedHost|getIrcConnectedHost()]] <br />
* channel: may not always contain a channel name, but will be the name of the target/recipient of a message or action. In some networks the name may be that of a service (like ''"Auth"'' for example) <br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function onIrcMessage(_, sender, target, message)<br />
echo(string.format('(%s) %s says, "%s"\n', target, sender, message))<br />
end<br />
<br />
registerAnonymousEventHandler("sysIrcMessage", onIrcMessage)<br />
</syntaxhighlight><br />
<br />
To send a message, see [[Manual:Networking_Functions#sendIrc|sendIrc()]].<br />
<br />
===sysLabelDeleted===<br />
<br />
Raised after a label is deleted, with the former label's name as an argument.<br />
<br />
<br />
===sysLoadEvent===<br />
<br />
Raised after Mudlet is done loading the profile, after all of the scripts, packages, and modules are installed. Note that when it does so, it also compiles and runs all scripts - which could be a good idea to initialize everything at once, but beware - scripts are also run when saved. Hence, hooking only on the sysLoadEvent would prevent multiple re-loads as you’re editing the script.<br />
<br />
===sysLuaInstallModule===<br />
<br />
Raised right after a module is installed through the Lua installModule() command. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysLuaUninstallModule===<br />
<br />
Raised right before a module is removed through the lua uninstallModule command. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysManualLocationSetEvent===<br />
<br />
Raised whenever the "set location" command (on the 2D mapper context menu) is used to reposition the current "player room". It provides the room ID of the new room ID that the player has been moved to.<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
===sysMapDownloadEvent===<br />
<br />
Raised whenever an [[Standards:MMP|MMP map]] is downloaded and loaded in.<br />
<br />
===sysMediaFinished===<br />
<br />
Raised when media finishes playing. This can be used in a music player for example to start the next song.<br />
<br />
Event handlers receive the media file name and the file path as additional arguments.<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
===sysPathChanged===<br />
<br />
Raised whenever file or directory added through [[Manual:Lua_Functions#addFileWatch|addFileWatch()]] is modified.<br />
<br />
For directories this event is emitted when the directory at a specified path is modified (e.g., when a file is added or deleted) or removed from disk. Note that if there are several changes during a short period of time, some of the changes might not emit this signal. However, the last change in the sequence of changes will always generate this signal.<br />
<br />
For files this event is emitted when the file at the specified path is modified, renamed or removed from disk.<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", herbsChangedHandler)<br />
</syntaxhighlight><br />
<br />
===sysPostHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#postHTTP|postHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysPostHttpError|sysPostHttpError]].<br />
<br />
===sysPostHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#postHTTP|postHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysPostHttpDone|sysPostHttpDone]].<br />
<br />
===sysProfileFocusChangeEvent===<br />
<br />
:Raised whenever a profile becomes or stops being the foreground one when multi-playing, whether multi-view (show all profiles side-by-side) is active or not. The event comes with a second ''boolean'' argument which is ''true'' if the profile is now the one that has the focus, i.e. will receive keystrokes entered from the keyboard, or ''false'' if the focus has just switched from it to another profile.<br />
<br />
{{MudletVersion|4.17.0}}<br />
<br />
===sysProtocolDisabled===<br />
<br />
Raised whenever a communications protocol is disabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.<br />
<br />
===sysProtocolEnabled===<br />
<br />
Raised whenever a communications protocol is enabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.<br />
<br />
<syntaxhighlight lang="lua"><br />
function onProtocolEnabled(_, protocol)<br />
if protocol == "GMCP" then<br />
print("GMCP enabled! Now we can use GMCP data.")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
===sysPutHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#putHTTP|putHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysPutHttpError|sysPutHttpError]].<br />
<br />
===sysPutHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#putHTTP|putHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysPutHttpDone|sysPutHttpDone]].<br />
<br />
===sysSoundFinished===<br />
<br />
This event is obsolete in Mudlet 4.15. Please replace this with [[Manual:Event_Engine#sysMediaFinished|sysMediaFinished()]]<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysSpeedwalkFinished===<br />
<br />
Raised when a speedwalk finishes, either one started by speedwalk() or the generic mapping script<br />
<br />
===sysSpeedwalkPaused===<br />
<br />
Raised when a speedwalk is paused, either via pauseSpeedwalk() or the generic mapping script.<br />
<br />
===sysSpeedwalkResumed===<br />
<br />
Raised when a speedwalk is resumed after pausing, whether it's the generic mapping script or the resumeSpeedwalk() function<br />
<br />
===sysSpeedwalkStarted===<br />
<br />
Raised when a speedwalk is started, either by the speedwalk() function or the generic mapping script<br />
<br />
===sysSpeedwalkStopped===<br />
<br />
Raised when a speedwalk is stopped prematurely by stopSpeedwalk() or the generic mapping script<br />
<br />
===sysSyncInstallModule===<br />
<br />
Raised right after a module is installed through the "sync" mechanism. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysSyncUninstallModule===<br />
<br />
Raised right before a module is removed through the "sync" mechanism. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysTelnetEvent===<br />
<br />
Raised whenever an unsupported telnet option is encountered, allowing you to handle it yourself. The arguments that get passed with the event are type, telnet option, and the message. <br />
<br />
===sysUninstall===<br />
<br />
Raised right before a module or package is uninstalled by any means. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed package or module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUninstallModule===<br />
<br />
Raised right before a module is removed through the module dialog. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUninstallPackage===<br />
<br />
Raised right before a package is removed by any means. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed package as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUnzipDone===<br />
<br />
Raised when a zip file is successfully unzipped using unzipAsync()<br />
<br />
Event handlers receive the zip file name and the unzip path as additional arguments.<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
===sysUnzipError===<br />
<br />
Raised when a zip file fails to unzip using unzipAsync()<br />
<br />
Event handlers receive the zip file name and the unzip path as additional arguments.<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
===sysUserWindowResizeEvent===<br />
<br />
Raised when a userwindow is resized, with the new height and width coordinates and the windowname passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.<br />
<br />
See alsoː [[#sysWindowResizeEvent|sysWindowResizeEvent]]<br />
<br />
Example<br />
<br />
This sample code will echo whenever a resize happened with the new dimensions:<br />
<br />
<syntaxhighlight lang="lua"><br />
function resizeEvent( event, x, y, windowname )<br />
echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.." windowname="..windowname.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
===sysWindowMousePressEvent===<br />
<br />
Raised when a mouse button is pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). The button number, the x,y coordinates of the click and the windowname are reported.<br />
<br />
{{note}}Windowname reported in Mudlet 4.9+<br />
<br />
See alsoː [[#sysWindowMouseReleaseEvent|sysWindowMouseReleaseEvent]]<br />
<br />
Example<br />
<br />
<syntaxhighlight lang="lua"><br />
function onClickHandler( event, button, x, y, windowname )<br />
echo("CLICK event:"..event.." button="..button.." x="..x.." y="..y.." windowname="..windowname.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
===sysWindowMouseReleaseEvent===<br />
<br />
Raised when a mouse button is released after being pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release).<br />
<br />
See [[#sysWindowMousePressEvent|sysWindowMousePressEvent]] for example use.<br />
<br />
===sysWindowResizeEvent===<br />
<br />
Raised when the main window is resized, or when one of the borders is resized, with the new height and width coordinates passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.<br />
<br />
See alsoː [[#sysUserWindowResizeEvent|sysUserWindowResizeEvent]]<br />
<br />
Example<br />
<br />
This sample code will echo whenever a resize happened with the new dimensions:<br />
<br />
<syntaxhighlight lang="lua"><br />
function resizeEvent( event, x, y )<br />
echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Event_Engine&diff=20357Manual:Event Engine2023-03-17T01:52:56Z<p>Kebap: /* sysInstall */ fix crosslink</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Manual on events, which events exist, how to raise events, how to handle them.}}<br />
=Event System=<br />
<br />
Events in Mudlet allow a paradigm of system-building that is easy to maintain (because if you’d like to restructure something, you’d have to do less work), enables interoperability (making a collection of scripts that work with each other is easier) and enables an event-based way of programming.<br />
<br />
The essentials of it are as such: you use Scripts to define which events a function should listen to, and when the event is raised, the said function(s) will be called. Events can also have function parameters with them, which’ll be passed onto the receiving functions.<br />
<br />
== Registering an event handler via UI ==<br />
Registering an event handler means that you’ll be telling Mudlet what function it should call for you when an event is raised, so it’s a two step process - you need to tell it both what function you’d like to have called, and on what event it should be called.<br />
<br />
To tell it what function should be called, create a new script, and give the script the name of the function you’d like to be called. This is the only time where an items name matters in Mudlet. You can define the function right inside the script as well, if you’d like.<br />
<br />
Next, we tell it what event or events this function should be called on - you can add multiple entries. To do that, enter the events name in the Add User Defined Event Handler: field, press enter, and it’ll go into the list - and that is all.<br />
<br />
== Registering an event from a script ==<br />
You can also register your event with the ''[[Manual:Miscellaneous_Functions#registerAnonymousEventHandler|registerAnonymousEventHandler(event name, function reference, [one shot])]]'' function inside your scripts:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size<br />
function keepStaticSize()<br />
setMainWindowSize(1280,720)<br />
end -- keepStaticSize<br />
<br />
registerAnonymousEventHandler("sysWindowResizeEvent", keepStaticSize, false)<br />
</syntaxhighlight><br />
<br />
{{note}} Mudlet also uses the event system in-game protocols (like ATCP, GMCP and others).<br />
<br />
== Raising a custom event== <br />
To raise an event, you'd use the [[Manual:Lua_Functions#raiseEvent|raiseEvent()]] function:<br />
<br />
<syntaxhighlight lang="lua">raiseEvent(name, [arguments...])</syntaxhighlight><br />
<br />
It takes an event name as the first argument, and then any amount of arguments after it which will be passed onto the receiving functions.<br />
<br />
== Example of registering and raising an event == <br />
Add a script to each profile you need the event.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
-- This is the function that will be called when the event is raised.<br />
-- "event" is set to the event name.<br />
-- "arg" is the argument(s) provided with raiseEvent/rasieGlobalEvent.<br />
-- "profile" - Is the profile name from where the raiseGlobalEvent where triggered from<br />
-- It is 'nil' if raiseEvent() was used.<br />
function onMyEvent(event, arg, profile)<br />
echo("Event: " .. event .. "\n")<br />
echo("Arg : " .. arg .. "\n")<br />
-- If the event is not raised with raiseGlobalEvent() profile will be 'nil'<br />
echo("Profile: " .. (profile or "Local") .. "\n")<br />
end<br />
<br />
-- Register the event handler.<br />
registerAnonymousEventHandler("my_event", onMyEvent)<br />
</syntaxhighlight><br />
<br />
To raise the event you can call:<br />
<syntaxhighlight lang="lua"><br />
-- Trigger only in the current profile:<br />
raiseEvent("my_event", "Hello world!")<br />
<br />
-- Trigger the event in all OTHER profiles:<br />
raiseGlobalEvent("my_event", "Hello World!")<br />
</syntaxhighlight><br />
<br />
To review, count and extract from an unknown number of arguments received by an event:<br />
<br />
<syntaxhighlight lang="lua"><br />
function eventArgs(...)<br />
local args = {...}<br />
local amount = #args<br />
local first = args[1]<br />
echo("Number of arguments: " .. amount)<br />
echo("\nTable of all arguments: ")<br />
display(args)<br />
echo("First argument: " .. first)<br />
echo("\n\n")<br />
end<br />
</syntaxhighlight><br />
<br />
== Gamepad functionality ==<br />
Gamepad functions are not fully supported with all operating systems and hardware. Windows supports XInput devices like Xbox 360 and Xbox One controllers. DirectInput controllers like a PlayStation 4 controller can be translated to XInput with third party software. Mudlet on Linux can support gamepads but only if you compile it yourself. The automated builds are made using the oldest supported version of Ubuntu, and the [https://doc.qt.io/qt-5/qtgamepad-index.html Qt5 gamepad module] was [https://packages.ubuntu.com/search?keywords=libqt5gamepad5-dev not available on Ubuntu 18.04 LTS].<br />
<br />
==Mudlet-raised events==<br />
Mudlet itself also creates events for your scripts to hook on. The following events are generated currently:<br />
<br />
===AdjustableContainerReposition===<br />
Raised while a [[Manual:Geyser#Adjustable.Container|adjustable container]] is re-positioned. <br />
<br />
<syntaxhighlight lang="lua"><br />
function repositioningContainer(eventName, containerName, width, height, x, y, mouseAction)<br />
print(f"{containerName}: {x}x, {y}y, {width}x{height}, using mouse? {mouseAction}")<br />
end<br />
<br />
registerAnonymousEventHandler("AdjustableContainerReposition", repositioningContainer)<br />
</syntaxhighlight><br />
<br />
===AdjustableContainerRepositionFinish===<br />
Raised when an [[Manual:Geyser#Adjustable.Container|adjustable container]] done being re-positioned.<br />
<br />
<syntaxhighlight lang="lua"><br />
function finishedRepositioning(eventName, containerName, width, height, x, y)<br />
print(f"{containerName}: {x}x, {y}y, {width}x{height}")<br />
end<br />
<br />
registerAnonymousEventHandler("AdjustableContainerRepositionFinish", finishedRepositioning)<br />
</syntaxhighlight><br />
<br />
===channel102Message===<br />
<br />
Raised when a telnet sub-option 102 message is received (which comprises of two numbers passed in the event). This is of particular use with the [http://www.aardwolf.com Aardwolf MUD] who originated this protocol. See [http://forums.mudlet.org/viewtopic.php?f=6&t=1471 this] forum topic for more about the Mudlet Aardwolf GUI that makes use of this.<br />
<br />
===mapModeChangeEvent===<br />
<br />
Raised when the mapper is switching between "view-only" and "editing" mode of the [[Manual:Mapper#Visual_Map_Editor|Visual Map Editor]]. A value of "editing" or "viewing" will be given as argument to indicate which mode was entered.<br />
<br />
===mapOpenEvent===<br />
<br />
Raised when the mapper is opened - either the floating dock or the in-Mudlet widget.<br />
<br />
===sysAppStyleSheetChange===<br />
<br />
Raised when [[Manual:UI_Functions#setAppStyleSheet|setAppStyleSheet]] is called and a new stylesheet applied to Mudlet.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- This will respond to a future (as yet unpublished) addition to the Mudlet code that will allow some<br />
-- of a default application style sheet to be supplied with Mudlet to compensate for some text colors<br />
-- that do not show up equally well in both light and dark desktop themes. That, perhaps, might finally<br />
-- allow different colored texts to be uses again for the trigger item types!<br />
function appStyleSheetChangeEvent( event, tag, source )<br />
if source == "system" then<br />
colorTable = colorTable or {}<br />
if tag == "mudlet-dark-theme" then<br />
colorTable.blue = {64, 64, 255}<br />
colorTable.green = {0, 255, 0}<br />
elseif tag == "mudlet-light-theme" then<br />
colorTable.blue = {0, 0, 255}<br />
colorTable.green = {64, 255, 64}<br />
end<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.19}}<br />
<br />
===sysBufferShrinkEvent===<br />
<br />
Raised when the oldest lines are removed from the back of any console or buffer belonging to a profile because it has reached the limit (either the default or that set by [[Manual:Mudlet_Object_Functions#setConsoleBufferSize|setConsoleBufferSize]]). The two additional arguments within the event are: the name of the console or buffer and the number of lines removed from the beginning of the buffer. This information will be useful for any situation where a line number is being stored as it will need to be decremented by that number of lines in order to continue to refer to the same line (assuming that it is still present - indicated by the number remaining positive) after the oldest ones have been removed.<br />
<br />
{{MudletVersion|4.17}}<br />
<br />
===sysConnectionEvent===<br />
<br />
Raised when the profile becomes connected to a MUD.<br />
<br />
===sysCustomHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#customHTTP|customHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters) and HTTP method.<br />
<br />
See also [[#sysCustomHttpError|sysCustomHttpError]].<br />
<br />
===sysCustomHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#customHTTP|customHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to and HTTP method.<br />
<br />
See also [[#sysCustomHttpDone|sysCustomHttpDone]].<br />
<br />
===sysDataSendRequest===<br />
<br />
Raised right before a command from the send(), sendAll() functions or the command line is sent to the game - useful for keeping track of what your last command was, manipulating input or even denying the command to be sent if necessary with [[Manual:Miscellaneous_Functions#denyCurrentSend|denyCurrentSend()]].<br />
<br />
sysDataSendRequest will send the event name and the command sent (in string form) to the functions registered to it. IE: commandSent in the example below will be "eat hambuger" if the user entered only that into command line and pressed enter, send("eat hamburger"), sendAll("eat humburger", "eat fish") or sendAll("eat fish", "eat humburger")<br />
<br />
Note: if you'll be making use of denyCurrentSend(), you ''really should'' notify the user that you denied their command - unexperienced ones might conclude that your script or Mudlet is buggy if they don't see visual feedback. Do not mis-use this and use it as [http://en.wikipedia.org/wiki/Keylogger keylogger] either.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- cancels all "eat hambuger" commands<br />
function cancelEatHamburger(eventName, commandSent)<br />
if commandSent == "eat hamburger" then<br />
denyCurrentSend() --cancels the command sent.<br />
cecho("<red>Denied! You can't do "..commandSent.." right now.\n")<br />
end --if commandSent == eat hamburger<br />
end<br />
<br />
registerAnonymousEventHandler("sysDataSendRequest", cancelEatHamburger)<br />
</syntaxhighlight><br />
<br />
If you wanted to control input you could set a bool after a trigger.<br />
This is useful if you want alias like control, do not know what text will be entered, but do know a trigger that WILL occur just before the user enters the command.<br />
<br />
<syntaxhighlight lang="lua"><br />
function controlInput(_, command) <br />
if changeCMDInput then<br />
changeCMDInput = false --set this if check to false to it doesn't occur every input<br />
--Also set the bool check BEFORE any send() functions within a sysDataSendRequest function<br />
sendAll(command .. "some target", command .. "some other target", true) --Duplicate and unknown command<br />
denyCurrentSend() --Deny the original command, not the commands sent with sendAll.<br />
end<br />
end<br />
registerAnonymousEventHandler("sysDataSendRequest", controlInput)<br />
</syntaxhighlight><br />
<br />
Take note that functions registered under sysDataSendRequest WILL trigger with ALL commands that are sent.<br />
<br />
===sysDeleteHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#deleteHTTP|deleteHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysDeleteHttpError|sysDeleteHttpError]].<br />
<br />
===sysDeleteHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#deleteHTTP|deleteHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysDeleteHttpDone|sysDeleteHttpDone]].<br />
<br />
===sysDisconnectionEvent===<br />
<br />
Raised when the profile becomes disconnected, either manually or by the game.<br />
<br />
If you'd like to automatically reconnect when you get disconnected, make a new <code>Script</code> and add this inside:<br />
<br />
<syntaxhighlight lang="lua"><br />
registerAnonymousEventHandler("sysDisconnectionEvent", reconnect)<br />
</syntaxhighlight><br />
<br />
===sysDownloadDone===<br />
<br />
Raised when Mudlet is finished downloading a file successfully - the location of the downloaded file is passed as a second argument.<br />
<br />
Example - put it into a new script and save it to run:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create a function to parse the downloaded webpage and display a result<br />
function downloaded_file(_, filename)<br />
-- is the file that downloaded ours?<br />
if not filename:find("achaea-who-count.html", 1, true) then return end<br />
<br />
-- read the contents of the webpage in<br />
local f, s, webpage = io.open(filename)<br />
if f then webpage = f:read("*a"); io.close(f) end<br />
-- delete the file on disk, don't clutter<br />
os.remove(filename)<br />
<br />
-- parse our downloaded file for the player count<br />
local pc = webpage:match([[Total: (%d+) players online]])<br />
display("Achaea has "..tostring(pc).." players on right now.")<br />
end<br />
<br />
-- register our function to run on the event that something was downloaded<br />
registerAnonymousEventHandler("sysDownloadDone", downloaded_file)<br />
<br />
-- download a list of fake users for a demo<br />
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")<br />
</syntaxhighlight><br />
<br />
You should see a result like this:<br />
<br />
[[File:DownloadFile_demo.png|frameless|800px]]<br />
<br />
===sysDownloadError===<br />
<br />
Raised when downloading a file failed - the second argument contains the error message, the third the local filename that was to be used and the actual URL used (might not be the same as what was given if redirection took place).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--if a download fails notify the player.<br />
function downloadErrorEventHandler(event, errorFound, localFilename, usedUrl)<br />
cecho("fuction downloadErrorEventHandler, "..errorFound)<br />
debugc("fuction downloadErrorEventHandler, "..errorFound) --display to error screen in editor<br />
end --function downloadErrorEventHandler<br />
registerAnonymousEventHandler("sysDownloadError", downloadErrorEventHandler)<br />
</syntaxhighlight><br />
<br />
===sysDownloadFileProgress===<br />
<br />
Raised while file is being downloaded to indicate progess of download.<br />
<br />
The arguments passed areː: event name, url of download, bytes downloaded, total bytes (if available).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- will show progress bar while download file and hide it after file download is complete<br />
local progressBar = Geyser.Gauge:new({<br />
name="downloadProgressBar",<br />
x="25%", y="10%",<br />
width="50%", height="5%",<br />
})<br />
progressBar:setFontSize(13)<br />
progressBar:setAlignment("center")<br />
progressBar:hide()<br />
<br />
<br />
local fileUrl = "https://www.mudlet.org/download/Mudlet-4.10.1-linux-x64.AppImage.tar"<br />
local targetFile = getMudletHomeDir() .. "/Mudlet.tar"<br />
function handleProgress(_, url, bytesDownloaded, totalBytes)<br />
if url ~= fileUrl then<br />
return<br />
end<br />
<br />
progressBar:show()<br />
<br />
if not totalBytes then<br />
bytesDownloaded = 0<br />
totalBytes = 1<br />
end<br />
<br />
progressBar:setValue(bytesDownloaded, totalBytes, math.floor((bytesDownloaded / totalBytes) * 100) .. "%")<br />
end<br />
<br />
registerAnonymousEventHandler("sysDownloadFileProgress", handleProgress)<br />
<br />
function hideProgressBar()<br />
tempTimer(3, function() progressBar:hide() end)<br />
end <br />
<br />
registerAnonymousEventHandler("sysDownloadDone", hideProgressBar)<br />
registerAnonymousEventHandler("sysDownloadError", hideProgressBar)<br />
<br />
downloadFile(targetFile, fileUrl)<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.11}}<br />
<br />
===sysDropEvent===<br />
<br />
Raised when a file is dropped on the Mudlet main window or a userwindow.<br />
The arguments passed areː filepath, suffix, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function onDragAndDrop(_, filepath, suffix, xpos, ypos, consolename)<br />
print(string.format("Dropped new file into %s: %s (suffix: %s)", consolename, filepath, suffix))<br />
end<br />
registerAnonymousEventHandler("sysDropEvent", onDragAndDrop)<br />
</syntaxhighlight><br />
<br />
===sysDropUrlEvent===<br />
<br />
Raised when a url is dropped on the Mudlet main window or a userwindow.<br />
As an url at the moment Mudlet understands<br />
The arguments passed areː url, schema, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function onDragAndDropUrl(_, url, schema, xpos, ypos, consolename)<br />
print(string.format("Dropped new url into %s: %s (suffix: %s)", consolename, filepath, suffix))<br />
if schema == "http" or schema == "https" then<br />
print("\nOh boy... this might be a link to some website")<br />
end<br />
end<br />
registerAnonymousEventHandler("sysDropUrlEvent", onDragAndDropUrl)<br />
</syntaxhighlight><br />
<br />
===sysExitEvent===<br />
<br />
Raised when Mudlet is shutting down the profile - a good event to hook onto for saving all of your data.<br />
<br />
===sysGamepadAxisMove===<br />
<br />
Raised when an axis on a gamepad is moved.<br />
<br />
Event handlers receive the device ID, axis number, and the new value as a number.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadButtonPress===<br />
<br />
Raised when a button on a gamepad is pressed down.<br />
<br />
Event handlers receive the device ID, button number, and the new value as a number.<br />
<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadButtonRelease===<br />
<br />
Raised when a button on a gamepad is released.<br />
<br />
Event handlers receive the device ID, button number, and the new value as a number.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadConnected===<br />
<br />
Raised when a [https://en.wikipedia.org/wiki/Gamepad gamepad] is connected. On Windows, this uses the XInput backend.<br />
<br />
Event handlers receive device ID as an argument.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
function noticeConnection(deviceID)<br />
local output = string.format("New gamepad connected: %s\n", deviceID)<br />
echo(output)<br />
end<br />
<br />
function noticeDisconnection(deviceID)<br />
local output = string.format("Gamepad disconnected: %s\n", deviceID)<br />
echo(output)<br />
end<br />
<br />
function noticeButtonPress(deviceID, buttonNumber, valueNumber)<br />
local output = string.format("Button pressed: gamepad %s, button %s, value %s\n", deviceID, buttonNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
function noticeButtonRelease(deviceID, buttonNumber, valueNumber)<br />
local output = string.format("Button released: gamepad %s, button %s, value %s\n", deviceID, buttonNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
function noticeAxis(deviceID, axisNumber, valueNumber)<br />
local output = string.format("Axis moved: gamepad %s, axis %s, value %s\n", deviceID, axisNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
registerAnonymousEventHandler("sysGamepadConnected", noticeConnection)<br />
registerAnonymousEventHandler("sysGamepadDisconnected", noticeDisconnection)<br />
registerAnonymousEventHandler("sysGamepadButtonPress", noticeButtonPress)<br />
registerAnonymousEventHandler("sysGamepadButtonRelease", noticeButtonRelease)<br />
registerAnonymousEventHandler("sysGamepadAxisMove", noticeAxis)<br />
</syntaxhighlight><br />
<br />
===sysGamepadDisconnected===<br />
<br />
Raised when a [https://en.wikipedia.org/wiki/Gamepad gamepad] is disconnected<br />
<br />
Event handlers receive device ID as an argument.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGetHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking Functions#getHTTP|getHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
This event is also raised when a post/put/delete request redirects to a ''GET''.<br />
<br />
See also [[#sysGetHttpError|sysGetHttpError]].<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
===sysGetHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#getHTTP|getHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysGetHttpDone|sysGetHttpDone]].<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
===sysInstall===<br />
<br />
Raised right after a module or package is installed by any means. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed package or module as additional argument.<br />
<br />
{{note}}Installed modules will raise this event handler each time the synced profile is opened. [[#sysInstallModule|sysInstallModule]] and [[#sysInstallPackage|sysInstallPackage]] are not raised by opening profiles.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function myScriptInstalled(_, name)<br />
-- stop if what got installed isn't my thing<br />
if name ~= "my script name here" then return end<br />
<br />
print("Hey, thanks for installing my thing!")<br />
end<br />
registerAnonymousEventHandler("sysInstallPackage", myScriptInstalled)<br />
</syntaxhighlight><br />
<br />
===sysInstallModule===<br />
<br />
Raised right after a module is installed through the module dialog. This can be used to display post-installation information or setup things.<br />
<br />
See also [[sysLuaInstallModule]] for when a module is installed via Lua.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysInstallPackage===<br />
<br />
Raised right after a package is installed by any means. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed package as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysIrcMessage===<br />
<br />
Raised when the IRC client receives an IRC message. The sender's name, channel name, and their message are passed as arguments to this event. <br />
<br />
Starting with Mudlet 3.3, this event changes slightly to provide more information from IRC network messages. Data such as status codes, command responses, or error messages sent by the IRC Server may be formatted as plain text by the client and posted to lua via this event. <br />
<br />
* sender: may be the nick name of an IRC user or the name of the IRC server host, as retrievable by [[Manual:Networking_Functions#getIrcConnectedHost|getIrcConnectedHost()]] <br />
* channel: may not always contain a channel name, but will be the name of the target/recipient of a message or action. In some networks the name may be that of a service (like ''"Auth"'' for example) <br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function onIrcMessage(_, sender, target, message)<br />
echo(string.format('(%s) %s says, "%s"\n', target, sender, message))<br />
end<br />
<br />
registerAnonymousEventHandler("sysIrcMessage", onIrcMessage)<br />
</syntaxhighlight><br />
<br />
To send a message, see [[Manual:Networking_Functions#sendIrc|sendIrc()]].<br />
<br />
===sysLabelDeleted===<br />
<br />
Raised after a label is deleted, with the former label's name as an argument.<br />
<br />
<br />
===sysLoadEvent===<br />
<br />
Raised after Mudlet is done loading the profile, after all of the scripts, packages, and modules are installed. Note that when it does so, it also compiles and runs all scripts - which could be a good idea to initialize everything at once, but beware - scripts are also run when saved. Hence, hooking only on the sysLoadEvent would prevent multiple re-loads as you’re editing the script.<br />
<br />
===sysLuaInstallModule===<br />
<br />
Raised right after a module is installed through the Lua installModule() command. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysLuaUninstallModule===<br />
<br />
Raised right before a module is removed through the lua uninstallModule command. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysManualLocationSetEvent===<br />
<br />
Raised whenever the "set location" command (on the 2D mapper context menu) is used to reposition the current "player room". It provides the room ID of the new room ID that the player has been moved to.<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
===sysMapDownloadEvent===<br />
<br />
Raised whenever an [[Standards:MMP|MMP map]] is downloaded and loaded in.<br />
<br />
===sysMediaFinished===<br />
<br />
Raised when media finishes playing. This can be used in a music player for example to start the next song.<br />
<br />
Event handlers receive the media file name and the file path as additional arguments.<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
===sysPathChanged===<br />
<br />
Raised whenever file or directory added through [[Manual:Lua_Functions#addFileWatch|addFileWatch()]] is modified.<br />
<br />
For directories this event is emitted when the directory at a specified path is modified (e.g., when a file is added or deleted) or removed from disk. Note that if there are several changes during a short period of time, some of the changes might not emit this signal. However, the last change in the sequence of changes will always generate this signal.<br />
<br />
For files this event is emitted when the file at the specified path is modified, renamed or removed from disk.<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", herbsChangedHandler)<br />
</syntaxhighlight><br />
<br />
===sysPostHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#postHTTP|postHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysPostHttpError|sysPostHttpError]].<br />
<br />
===sysPostHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#postHTTP|postHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysPostHttpDone|sysPostHttpDone]].<br />
<br />
===sysProfileFocusChangeEvent===<br />
<br />
:Raised whenever a profile becomes or stops being the foreground one when multi-playing, whether multi-view (show all profiles side-by-side) is active or not. The event comes with a second ''boolean'' argument which is ''true'' if the profile is now the one that has the focus, i.e. will receive keystrokes entered from the keyboard, or ''false'' if the focus has just switched from it to another profile.<br />
<br />
{{MudletVersion|4.17.0}}<br />
<br />
===sysProtocolDisabled===<br />
<br />
Raised whenever a communications protocol is disabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.<br />
<br />
===sysProtocolEnabled===<br />
<br />
Raised whenever a communications protocol is enabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.<br />
<br />
<syntaxhighlight lang="lua"><br />
function onProtocolEnabled(_, protocol)<br />
if protocol == "GMCP" then<br />
print("GMCP enabled! Now we can use GMCP data.")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
===sysPutHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#putHTTP|putHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysPutHttpError|sysPutHttpError]].<br />
<br />
===sysPutHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#putHTTP|putHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysPutHttpDone|sysPutHttpDone]].<br />
<br />
===sysSoundFinished===<br />
<br />
This event is obsolete in Mudlet 4.15. Please replace this with [[Manual:Event_Engine#sysMediaFinished|sysMediaFinished()]]<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysSpeedwalkFinished===<br />
<br />
Raised when a speedwalk finishes, either one started by speedwalk() or the generic mapping script<br />
<br />
===sysSpeedwalkPaused===<br />
<br />
Raised when a speedwalk is paused, either via pauseSpeedwalk() or the generic mapping script.<br />
<br />
===sysSpeedwalkResumed===<br />
<br />
Raised when a speedwalk is resumed after pausing, whether it's the generic mapping script or the resumeSpeedwalk() function<br />
<br />
===sysSpeedwalkStarted===<br />
<br />
Raised when a speedwalk is started, either by the speedwalk() function or the generic mapping script<br />
<br />
===sysSpeedwalkStopped===<br />
<br />
Raised when a speedwalk is stopped prematurely by stopSpeedwalk() or the generic mapping script<br />
<br />
===sysSyncInstallModule===<br />
<br />
Raised right after a module is installed through the "sync" mechanism. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysSyncUninstallModule===<br />
<br />
Raised right before a module is removed through the "sync" mechanism. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysTelnetEvent===<br />
<br />
Raised whenever an unsupported telnet option is encountered, allowing you to handle it yourself. The arguments that get passed with the event are type, telnet option, and the message. <br />
<br />
===sysUninstall===<br />
<br />
Raised right before a module or package is uninstalled by any means. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed package or module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUninstallModule===<br />
<br />
Raised right before a module is removed through the module dialog. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUninstallPackage===<br />
<br />
Raised right before a package is removed by any means. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed package as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUnzipDone===<br />
<br />
Raised when a zip file is successfully unzipped using unzipAsync()<br />
<br />
Event handlers receive the zip file name and the unzip path as additional arguments.<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
===sysUnzipError===<br />
<br />
Raised when a zip file fails to unzip using unzipAsync()<br />
<br />
Event handlers receive the zip file name and the unzip path as additional arguments.<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
===sysUserWindowResizeEvent===<br />
<br />
Raised when a userwindow is resized, with the new height and width coordinates and the windowname passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.<br />
<br />
See alsoː [[#sysWindowResizeEvent|sysWindowResizeEvent]]<br />
<br />
Example<br />
<br />
This sample code will echo whenever a resize happened with the new dimensions:<br />
<br />
<syntaxhighlight lang="lua"><br />
function resizeEvent( event, x, y, windowname )<br />
echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.." windowname="..windowname.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
===sysWindowMousePressEvent===<br />
<br />
Raised when a mouse button is pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). The button number, the x,y coordinates of the click and the windowname are reported.<br />
<br />
{{note}}Windowname reported in Mudlet 4.9+<br />
<br />
See alsoː [[#sysWindowMouseReleaseEvent|sysWindowMouseReleaseEvent]]<br />
<br />
Example<br />
<br />
<syntaxhighlight lang="lua"><br />
function onClickHandler( event, button, x, y, windowname )<br />
echo("CLICK event:"..event.." button="..button.." x="..x.." y="..y.." windowname="..windowname.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
===sysWindowMouseReleaseEvent===<br />
<br />
Raised when a mouse button is released after being pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release).<br />
<br />
See [[#sysWindowMousePressEvent|sysWindowMousePressEvent]] for example use.<br />
<br />
===sysWindowResizeEvent===<br />
<br />
Raised when the main window is resized, or when one of the borders is resized, with the new height and width coordinates passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.<br />
<br />
See alsoː [[#sysUserWindowResizeEvent|sysUserWindowResizeEvent]]<br />
<br />
Example<br />
<br />
This sample code will echo whenever a resize happened with the new dimensions:<br />
<br />
<syntaxhighlight lang="lua"><br />
function resizeEvent( event, x, y )<br />
echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Compiling_Mudlet&diff=20356Compiling Mudlet2023-03-16T20:44:01Z<p>Kebap: /* CLion setup on Windows */ update boost library version number</p>
<hr />
<div>{{TOC right}}<br />
<br />
If you just want to use Mudlet, you can skip these steps, and use one of the already ready (pre-compiled) installers [https://www.mudlet.org/download ready for download].<br />
<br />
Otherwise, hop in for new adventure! <br />
<br />
[[File:Easy Mudlet code understanding.png|frame|none]]<br />
<br />
= Key contributing information =<br />
<br />
Clang format is used to automatically format code submissions using the [https://github.com/Mudlet/Mudlet/blob/development/src/.clang-format src/.clang-format] style. [http://doc.qt.io/qtcreator/creator-beautifier.html See here] how to enable clang-format with Qt Creator - and make sure to specify the 'File' option for the configuration style.<br />
<br />
Branches:<br />
<br />
'''development''' is the development branch where new features can go.<br />
<br />
Workflow:<br />
<br />
Fork and submit a PR with your changes ([https://guides.github.com/activities/forking/ Github tutorial]).<br />
<br />
Here is a list of package versions delivered with different Linux distros. You may want to upgrade these: <br />
https://repology.org/project/mudlet/versions<br />
<br />
= Lua & Luarocks =<br />
<br />
Mudlet includes a [https://en.wikipedia.org/wiki/Lua_(programming_language) Lua] (version 5.1) scripting system for the end-user, which you, as a reader of this Wiki, may already be aware of! If not, you might wish to (after you have got your hands on a working Mudlet) take a look at [https://wiki.mudlet.org/w/Manual:Lua_Functions Mudlet Lua API] as that is the recommended place to find out the details of all the functions that Mudlet provides on top of the core Lua functionality.<br />
<br />
Some of that ability comes from extra code that is not built-in to Lua but is in the form of external modules either in the form of script (text) files written in the Lua language itself or binary (library) files compiled from (usually but not exclusively [https://en.wikipedia.org/wiki/C_(programming_language) 'C']) source code. In order to have that functionality Mudlet makes use of several of these modules which can most readily (if not already available as "packages" for a particular Operating System) be obtained as '''rocks''' from the public [https://en.wikipedia.org/wiki/LuaRocks Luarocks] collection. Such a rock actually consists of a ''rockspec'' file that gives instructions to the Luarocks tool how to obtains the (source) code, compile it on any supported OS into the form that a Lua interpreter (including the one included in '''''each''''' running Mudlet ''profile'') can use, and where and what it will be placed and called when it has been made. After that it should be available to Lua via the ''require'' command.<br />
<br />
Anyone compiling Mudlet for themselves will find it desirable to ensure they have a usable Luarocks installation and have the ''lua-yajl'' module installed before commencing to compile Mudlet itself; this is because a Lua (version 5.1) interpreter and that module are used within the build process of making the executable code that is the Mudlet application.<br />
<br />
= Compiling =<br />
<br />
== Compiling on Ubuntu ==<br />
<br />
These instructions will get you setup compiling on Ubuntu. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
===Ubuntu 22.04===<br />
Following instructions will work on Ubuntu 22.04 as well as all its flavours and derivatives (such as KDE Neon, for example)<br />
Important thing is to have ''Universe'' repository enabled in your package manager. (on Ubuntu you will have all the repositories that you need already enabled by default.)<br />
<br />
'''1. necessary dependencies'''<br />
<br />
Majority of required dependencies can be obtained from repositories, and can be installed with following command:<br />
<br />
sudo apt install ubuntu-restricted-extras qtcreator build-essential git zlib1g-dev libhunspell-dev \<br />
libpcre3-dev libzip-dev libboost-dev libboost-all-dev libyajl-dev libpulse-dev libpugixml-dev \<br />
liblua5.1-0-dev lua-filesystem lua-zip lua-sql-sqlite3 luarocks ccache lua5.1 \<br />
libglu1-mesa-dev mesa-common-dev libglib2.0-dev libgstreamer1.0-dev libqt5opengl5-dev \<br />
qtmultimedia5-dev qttools5-dev qt5keychain-dev libsecret-1-dev \<br />
libqt5texttospeech5-dev qtspeech5-flite-plugin qtspeech5-speechd-plugin \<br />
qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev<br />
<br />
Few of required Lua modules are not available in official repositories, so they have to be installed using ''luarocks''<br />
sudo luarocks install lcf<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
sudo luarocks install lrexlib-pcre<br />
<br />
'''2. obtaining the source code'''<br />
<br />
Obtain the latest in-development code with:<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
mkdir Mudlet/build<br />
cd Mudlet/build<br />
<br />
'''3. compiling the code'''<br />
<br />
There below are two ways to build with qmake, the first is for general use, the second is for developers:<br />
qmake ../src/mudlet.pro<br />
'''*OR*'''<br />
qmake CONFIG+=debug ../src/mudlet.pro<br />
<br />
'''Now finish compiling:'''<br />
make -j `nproc`<br />
<br />
4. '''installing compiled code'''<br />
<br />
After successful code compilation, next few commands will install resulting binaries, desktop file for menus and appropriate icon.<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
5. '''optional additional software'''<br />
<br />
One of the major reasons for compiling Mudlet from source is the ability to unlock more features that are not enabled in official AppImage.<br />
Manual compilation will resolve the issues with sound by using system provided libraries, as well as enable more detailed theming of Mudlet application itself.<br />
However, do take note that Mudlet is a Qt based program, and that theming will not 'just work' in GTK based desktop environments (Gnome, XFCE, MATE, Budgie).<br />
sudo apt install qt5ct<br />
will install a tool for configuration of look and feel of Qt programs inside those desktop environments.<br />
Users of Qt based Desktop environments (KDE Plasma, LXQT) can simply use settings provided by environment itself.<br />
<br />
Many of Qt widget styles and color schemes are available in official repositories, and will make Mudlet better.<br />
<br />
6. '''Mudlet on Wayland'''<br />
<br />
Mudlet compiled like this will run and work on Wayland, however, there are a few quirks with Keybidings (Numpad may not work as expected).<br />
Until that is resolved you may wish to start mudlet with:<br />
QT_QPA_PLATFORM=xcb mudlet<br />
(enter in terminal or simply change the Exec= line in /usr/share/applications/mudlet.desktop)<br />
<br />
7. '''uninstallation'''<br />
<br />
You can reverse the process described in this guide with following command:<br />
<br />
sudo rm -fr /usr/bin/mudlet /usr/share/mudlet /usr/share/applications/mudlet.desktop /usr/share/pixmaps/mudlet.png<br />
<br />
===Other Ubuntu Versions===<br />
<br />
Most of the installation instructions for 22.04 should work for older versions as well. Of note is the required version of Qt, which is 5.14. If your used version of Ubuntu only supplies older<br />
Qt versions, have a look at [https://launchpad.net/~beineri Stephan Binners PPAs], which supplies a whole range of packages for different Ubuntu versions. Be sure to read the installation and<br />
usage instructions as Qt is installed to /opt and requires sourcing a script to set up.<br />
<br />
== Compiling on Chrome OS ==<br />
<br />
These instructions will get you setup compiling on Chrome OS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Install dependencies'''<br />
<br />
sudo apt install git build-essential qt5-default qtmultimedia5-dev qttools5-dev \<br />
lua5.1 liblua5.1-0-dev libpcre3-dev libboost-dev zlib1g-dev cmake \<br />
libhunspell-dev lua-rex-pcre lua-sql-sqlite3 lua-filesystem lua-zip libyajl-dev \<br />
libzip-dev libglu1-mesa-dev ccache libpugixml-dev mesa-common-dev qtcreator \<br />
libpulse-dev libglib2.0-dev luarocks libboost-all-dev libsecret-1-dev \<br />
ninja-build libsecret-1-dev<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''3. Get Mudlet source'''<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''4. Create a build directory'''<br />
<br />
cd mudlet<br />
mkdir build && cd build<br />
<br />
'''5. Run the following command '''<br />
<br />
cmake .. -G Ninja<br />
<br />
'''then:'''<br />
<br />
ninja<br />
<br />
'''5. Start the application you have just compiled - enjoy'''<br />
<br />
src/mudlet<br />
{{Note}}Did <code>ninja</code> fail with <code>c++: fatal error: Killed signal terminated program cclplus</code>? Try again with <code>ninja -j 2</code><br />
<br />
== Compiling on macOS ==<br />
<br />
These instructions will get you setup compiling on macOS. Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums] otherwise.<br />
<br />
<br />
'''1. Install prerequisites'''<br />
<br />
Install [https://itunes.apple.com/us/app/xcode/id497799835?ls=1&mt=12 XCode], command line tools for XCode, and [http://brew.sh HomeBrew].<br />
<br />
Once everything is installed, do:<br />
<br />
brew doctor<br />
brew update<br />
brew install git<br />
<br />
'''2. Get Mudlet source'''<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git <br />
<br />
'''3. Go to the parent of the mudlet "src" folder and create (if necessary) a build subdirectory (this is so that we can build out of source which keeps the source code clean)'''<br />
cd Mudlet && mkdir build<br />
<br />
'''3. Setup your environment'''<br />
./CI/travis.osx.before_install.sh<br />
./CI/travis.osx.install.sh<br />
<br />
luarocks config lua_version 5.1<br />
eval `luarocks path --lua-version=5.1`<br />
For the following, one may have to add <code>''_DIR="/opt/homebrew/"''</code> such as <code>PCRE_DIR="/opt/homebrew/"</code> or <code>ZIP_DIR="/opt/homebrew/"</code> if the installation could not find header files.<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lrexlib-pcre PCRE_DIR=`brew --prefix pcre`<br />
brew install sqlite<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luasql-sqlite3 SQLITE_DIR=`brew --prefix sqlite` <br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luautf8<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-yajl YAJL_LIBDIR=`brew --prefix yajl`<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install luafilesystem<br />
luarocks --lua-version=5.1 --lua-dir=`brew --prefix lua@5.1` install lua-zip ZIP_DIR=`brew --prefix libzip`<br />
<br />
brew install p7zip<br />
export BOOST_ROOT="$(pwd)/../Mudlet/3rdparty/boost"<br />
export BOOST_URL="https://sourceforge.net/projects/boost/files/boost/1.72.0/boost_1_72_0.tar.bz2/download"<br />
mkdir -p $BOOST_ROOT<br />
curl --progress-bar --location --output $BOOST_ROOT/download.tar.bz2 $BOOST_URL<br />
7z -o$BOOST_ROOT x $BOOST_ROOT/download.tar.bz2 -y -bd<br />
7z -o$BOOST_ROOT x $BOOST_ROOT/download.tar -y -bd<br />
cd $BOOST_ROOT && cp -r boost_*/* .<br />
rm -rf boost_*/* download.tar.bz2 download.tar<br />
OK to answer yes to delete files if prompted for the <code>rm</code> command above.<br />
<br />
'''4. Run the following commands'''<br />
<br />
cd ../../build<br />
cmake ../../Mudlet -DCMAKE_PREFIX_PATH=`brew --prefix qt5`<br />
make -j `sysctl -n hw.ncpu`<br />
<br />
<br />
'''5. Enjoy'''<br />
<br />
The mudlet.app is now available in <code>src/</code> for launching:<br />
<br />
open src/Mudlet.app<br />
<br />
'''6. Qt Creator setup'''<br />
<br />
No Lua installation is found, despite it existing on your system? Launch Qt Creator by doing <code>open /Applications/Qt Creator.app</code> (location depends on how you installed it).<br />
<br />
Receiving a <code>No rule to make target ... libQt5UiTools_debug.a</code> error? A workaround is to [https://bugreports.qt.io/browse/QTBUG-81251?focusedCommentId=538705&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-538705 symlink a file].<br />
<br />
Mudlet in Qt Creator is not launching due to <code>dyld: Symbol not found: __cg_jpeg_resync_to_restart</code>? See [https://stackoverflow.com/a/44851430/72944 here] for a workaround.<br />
<br />
====== 7. Troubleshooting ======<br />
If you exhaust all efforts to get YAJL to compile on your local system with homebrew, [https://github.com/lloyd/yajl/ clone from the YAJL repository] then <code>./configure && sudo make install</code>.<br />
<br />
== Compiling on Debian 'Sid' ==<br />
<br />
'''1. Install required packages from main repo.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev<br />
<br />
sudo luarocks install luautf8<br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Grab latest Mudlet source.'''<br />
<br />
mkdir ~/projects && cd ~/projects && git clone --recursive https://github.com/Mudlet/Mudlet.git mudlet<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
cd ~/projects/mudlet/src<br />
<br />
qmake<br />
<br />
make<br />
<br />
sudo make install<br />
<br />
== Compiling on Debian 11 'Bullseye' ==<br />
<br />
'''1. Install required packages.'''<br />
<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qtbase5-dev qtchooser qt5-qmake qtbase5-dev-tools qtmultimedia5-dev \<br />
qttools5-dev luarocks ccache libpugixml-dev libqt5texttospeech5-dev qtspeech5-flite-plugin \<br />
qtspeech5-speechd-plugin libqt5opengl5-dev ninja-build cmake libsecret-1-dev<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl<br />
<br />
'''2. Get Mudlet source.'''<br />
<br />
mkdir ~/source && cd ~/source<br />
<br />
git clone --recursive https://github.com/Mudlet/Mudlet.git<br />
<br />
Note: the line above will check out `development` branch source code, and this might not always be stable. You can check out the latest release source code using this command:<br />
<br />
git clone --recursive --branch main https://github.com/Mudlet/Mudlet.git<br />
<br />
'''3. Build Mudlet.'''<br />
<br />
mkdir ~/source/Mudlet/build && cd ~/source/Mudlet/build<br />
<br />
qmake ../src/mudlet.pro<br />
<br />
make -j `nproc`<br />
<br />
sudo make install<br />
<br />
After these steps you can run Mudlet by typing:<br />
<br />
mudlet<br />
<br />
== Compiling on Raspberry Pi OS ==<br />
<br />
These instructions will get you compiling and running Mudlet on Raspberry Pi OS (Buster). Need a hand? Join us on Mudlet's [https://discord.gg/BwgJpMj Discord] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
''' 1.a Install apt dependencies '''<br />
<br />
sudo apt-get update<br />
sudo apt-get install build-essential git liblua5.1-dev zlib1g-dev libhunspell-dev libpcre3-dev \<br />
libzip-dev libboost-graph-dev libyajl-dev libpulse-dev lua-rex-pcre lua-filesystem lua-zip \<br />
lua-sql-sqlite3 qt5-default qtmultimedia5-dev qttools5-dev luarocks ccache libpugixml-dev cmake<br />
<br />
<br />
[[File:Apt-get-install-y-n.png|center|thumb|installing apt dependencies]]<br />
<br />
''' 1.b Install luarocks dependencies '''<br />
<br />
sudo luarocks install luautf8 <br />
sudo luarocks install lua-yajl YAJL_LIBDIR=`find /usr -name "libyajl.so" -printf '%h\n'` YAJL_INCDIR=/usr/include<br />
<br />
<br />
[[File:After-luarocks-dependencies.png|center|thumb|after luarocks dependencies]]<br />
<br />
''' 2. Get Mudlet source '''<br />
<br />
mkdir ~/source && cd ~/source <br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
<br />
[[File:After-get-mudlet-source.png|center|thumb|After cloning]]<br />
<br />
''' 3. Create a build directory '''<br />
<br />
cd Mudlet && mkdir build && cd build<br />
<br />
''' 4. Run the following commands to build '''<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake ../src/mudlet.pro<br />
<br />
:If you get a response along the lines of:<br />
<br />
qmake: could not find a Qt installation of ''<br />
<br />
:then you likely have ''qtchooser'' present in your system that allows for both Qt4 and Qt5 (or more than one Qt5 version) and it modifiers qmake and some other Qt development programs to take an additional argument to specify which version to use. In that case you should use:<br />
<br />
WITH_UPDATER=NO WITH_3DMAPPER=NO qmake -qt=qt5 ../src/mudlet.pro<br />
<br />
[[File:After-qmake.png|center|thumb|After qmake]]<br />
<br />
''' THEN: '''<br />
:For the fastest compile time while still being able to use the system at all (~35min on a RPi4 with 4GB of ram)<br />
make -j $(expr `nproc` - 1)<br />
<br />
''' OR: '''<br />
<br />
:Use this if you have an older Raspberry Pi. Be prepared for it to take a while (over an hour) - ''it is not recommended to try to more than one compilation task at a time on the older systems with the '''-j''' option as they will only have a system memory with enough space for one of some of those tasks'':<br />
make<br />
<br />
[[File:Success.png|center|thumb|Success!]]<br />
<br />
''' 4. Install the application you have just compiled '''<br />
<br />
sudo make install<br />
<br />
[[File:Installed.png|center|thumb|Installed now]]<br />
<br />
''' 5. Enjoy! '''<br />
<br />
# mudlet is in the path, can just run it<br />
mudlet<br />
<br />
== Compiling on ArchLinux ==<br />
<br />
Mudlet is available in the [https://aur.archlinux.org Arch User Repository]. <br />
<br />
To install it use your favourite AUR helper (helper tool will automatically resove dependancies); example using ''yay'' :<br />
yay -S mudlet<br />
<br />
For more info on this process, visit [https://wiki.archlinux.org/index.php/Arch_User_Repository Arch User Repository - ArchWiki].<br />
<br />
''Note: For the most recent development version of Mudlet, replace 'mudlet' with 'mudlet-git' in the above commands and proceed as described.''<br />
<br />
''Built in fonts have been disabled, but are available in packages listed as optional dependancies.''<br />
<br />
''Discord support in Mudlet depends on an extrenal library provided by discord-rpc-api, which is also available in AUR, choose whichever variant suits you best.''<br />
<br />
== Compiling on Fedora (aarch64) ==<br />
<br />
==== 1. Install Dependencies ====<br />
sudo dnf groupinstall "Development Tools" "Development Libraries"<br />
<br />
sudo dnf install compat-lua compat-lua-devel compat-lua-libs hunspell-devel lua5.1-filesystem luarocks pugixml-devel qtkeychain-qt5-devel bitstream-vera-fonts-all ccache qt-creator qt5-qtmultimedia-devel qt5-qtgamepad-devel yajl-devel qtchooser qt5-qttools-devel qt5-qttools-static zziplib-devel pcre-devel libzip-devel sqlite-devel<br />
<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luazip<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luasql-sqlite3<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lcf<br />
sudo luarocks --lua-version 5.1 --tree=/usr install luautf8<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lua-yajl<br />
sudo luarocks --lua-version 5.1 --tree=/usr install lrexlib-pcre<br />
In your user's home directory:<br />
<br />
If you use a bash shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .bashenv<br />
source .bashenv<br />
If you use a zsh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .zshenv<br />
source .zshenv<br />
If you use a csh shell:<br />
luarocks --lua-version 5.1 path --no-bin >> .cshenv<br />
source .cshenv<br />
This should cover paths, but you may want to reboot to be sure.<br />
<br />
==== 2. Obtain the source code ====<br />
git clone --recursive --branch=development <nowiki>https://github.com/Mudlet/Mudlet.git</nowiki><br />
mkdir Mudlet/build<br />
cd Mudlet/src<br />
<br />
==== 3. Make necessary compiling instruction adjustments ====<br />
<br />
====== Edit mudlet.pro ======<br />
Find these lines in mudlet.pro and make the following changes:<br />
linux {<br />
LIBS += \<br />
-llua5.1 \<br />
-lhunspell<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
We're adding a - between lua and 5.1 and adding -1.7 to hunspell under LIBS so that it becomes this:<br />
linux {<br />
LIBS += \<br />
-llua-5.1 \<br />
-lhunspell-1.7<br />
INCLUDEPATH += /usr/include/lua5.1<br />
}<br />
Save and exit.<br />
<br />
==== 4. Compile ====<br />
cd ../build<br />
Run this in the build directory:<br />
WITH_FONTS=NO WITH_OWN_QTKEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share qmake-qt5 PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1 LUA_SEARCH_OUT=lua-5.1 ../src/mudlet.pro<br />
An explanation of the qmake arguments -- we're passing these environment variables to mudlet.pro:<br />
WITH_FONTS=NO WITH_OWN_KEYCHAIN=NO WITH_UPDATER=NO WITH_VARIABLE_SPLASH_SCREEN=NO XDG_DATA_DIRS=/usr/share<br />
Adding build variables to mudlet.pro so that it finds the correct libraries:<br />
PREFIX=/usr INCLUDEPATH+=/usr/include/lua-5.1<br />
And finally adding a build variable to translations/translated/updateqm.pri so that it uses the correct version of the Lua compiler (Fedora also comes with 5.4) to generate translation statistics.<br />
LUA_SEARCH_OUT=lua-5.1<br />
Once complete, run the following:<br />
<br />
If you have time to kill (About 10 minutes on an Apple M1 Max in Fedora):<br />
make<br />
If you want it done as fast as possible(Less than a minute on an Apple M1 Max in Fedora):<br />
make -j `nproc`<br />
Or if you want something in between, make -j `nproc` tells it to use all available processor cores. If you want to use a specific number instead (ie 2), you can use:<br />
make -j 2<br />
<br />
==== 5. Install ====<br />
sudo make install<br />
sudo cp ../mudlet.png /usr/share/pixmaps<br />
sudo cp ../mudlet.desktop /usr/share/applications<br />
<br />
==== 6. Hang onto the cloned git repo. ====<br />
If you need to uninstall, you can go back into the /build directory and 'sudo make uninstall'.<br />
<br />
<br />
<br />
== Compiling on Gentoo ==<br />
An [https://github.com/toaster/gentoo-overlay overlay containing Mudlet is available] for compiling Mudlet on Gentoo.<br />
<br />
== Compiling on Windows ==<br />
<br />
These instructions will get you setup compiling on Windows. <br />
<br />
Need a hand? Join us on the Mudlet [https://discord.gg/BwgJpMj Discord server] or [http://forums.mudlet.org/viewforum.php?f=7 forums].<br />
<br />
'''1. Download Mudlet source code'''<br />
<br />
# Install [https://desktop.github.com/ Github Desktop].<br />
# Clone ([https://help.github.com/desktop/guides/contributing-to-projects/cloning-a-repository-from-github-to-github-desktop/#platform-windows instructions]) Mudlet's [https://github.com/mudlet/mudlet repository] to your local drive.<br />
{{note}} You must use a location on <code>C:\</code> without any spaces in folder names! <br />
<br />
'''2. Perform a one-time setup'''<br />
<br />
Right-click on <code>setup-windows-sdk.ps1</code> and select <code>Run with PowerShell</code>. This will automatically download all of the requires tools (including Python 2) and libraries, set them up for you, build Mudlet, and launch it! If this script exits immediately, please [https://docs.microsoft.com/en-us/powershell/scripting/windows-powershell/install/installing-windows-powershell?view=powershell-7.1#upgrading-existing-windows-powershell upgrade your PowerShell version] first.<br />
<br />
{{note}} Depending on your Internet connection and computer speed, this one-time setup will take 30 minutes or more - so grab a cup of tea or coffee.<br />
<br />
[[File:Start-of-installation.gif|frame|none|Sometimes the output will get stuck and not progress - just press Enter to make it continue. This is a well-known [https://serverfault.com/questions/204150/sometimes-powershell-stops-sending-output-until-i-press-enter-why Powershell bug.]]]<br />
<br />
During the installation, you'll see the Qt installer window pop-up - this is normal:<br />
<br />
[[File:Qt-installer.gif|thumb|none]]<br />
<br />
The Qt installer might ask you about your data collection preferences - answer as you wish and the automated install will continue:<br />
<br />
[[File:Qt-installer-data-collection.png|thumb|none]]<br />
<br />
The installer's final step will be compiling all of the source code, which looks like this:<br />
<br />
[[File:Compiling-step.gif|thumb|none]]<br />
<br />
After it's all done, a Mudlet version ending in "-dev" will launch automatically:<br />
<br />
[[File:Mudlet-launching.gif|frame|none]]<br />
<br />
If something didn't work right, you can check out the verbose log that is available at <code>C:\src\verbose_output.log</code>.<br />
<br />
=== Coding on Mudlet ===<br />
<br />
Open <code>C:\<path to repository>\src\mudlet.pro</code> in Qt Creator, which resides here: <code>C:\Qt\Tools\QtCreator\bin\qtcreator.exe</code>. Then enable Debug and Release builds and hit ''Configure Project'':<br />
<br />
[[File:Selection_173.png|frame|none]]<br />
<br />
Press <code>Ctrl+5</code> and update project settings. Check how many logical processors are available in your system with the Task Manager:<br />
<br />
[[File:Task-manager.png|thumb|none|2 processors are available in this example]]<br />
<br />
And set this amount in Qt Creator:<br />
<br />
[[File:Change Qt Creator to use many cores.gif|frame|none]]<br />
<br />
Hit run:<br />
<br />
[[File:Selection 176.png|frame|none]]<br />
<br />
Click on '''Compile Output''' to see progress on compiling:<br />
<br />
[[File:Selection 177.png|frame|none]]<br />
<br />
When it's all ready, the new Mudlet with your changes will launch. '''You're all done'''!<br />
<br />
=== Contributing changes ===<br />
<br />
Once you're all done with your changes, contribute them to Mudlet using a [https://help.github.com/desktop/guides/contributing-to-projects/creating-a-pull-request/#platform-windows pull request]. Thanks for improving open-source!<br />
<br />
=== Uninstalling ===<br />
To get rid of everything, remove the following folders:<br />
<br />
C:\Libraries<br />
C:\LuaRocks<br />
C:\MinGW<br />
C:\Python27<br />
C:\Qt<br />
C:\src<br />
<br />
== Compiling on Github Codespaces ==<br />
<br />
[https://github.com/features/codespaces/ Github Codespaces] allow you to code and run Mudlet all from the browser - makes it a lot easier to get started. It also allows you to code Mudlet itself from any computer in the world! <br />
<br />
'''1. Create a new codespace'''<br />
<br />
Create a new Codespace by going to https://github.com/Mudlet/Mudlet using Google Chrome or Microsoft Edge (Firefox at the time of the writing doesn't have working copy/paste). There, click the green "Code" button, select the "Codespaces" tab and click "New codespace".<br />
<br />
[[File:New codespace.png|alt=New codespace screenshot|frameless]]<br />
<br />
'''2. Wait for it to load'''<br />
<br />
This will take a while (~5min) so grab a tea:<br />
<br />
[[File:Building Visual Studio Codespace.png|frameless]]<br />
<br />
'''3. Connect to the environment'''<br />
<br />
Go to the <code>Ports</code> section at the bottom and change the Port Privacy of the Open Mudlet port to Public:<br />
<br />
[[File:Port privacy in Github Codespaces.png|900x900px]]<br />
<br />
<br />
Then connect to your online Linux desktop with <code>mudlet</code> as the password by clicking on the web icon. <br />
<br />
[[File:Connect to remote machine.png|frameless]]<br />
<br />
<br />
In case it can't connect, make sure the port privacy is set to <code>Public</code>. If it still can't connect, try 4-5 more times - eventually it'll work.<br />
<br />
<br />
<br />
We chose a retro 90's look here to fit with the whole hacking theme, so if you see this you're good 😉<br />
<br />
[[File:Github_codespaces_desktop.png|alt=|frameless|400x400px]]<br />
<br />
'''4. Build Mudlet'''<br />
<br />
In Codespaces, hit <code>F7</code> and select <code>Let CMake guess...</code><br />
<br />
[[File:CMake configuration.png|none]]<br />
<br />
It will then start building Mudlet automatically. Using the [https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/about-billing-for-codespaces Basic instance] (only kind available in beta) the first-time build will take ~25min, so take a break here - you've made excellent progress. All follow-up compiles after this will be quicker, by the way.<br />
<br />
[[File:Building Mudlet in codespaces.png|none]]<br />
<br />
'''5. Run Mudlet'''<br />
<br />
[[File:Launch Mudlet.png|none]]<br />
<br />
Hit the little play button at the bottom of the screen, and Mudlet will now launch in the remote connection tab. Not working? [https://discord.gg/kuYvMQ9 We can help]. Otherwise, enjoy!<br />
<br />
[[File:Mudlet running remotely.png |500px]]<br />
<br />
Note: When the codespace is unused for a while, it will disconnect. It'll never disconnect while you're actively using it. See [https://github.com/microsoft/vscode-dev-containers/issues/588 Github issue] for details.<br />
<br />
== Developing with Docker ==<br />
<br />
Docker is a system designed for more reproducible and isolated builds. A docker setup exists and has been tested using Pop OS! 20.04 (which is derived from Ubuntu 20.04). First, follow the instructions to install both [https://docs.docker.com/get-docker/ docker] and [https://docs.docker.com/compose/install/ docker-compose].<br />
<br />
Clone the development branch<br />
<br />
git clone --recursive -b development https://github.com/Mudlet/Mudlet.git<br />
cd Mudlet/docker<br />
<br />
Make a local copy of the .env.template file:<br />
<br />
cp .env.template .env<br />
<br />
If you wish to customize things like the number of cores to use for building mudlet, feel free to change the corresponding values in the .env file.<br />
<br />
To run Qt-Creator and develop Mudlet, run <code>docker-compose up dev</code>.<br />
<br />
To run Mudlet, run <code>docker-compose up mudlet</code>. Note: At the moment, the mudlet build will not persist settings past container rebuilds.<br />
<br />
== Compiling on Windows 7+ (MSYS2 Alternative)==<br />
<br />
''INCOMPLETE, IN PROGRESS''<br />
<br />
Go to http://www.msys2.org/ to download the 64 bit MSYS2 installer (as of 2020/05/24 32 bit hosts - for '''compiling''' software, but ''not'' for using code built with it have been deprecated, the last installer for that 32-bit systems is held at: http://repo.msys2.org/distrib/i686/msys2-i686-20200517.exe) and follow the installation instructions (Steps 1 to 8 on that page), these instructions assume that "C:\msys64" or "C:\msys32" is used depending on the bitness of the system it is being installed on.<br />
<br />
Install the following packages (using "pacman -S ''packageName''"), the ones with a '''-i686-''' in the middle are the ones for 32-bit (i686) targets and '''-x86_64-''' are the ones for 64-bit targets - it is possible to install both for building Mudlet for target PCs of both bitnesses on a 64-bit host, it is not clear whether the reverse is true with a 32-bit host. These will pull in a number of other required packages as well (the ''--needed'' option prevents the re-installation of packages that have already been installed by MSYS2/Mingw-w64's own setup/installation process) - as some of the packages, e.g. ''base-devel'' are actually ''groups'' you will be requested to select which members of that group are actually required, it is easiest to just go with the default which is to install ALL of the packages in that group!<br />
<br />
: For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-i686-toolchain mingw-w64-i686-qt-creator mingw-w64-i686-qt5-multimedia mingw-w64-i686-libzip mingw-w64-i686-pugixml mingw-w64-i686-lua51 mingw-w64-i686-lua51-lpeg mingw-w64-i686-lua51-lsqlite3 mingw-w64-i686-hunspell mingw-w64-i686-boost mingw-w64-i686-yajl mingw-w64-i686-clang mingw-w64-i686-cmake mingw-w64-i686-SDL unzip<br />
</syntaxhighlight><br />
<br />
: For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ pacman -S --needed base-devel git mercurial cvs wget ruby zip p7zip python mingw-w64-x86_64-toolchain mingw-w64-x86_64-qt-creator mingw-w64-x86_64-qt5-multimedia mingw-w64-x86_64-libzip mingw-w64-x86_64-pugixml mingw-w64-x86_64-lua51 mingw-w64-x86_64-lua51-lpeg mingw-w64-x86_64-lua51-lsqlite3 mingw-w64-x86_64-hunspell mingw-w64-x86_64-boost mingw-w64-x86_64-yajl mingw-w64-x86_64-clang mingw-w64-x86_64-cmake mingw-w64-x86_64-SDL unzip<br />
</syntaxhighlight><br />
<br />
::The ''*-zziplib'' libraries are used by the ''luazip'' luarock {from the Kepler project} but Mudlet will work perfectly well with the alternative ''lua-zip'' {from the brimworks GitHub repository - which also provides the ''lua-yajl'' rock} which does not require this library - although it is possible that it might still be pulled into the system as a dependency of another MSYS2 package.<br />
<br />
:Note that this will install the MSYS2 builds of the Qt Libraries and Creator IDE - ''THE ON/OFF-LINE INSTALLER OF THE QT LIBRARIES AND CREATOR VIA DOWNLOADS FROM QT ARE NOT USEFUL IN THIS SETUP!''<br />
<br />
:{| class="wikitable"<br />
|-<br />
|'''Attention - Luarocks packages problem'''<br />
|-<br />
| Recently the Luarocks project attempted to adopt the MSYS2/Mingw-w64 platform as one it would supported natively and the MSYS2/Mingw-w64 project went and upgraded its luarocks packages to make use of the changes and also on-board other improvements (and the version number increased from ''2.4.4-2'' to ''3.5.0-1'') unfortunately this completely broke them and although the issue has been reported ([https://github.com/msys2/MINGW-packages/issues/9037 MSYS2 Issue 9037]) a fix has not yet materialised. The only way to work around this in the meantime is to download the older package (with '''wget''') and install it manually (with '''pacman -U):<br />
|-<br />
|For 32-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:19:09-- https://repo.msys2.org/mingw/mingw32/mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97905 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-i686-lua51-luarocks-2.4.4-2- 100%[===========================================================================>] 95.61K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:19:10 (1.43 MB/s) - ‘mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97905/97905]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-i686-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-i686-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-i686-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|-<br />
|For 64-Bit Mudlet builds:<br />
:<syntaxhighlight lang="shell"><br />
MSYS user@computer ~<br />
$ wget https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
--2021-07-07 22:17:32-- https://repo.msys2.org/mingw/mingw64/mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
Resolving repo.msys2.org (repo.msys2.org)... 178.63.98.68<br />
Connecting to repo.msys2.org (repo.msys2.org)|178.63.98.68|:443... connected.<br />
HTTP request sent, awaiting response... 200 OK<br />
Length: 97935 (96K) [application/octet-stream]<br />
Saving to: ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’<br />
<br />
mingw-w64-x86_64-lua51-luarocks-2.4.4- 100%[===========================================================================>] 95.64K --.-KB/s in 0.07s<br />
<br />
2021-07-07 22:17:32 (1.28 MB/s) - ‘mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst’ saved [97935/97935]<br />
<br />
<br />
MSYS user@computer ~<br />
$ pacman -U mingw-w64-x86_64-lua51-luarocks-2.4.4-2-any.pkg.tar.zst<br />
loading packages...<br />
resolving dependencies...<br />
looking for conflicting packages...<br />
<br />
Packages (1) mingw-w64-x86_64-lua51-luarocks-2.4.4-2<br />
<br />
Total Installed Size: 0.46 MiB<br />
<br />
:: Proceed with installation? [Y/n] y<br />
(1/1) checking keys in keyring [#####################################################] 100%<br />
(1/1) checking package integrity [#####################################################] 100%<br />
(1/1) loading package files [#####################################################] 100%<br />
(1/1) checking for file conflicts [#####################################################] 100%<br />
(1/1) checking available disk space [#####################################################] 100%<br />
:: Processing package changes...<br />
(1/1) installing mingw-w64-x86_64-lua51-luarocks [#####################################################] 100%<br />
<br />
MSYS user@computer ~<br />
</syntaxhighlight><br />
|}<br />
<br />
::{| class="wikitable"<br />
|-<br />
|'''Warning for those planning to build ''both'' 32 and 64 bit versions'''<br />
|-<br />
|If one is planning to build ''both'' bitness binaries an additional step is necessary as, by default, the MSYS2/Mingw-w64 ''luarocks'' setup seems to place any ''.lua'' or ''.dll'' modules it builds/installs on a per user (the so-called ''local'' basis) into the same directories with the same names. This is no good for two reasons:<br />
* It is difficult to work out which bitness a particular module is for and whilst 32-bit modules ''might'' work in a 64-bit environment the reverse is definitely not the case<br />
* It confuses the Luarocks package management systems (as effectively there will be two different luarocks systems operated side-by-side)<br />
<br />
This can be worked around by:<br />
* Editing the '''.\etc\luarocks\config-5.1.lua''' for each bitness so that the ''rocks_trees'' table entry for the ''user'' key is changed from this in '''both''' files:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks]] },</syntaxhighlight><br />
to something different for each of them, say, for example, for the the 64-bit one:<br />
:<syntaxhighlight lang="lua"> { name = [[user]], root = home..[[/.luarocks-x64]] },</syntaxhighlight><br />
* Then by specifying the ''rocktree'' name ('''user''') on the command line when '''installing''' or '''building''' a luarock with the ''--tree user'' argument - note that for some inexplicable reason the ''--local'' argument that '''''should''''' do the same thing does not seem to work for these two actions, it is not clear whether this is a MSYS2/Mingw-w64 specific issue or it goes further upstream to Luarocks in general. Thus, in the next step it will be necessary to change from using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --local rockname<br />
</syntaxhighlight><br />
to, for the example given:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install --tree user rockname<br />
</syntaxhighlight><br />
where ''user'' is the literal string "user" to match the Lua table key in the rock_trees and not, in this case, a representation of the user-name/account of the person performing the action.<br />
|}<br />
<br />
From the Windows ''Start menu'' start a shell appropriate for the target with the bitness to be built for i.e. '''"MSYS2 Mingw 32-Bit"''' or '''"MSYS2 Mingw 64-Bit"'''. This will likely position the current directory to the root directory of the MSYS2 environment, the text about the prompt line (the one with the "$") will contain three different bits of colored text '''username@computername'''; one of '''MSYS2'''/'''MINGW32'''/'''MINGW''' depending on the type of shell you currently in use and '''/''' representing the root directory (which will actually be the directory MSYS2 was installed to, for example on the author's system this is "C:/msys64"). Change to the home directory in MYSY by entering "cd" on its own with no argument (it will show up as '''~''' and it would work out to be, for '''user''' to be '''c:/msys64/home/user''' or '''c:/msys32/home/user''' (if both bitnessess are to be built it will be necessary to repeat the following step twice, one for each and also observe the steps in the above warning) install the following luarocks:<br />
<br />
:{| class="wikitable sortable"<br />
|-<br />
! rockname<br />
|-<br />
| lrexlib-pcre<br />
|-<br />
| lua-yajl<br />
|-<br />
| luafilesystem<br />
|-<br />
| luasql-sqlite3<br />
|-<br />
| luautf8<br />
|-<br />
| luazip or lua-zip<br />
|}<br />
by using:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ luarocks install [--local] rockname<br />
</syntaxhighlight><br />
The ''--local'' argument is an optional one that causes the luarock and the lua module to be installed on a per-user basis rather than on a system wide one, this may be important if the PC is used by multiple users and more than one of them uses Lua in any form.<br />
<br />
Now create somewhere to work on the Mudlet source, assuming that other software coding with other pieces of software will be done, create a sub-directory in the home directory, and then make one just for Mudlet under that:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ mkdir ./src<br />
<br />
MINGW64 user@computer ~<br />
$ mkdir ./src/mudlet<br />
</syntaxhighlight><br />
<br />
Change to that directory and get the source code:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~<br />
$ cd ./src/mudlet<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git clone git://github.com/Mudlet/Mudlet.git .<br />
</syntaxhighlight><br />
<br />
If you are planning to contribute to the Mudlet code you will want to visit Github and create your own GitHub repository, you can then push commits (changes to the code) to there and raise a Pull Request for a Mudlet Maker to drag the changes over to the above repository. You will want to add your repository and perhaps those of some other contributors so you can track what they are doing and see/try/experiment with their PRs before they get merged. Therefore you will want to add some other repositories into the mix. The names you use to identify those other repositories will show up in any utility that works with the repository you have just created in the above "clone" operation and can be anything you like but it makes sense to have clear names. So to add "myName", and those of the leading active contributors to the Mudlet codebase you will use:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Mine https://github.com/myName/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Vadim https://github.com/vadi2/Mudlet.git <br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add SlySven https://github.com/SlySven/Mudlet.git<br />
<br />
MINGW64 user@computer ~/src/mudlet<br />
$ git remote add Kebap https://github.com/Kebap/Mudlet.git<br />
</syntaxhighlight><br />
<br />
Now obtain ''all'' the versions of the code with:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ git fetch --all<br />
</syntaxhighlight><br />
<br />
This will produce a lot of lines of output the first time and it might take a little while on a slow connection...<br />
<br />
{Section missing - it turns out that the default GUI git tools that the author of this section would normally use: "gitk" and "git gui" have some problems in the versions currently supplied from the MSYS2 system - and it was necessary to import them from the set that the Git4Win have patched - see https://github.com/git-for-windows/git/wiki/Install-inside-MSYS2-proper }<br />
<br />
Some modifications to the qmake/cmake project files are needed and these are now supported in the main ''development'' branch in the upstream {the Mudlet organisation's own GitHub repository} which requires that there is an environmental variable '''WITH_MAIN_BUILD_SYSTEM''' and it is set to the (case-insensitive) value '''NO''':<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export WITH_MAIN_BUILD_SYSTEM=NO<br />
</syntaxhighlight><br />
<br />
Also the '''MINGW_BASE_DIR''' environmental variable will need to be set to the root directory for the MINGW-W64 installation for the appropriate bitness of the target to be made. For building on a 64-Bit Host {the PC that is ''compiling'' the code} to make a 64-Bit application this will likely be '''C:/msys64/mingw64''' and for a 32-Bit application it will probably be '''C:/msys64/ming32'''.<br />
: E.g. <syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw64 # To build a 64-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
: Or: <syntaxhighlight lang="shell"><br />
MINGW32 user@computer ~/src/mudlet<br />
$ export MINGW_BASE_DIR=C:/msys64/mingw32 # To build a 32-Bit Application with a 64-Bit system<br />
</syntaxhighlight><br />
<br />
Now checkout a branch {ideally, if working on solving a new issue, or adding a feature or resolving a bug, one should create a new branch that is a copy of the current, upstream ''development'' branch} and then work on it with Qt Creator:<br />
:<syntaxhighlight lang="shell"><br />
MINGW64 user@computer ~/src/mudlet<br />
$ qtcreator &<br />
</syntaxhighlight><br />
<br />
Load in the '''mudlet.pro''' ''qmake'' project file in the '''src''' subdirectory (e.g. for this example: '''c:/msys64/home/user/src/mudlet/src/mudlet.pro''') and get hacking...<br />
<br />
= Setting up IDEs =<br />
== CLion ==<br />
=== Qt not detected ===<br />
If you'd like to use CLion and it is giving the following error:<br />
<br />
<nowiki><br />
By not providing "FindQt5Core.cmake" in CMAKE_MODULE_PATH this project has<br />
asked CMake to find a package configuration file provided by "Qt5Core", but<br />
CMake did not find one.<br />
<br />
...<br />
</nowiki><br />
<br />
You can fix this by setting <code>-DCMAKE_PREFIX_PATH=<your Qt + version + compiler location></code>. For example: <code>-DCMAKE_PREFIX_PATH=/media/vadi/SSDer/Programs/Qt/5.15.2/gcc_64/</code> [[File:CLion CMake settings - finidng Qt.png|700px|none]]<br />
<br />
=== CLion setup on Windows ===<br />
After running <code>setup-windows-sdk.ps1</code> make sure to set Cmake options to:<br />
-DCMAKE_PREFIX_PATH=C:\Qt\Tools\mingw730_32;C:\Qt\5.14.2\mingw73_32 -DBoost_INCLUDE_DIR=C:\Libraries\boost_1_77_0<br />
''Directories might vary slightly, when different Qt, Boost or MinGW version will be used.''<br />
<br />
[[File:Clion Settings - Cmake.png|frameless|700x700px]]<br />
<br />
<br />
<br />
You will need 32 bit version of MinGW. Set it in the <code>Toolset</code> field to:<br />
C:\Qt\Tools\mingw730_32<br />
<br />
''Directory may be slightly different if MinGW version used will change.''<br />
<br />
[[File:Toolchain.png|frameless|700x700px]]<br />
<br />
=== Clang Tidy ===<br />
Ensure that CLion is set to run the project's [https://www.jetbrains.com/help/clion/clang-tidy-checks-support.html#paticularcheck .clang-tidy checks] with the <code>Prefer .clang-tidy files over IDE settings</code> option:<br />
<br />
[[File:Clang Tidy CLIon.png|700px|none]]<br />
<br />
This helps us catch any issues just a bit earlier.<br />
<br />
=== Clang Format ===<br />
Ensure that [https://www.jetbrains.com/help/clion/clangformat-as-alternative-formatter.html#clion-support CLion is set to use] the <code>.clang-format</code> formatting style:<br />
<br />
[[File:Clang-format CLion.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
== Visual Studio Code ==<br />
<br />
To set the path in Visual Studio Code, open settings, search for <code>cmake environment</code> and set the <code>CMAKE_PREFIX_PATH</code> to your path, such as <code>/media/vadi/SSDer/Programs/Qt/5.14.1/gcc_64/</code>:<br />
<br />
[[File:CMake path in Visual Studio Code.png|none]]<br />
<br />
===Clang Tidy===<br />
clang-tidy catches common programming issues, run it by selecting 'Analysis' from the command palette (Ctrl+Shift+P by default):<br />
<br />
[[File:Clang-tidy in vscode.png|none]]<br />
<br />
It is also possible [https://devblogs.microsoft.com/cppblog/visual-studio-code-c-december-2021-update-clang-tidy/ check status of analysis and cancel if needed].<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in VSCode, set the <code>cmake.configureSettings</code> variable:<br />
<br />
[[File:Cmake.configureSettings option in vscode.png|frameless|890x890px]]<br />
<br />
[[File:Choosing which sanitizers in vscode to use.png|frameless|891x891px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
== Qt Creator==<br />
===Clang Tidy and Clazy===<br />
<br />
Configure Mudlet-specific checks for [https://clang.llvm.org/extra/clang-tidy/ clang-tidy] and [https://github.com/KDE/clazy clazy] tools help catch any issues early on. See [https://doc.qt.io/qtcreator/creator-clang-tools.html Qt Creator's instructions] for setting this up - clang-tidy can use the <code>.clang-tidy</code> file that's available at the root of the repository, and for clazy enable <code>level0</code> and <code>level1</code> checks.<br />
<br />
[[File:Clang tidy configuration.png|frame|none]]<br />
[[File:Clazy configuration.png|frame|none]]<br />
<br />
===Checking memory leaks & other issues (sanitizers)===<br />
Besides clang-tidy, it's also possible to enable clang sanitizers to double-check for issues:<br />
<br />
* [https://clang.llvm.org/docs/LeakSanitizer.html LeakSanitizer] for detecting memory leaks<br />
* [https://clang.llvm.org/docs/AddressSanitizer.html AddressSanitizer] for detecting most issues dealing with memory, such as out of bounds accesses to heap, stack, global and more<br />
* [https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html UndefinedBehaviourSanitizer] for detecting the use of various features of C/C++ that are explicitly listed as resulting in undefined behaviour (such as using misaligned or null pointer, conversion to, from, or between floating-point types which would overflow the destination, division by zero, etc)<br />
* [https://clang.llvm.org/docs/MemorySanitizer.html MemorySanitizer] for detecting reading uninitialised memory<br />
* [https://clang.llvm.org/docs/ThreadSanitizer.html ThreadSanitizer] for detecting threading issues<br />
<br />
To use the sanitisers, set the <code>USE_SANITIZER</code> CMake variable to one or several variables (separate by comma): <code>Address</code>, <code>Memory</code>, <code>MemoryWithOrigins</code>, <code>Undefined</code>, <code>Thread</code>, or <code>Leak</code><br />
<br />
To use them in Qt creator, head to <code>Projects</code> - <code>Build</code>: <br />
<br />
[[File:Sanitisers in qt creator.png|frameless|890x890px]]<br />
<br />
Not all sanitisers can be used with each other - in that case the cmake configuration won't allow you to continue.<br />
<br />
==Clang Format==<br />
Ensure that Qt Creator is set to use the <code>.clang-format</code> formatting style in the C++ settings. Turn on <code>Format instead of indenting</code> for <code>Ctrl+I</code> to format code, and ensure <code>Override Clang Format configuration file</code> is disabled:<br />
<br />
[[File:Qt Creator clang format.png]]<br />
<br />
This helps keep the look'n'feel of the source code in a consistent manner, even with many people contributing to Mudlet.<br />
<br />
<br />
=Building with multiple versions of Lua=<br />
Mudlet uses Lua 5.1 only, so if you are compiling on a system that also has later versions installed, you might get the following error: <code>‘LUA_GLOBALSINDEX’ was not declared in this scope</code>.<br />
<br />
To fix this, pass the path to Lua headers explicitly. For CMake: <code>-DLUA_INCLUDE_DIR=/usr/include/lua5.1</code> (adjust as needed).</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Event_Engine&diff=20341Manual:Event Engine2023-03-08T00:18:47Z<p>Kebap: Use function object reference, not function name as string!</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Manual on events, which events exist, how to raise events, how to handle them.}}<br />
=Event System=<br />
<br />
Events in Mudlet allow a paradigm of system-building that is easy to maintain (because if you’d like to restructure something, you’d have to do less work), enables interoperability (making a collection of scripts that work with each other is easier) and enables an event-based way of programming.<br />
<br />
The essentials of it are as such: you use Scripts to define which events a function should listen to, and when the event is raised, the said function(s) will be called. Events can also have function parameters with them, which’ll be passed onto the receiving functions.<br />
<br />
== Registering an event handler via UI ==<br />
Registering an event handler means that you’ll be telling Mudlet what function it should call for you when an event is raised, so it’s a two step process - you need to tell it both what function you’d like to have called, and on what event it should be called.<br />
<br />
To tell it what function should be called, create a new script, and give the script the name of the function you’d like to be called. This is the only time where an items name matters in Mudlet. You can define the function right inside the script as well, if you’d like.<br />
<br />
Next, we tell it what event or events this function should be called on - you can add multiple entries. To do that, enter the events name in the Add User Defined Event Handler: field, press enter, and it’ll go into the list - and that is all.<br />
<br />
== Registering an event from a script ==<br />
You can also register your event with the ''[[Manual:Miscellaneous_Functions#registerAnonymousEventHandler|registerAnonymousEventHandler(event name, function reference, [one shot])]]'' function inside your scripts:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size<br />
function keepStaticSize()<br />
setMainWindowSize(1280,720)<br />
end -- keepStaticSize<br />
<br />
registerAnonymousEventHandler("sysWindowResizeEvent", keepStaticSize, false)<br />
</syntaxhighlight><br />
<br />
{{note}} Mudlet also uses the event system in-game protocols (like ATCP, GMCP and others).<br />
<br />
== Raising a custom event== <br />
To raise an event, you'd use the [[Manual:Lua_Functions#raiseEvent|raiseEvent()]] function:<br />
<br />
<syntaxhighlight lang="lua">raiseEvent(name, [arguments...])</syntaxhighlight><br />
<br />
It takes an event name as the first argument, and then any amount of arguments after it which will be passed onto the receiving functions.<br />
<br />
== Example of registering and raising an event == <br />
Add a script to each profile you need the event.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
-- This is the function that will be called when the event is raised.<br />
-- "event" is set to the event name.<br />
-- "arg" is the argument(s) provided with raiseEvent/rasieGlobalEvent.<br />
-- "profile" - Is the profile name from where the raiseGlobalEvent where triggered from<br />
-- It is 'nil' if raiseEvent() was used.<br />
function onMyEvent(event, arg, profile)<br />
echo("Event: " .. event .. "\n")<br />
echo("Arg : " .. arg .. "\n")<br />
-- If the event is not raised with raiseGlobalEvent() profile will be 'nil'<br />
echo("Profile: " .. (profile or "Local") .. "\n")<br />
end<br />
<br />
-- Register the event handler.<br />
registerAnonymousEventHandler("my_event", onMyEvent)<br />
</syntaxhighlight><br />
<br />
To raise the event you can call:<br />
<syntaxhighlight lang="lua"><br />
-- Trigger only in the current profile:<br />
raiseEvent("my_event", "Hello world!")<br />
<br />
-- Trigger the event in all OTHER profiles:<br />
raiseGlobalEvent("my_event", "Hello World!")<br />
</syntaxhighlight><br />
<br />
To review, count and extract from an unknown number of arguments received by an event:<br />
<br />
<syntaxhighlight lang="lua"><br />
function eventArgs(...)<br />
local args = {...}<br />
local amount = #args<br />
local first = args[1]<br />
echo("Number of arguments: " .. amount)<br />
echo("\nTable of all arguments: ")<br />
display(args)<br />
echo("First argument: " .. first)<br />
echo("\n\n")<br />
end<br />
</syntaxhighlight><br />
<br />
== Gamepad functionality ==<br />
Gamepad functions are not fully supported with all operating systems and hardware. Windows supports XInput devices like Xbox 360 and Xbox One controllers. DirectInput controllers like a PlayStation 4 controller can be translated to XInput with third party software. Mudlet on Linux can support gamepads but only if you compile it yourself. The automated builds are made using the oldest supported version of Ubuntu, and the [https://doc.qt.io/qt-5/qtgamepad-index.html Qt5 gamepad module] was [https://packages.ubuntu.com/search?keywords=libqt5gamepad5-dev not available on Ubuntu 18.04 LTS].<br />
<br />
==Mudlet-raised events==<br />
Mudlet itself also creates events for your scripts to hook on. The following events are generated currently:<br />
<br />
===AdjustableContainerReposition===<br />
Raised while a [[Manual:Geyser#Adjustable.Container|adjustable container]] is re-positioned. <br />
<br />
<syntaxhighlight lang="lua"><br />
function repositioningContainer(eventName, containerName, width, height, x, y, mouseAction)<br />
print(f"{containerName}: {x}x, {y}y, {width}x{height}, using mouse? {mouseAction}")<br />
end<br />
<br />
registerAnonymousEventHandler("AdjustableContainerReposition", repositioningContainer)<br />
</syntaxhighlight><br />
<br />
===AdjustableContainerRepositionFinish===<br />
Raised when an [[Manual:Geyser#Adjustable.Container|adjustable container]] done being re-positioned.<br />
<br />
<syntaxhighlight lang="lua"><br />
function finishedRepositioning(eventName, containerName, width, height, x, y)<br />
print(f"{containerName}: {x}x, {y}y, {width}x{height}")<br />
end<br />
<br />
registerAnonymousEventHandler("AdjustableContainerRepositionFinish", finishedRepositioning)<br />
</syntaxhighlight><br />
<br />
===channel102Message===<br />
<br />
Raised when a telnet sub-option 102 message is received (which comprises of two numbers passed in the event). This is of particular use with the [http://www.aardwolf.com Aardwolf MUD] who originated this protocol. See [http://forums.mudlet.org/viewtopic.php?f=6&t=1471 this] forum topic for more about the Mudlet Aardwolf GUI that makes use of this.<br />
<br />
===mapModeChangeEvent===<br />
<br />
Raised when the mapper is switchting between "view-only" and "editing" mode of the [[Manual:Mapper#Visual_Map_Editor|Visual Map Editor]]. A value of "editing" or "viewing" will be given as argument to indicate which mode was entered.<br />
<br />
===mapOpenEvent===<br />
<br />
Raised when the mapper is opened - either the floating dock or the in-Mudlet widget.<br />
<br />
===sysAppStyleSheetChange===<br />
<br />
Raised when [[Manual:UI_Functions#setAppStyleSheet|setAppStyleSheet]] is called and a new stylesheet applied to Mudlet.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- This will respond to a future (as yet unpublished) addition to the Mudlet code that will allow some<br />
-- of a default application style sheet to be supplied with Mudlet to compensate for some text colors<br />
-- that do not show up equally well in both light and dark desktop themes. That, perhaps, might finally<br />
-- allow different colored texts to be uses again for the trigger item types!<br />
function appStyleSheetChangeEvent( event, tag, source )<br />
if source == "system" then<br />
colorTable = colorTable or {}<br />
if tag == "mudlet-dark-theme" then<br />
colorTable.blue = {64, 64, 255}<br />
colorTable.green = {0, 255, 0}<br />
elseif tag == "mudlet-light-theme" then<br />
colorTable.blue = {0, 0, 255}<br />
colorTable.green = {64, 255, 64}<br />
end<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.19}}<br />
<br />
===sysBufferShrinkEvent===<br />
<br />
Raised when the oldest lines are removed from the back of any console or buffer belonging to a profile because it has reached the limit (either the default or that set by [[Manual:Mudlet_Object_Functions#setConsoleBufferSize|setConsoleBufferSize]]). The two additional arguments within the event are: the name of the console or buffer and the number of lines removed from the beginning of the buffer. This information will be useful for any situation where a line number is being stored as it will need to be decremented by that number of lines in order to continue to refer to the same line (assuming that it is still present - indicated by the number remaining positive) after the oldest ones have been removed.<br />
<br />
{{MudletVersion|4.17}}<br />
<br />
===sysConnectionEvent===<br />
<br />
Raised when the profile becomes connected to a MUD.<br />
<br />
===sysCustomHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#customHTTP|customHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters) and HTTP method.<br />
<br />
See also [[#sysCustomHttpError|sysCustomHttpError]].<br />
<br />
===sysCustomHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#customHTTP|customHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to and HTTP method.<br />
<br />
See also [[#sysCustomHttpDone|sysCustomHttpDone]].<br />
<br />
===sysDataSendRequest===<br />
<br />
Raised right before a command from the send(), sendAll() functions or the command line is sent to the game - useful for keeping track of what your last command was, manipulating input or even denying the command to be sent if necessary with [[Manual:Miscellaneous_Functions#denyCurrentSend|denyCurrentSend()]].<br />
<br />
sysDataSendRequest will send the event name and the command sent (in string form) to the functions registered to it. IE: commandSent in the example below will be "eat hambuger" if the user entered only that into command line and pressed enter, send("eat hamburger"), sendAll("eat humburger", "eat fish") or sendAll("eat fish", "eat humburger")<br />
<br />
Note: if you'll be making use of denyCurrentSend(), you ''really should'' notify the user that you denied their command - unexperienced ones might conclude that your script or Mudlet is buggy if they don't see visual feedback. Do not mis-use this and use it as [http://en.wikipedia.org/wiki/Keylogger keylogger] either.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- cancels all "eat hambuger" commands<br />
function cancelEatHamburger(eventName, commandSent)<br />
if commandSent == "eat hamburger" then<br />
denyCurrentSend() --cancels the command sent.<br />
cecho("<red>Denied! You can't do "..commandSent.." right now.\n")<br />
end --if commandSent == eat hamburger<br />
end<br />
<br />
registerAnonymousEventHandler("sysDataSendRequest", cancelEatHamburger)<br />
</syntaxhighlight><br />
<br />
If you wanted to control input you could set a bool after a trigger.<br />
This is useful if you want alias like control, do not know what text will be entered, but do know a trigger that WILL occur just before the user enters the command.<br />
<br />
<syntaxhighlight lang="lua"><br />
function controlInput(_, command) <br />
if changeCMDInput then<br />
changeCMDInput = false --set this if check to false to it doesn't occur every input<br />
--Also set the bool check BEFORE any send() functions within a sysDataSendRequest function<br />
sendAll(command .. "some target", command .. "some other target", true) --Duplicate and unknown command<br />
denyCurrentSend() --Deny the original command, not the commands sent with sendAll.<br />
end<br />
end<br />
registerAnonymousEventHandler("sysDataSendRequest", controlInput)<br />
</syntaxhighlight><br />
<br />
Take note that functions registered under sysDataSendRequest WILL trigger with ALL commands that are sent.<br />
<br />
===sysDeleteHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#deleteHTTP|deleteHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysDeleteHttpError|sysDeleteHttpError]].<br />
<br />
===sysDeleteHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#deleteHTTP|deleteHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysDeleteHttpDone|sysDeleteHttpDone]].<br />
<br />
===sysDisconnectionEvent===<br />
<br />
Raised when the profile becomes disconnected, either manually or by the game.<br />
<br />
If you'd like to automatically reconnect when you get disconnected, make a new <code>Script</code> and add this inside:<br />
<br />
<syntaxhighlight lang="lua"><br />
registerAnonymousEventHandler("sysDisconnectionEvent", reconnect)<br />
</syntaxhighlight><br />
<br />
===sysDownloadDone===<br />
<br />
Raised when Mudlet is finished downloading a file successfully - the location of the downloaded file is passed as a second argument.<br />
<br />
Example - put it into a new script and save it to run:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create a function to parse the downloaded webpage and display a result<br />
function downloaded_file(_, filename)<br />
-- is the file that downloaded ours?<br />
if not filename:find("achaea-who-count.html", 1, true) then return end<br />
<br />
-- read the contents of the webpage in<br />
local f, s, webpage = io.open(filename)<br />
if f then webpage = f:read("*a"); io.close(f) end<br />
-- delete the file on disk, don't clutter<br />
os.remove(filename)<br />
<br />
-- parse our downloaded file for the player count<br />
local pc = webpage:match([[Total: (%d+) players online]])<br />
display("Achaea has "..tostring(pc).." players on right now.")<br />
end<br />
<br />
-- register our function to run on the event that something was downloaded<br />
registerAnonymousEventHandler("sysDownloadDone", downloaded_file)<br />
<br />
-- download a list of fake users for a demo<br />
downloadFile(getMudletHomeDir().."/achaea-who-count.html", "https://www.achaea.com/game/who")<br />
</syntaxhighlight><br />
<br />
You should see a result like this:<br />
<br />
[[File:DownloadFile_demo.png|frameless|800px]]<br />
<br />
===sysDownloadError===<br />
<br />
Raised when downloading a file failed - the second argument contains the error message, the third the local filename that was to be used and the actual URL used (might not be the same as what was given if redirection took place).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--if a download fails notify the player.<br />
function downloadErrorEventHandler(event, errorFound, localFilename, usedUrl)<br />
cecho("fuction downloadErrorEventHandler, "..errorFound)<br />
debugc("fuction downloadErrorEventHandler, "..errorFound) --display to error screen in editor<br />
end --function downloadErrorEventHandler<br />
registerAnonymousEventHandler("sysDownloadError", downloadErrorEventHandler)<br />
</syntaxhighlight><br />
<br />
===sysDownloadFileProgress===<br />
<br />
Raised while file is being downloaded to indicate progess of download.<br />
<br />
The arguments passed areː: event name, url of download, bytes downloaded, total bytes (if available).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- will show progress bar while download file and hide it after file download is complete<br />
local progressBar = Geyser.Gauge:new({<br />
name="downloadProgressBar",<br />
x="25%", y="10%",<br />
width="50%", height="5%",<br />
})<br />
progressBar:setFontSize(13)<br />
progressBar:setAlignment("center")<br />
progressBar:hide()<br />
<br />
<br />
local fileUrl = "https://www.mudlet.org/download/Mudlet-4.10.1-linux-x64.AppImage.tar"<br />
local targetFile = getMudletHomeDir() .. "/Mudlet.tar"<br />
function handleProgress(_, url, bytesDownloaded, totalBytes)<br />
if url ~= fileUrl then<br />
return<br />
end<br />
<br />
progressBar:show()<br />
<br />
if not totalBytes then<br />
bytesDownloaded = 0<br />
totalBytes = 1<br />
end<br />
<br />
progressBar:setValue(bytesDownloaded, totalBytes, math.floor((bytesDownloaded / totalBytes) * 100) .. "%")<br />
end<br />
<br />
registerAnonymousEventHandler("sysDownloadFileProgress", handleProgress)<br />
<br />
function hideProgressBar()<br />
tempTimer(3, function() progressBar:hide() end)<br />
end <br />
<br />
registerAnonymousEventHandler("sysDownloadDone", hideProgressBar)<br />
registerAnonymousEventHandler("sysDownloadError", hideProgressBar)<br />
<br />
downloadFile(targetFile, fileUrl)<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.11}}<br />
<br />
===sysDropEvent===<br />
<br />
Raised when a file is dropped on the Mudlet main window or a userwindow.<br />
The arguments passed areː filepath, suffix, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function onDragAndDrop(_, filepath, suffix, xpos, ypos, consolename)<br />
print(string.format("Dropped new file into %s: %s (suffix: %s)", consolename, filepath, suffix))<br />
end<br />
registerAnonymousEventHandler("sysDropEvent", onDragAndDrop)<br />
</syntaxhighlight><br />
<br />
===sysDropUrlEvent===<br />
<br />
Raised when a url is dropped on the Mudlet main window or a userwindow.<br />
As an url at the moment Mudlet understands<br />
The arguments passed areː url, schema, xpos, ypos, and consolename - "main" for the main window and otherwise of the userwindow/miniconsole name.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function onDragAndDropUrl(_, url, schema, xpos, ypos, consolename)<br />
print(string.format("Dropped new url into %s: %s (suffix: %s)", consolename, filepath, suffix))<br />
if schema == "http" or schema == "https" then<br />
print("\nOh boy... this might be a link to some website")<br />
end<br />
end<br />
registerAnonymousEventHandler("sysDropUrlEvent", onDragAndDropUrl)<br />
</syntaxhighlight><br />
<br />
===sysExitEvent===<br />
<br />
Raised when Mudlet is shutting down the profile - a good event to hook onto for saving all of your data.<br />
<br />
===sysGamepadAxisMove===<br />
<br />
Raised when an axis on a gamepad is moved.<br />
<br />
Event handlers receive the device ID, axis number, and the new value as a number.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadButtonPress===<br />
<br />
Raised when a button on a gamepad is pressed down.<br />
<br />
Event handlers receive the device ID, button number, and the new value as a number.<br />
<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadButtonRelease===<br />
<br />
Raised when a button on a gamepad is released.<br />
<br />
Event handlers receive the device ID, button number, and the new value as a number.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGamepadConnected===<br />
<br />
Raised when a [https://en.wikipedia.org/wiki/Gamepad gamepad] is connected. On Windows, this uses the XInput backend.<br />
<br />
Event handlers receive device ID as an argument.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
function noticeConnection(deviceID)<br />
local output = string.format("New gamepad connected: %s\n", deviceID)<br />
echo(output)<br />
end<br />
<br />
function noticeDisconnection(deviceID)<br />
local output = string.format("Gamepad disconnected: %s\n", deviceID)<br />
echo(output)<br />
end<br />
<br />
function noticeButtonPress(deviceID, buttonNumber, valueNumber)<br />
local output = string.format("Button pressed: gamepad %s, button %s, value %s\n", deviceID, buttonNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
function noticeButtonRelease(deviceID, buttonNumber, valueNumber)<br />
local output = string.format("Button released: gamepad %s, button %s, value %s\n", deviceID, buttonNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
function noticeAxis(deviceID, axisNumber, valueNumber)<br />
local output = string.format("Axis moved: gamepad %s, axis %s, value %s\n", deviceID, axisNumber, valueNumber)<br />
echo(output)<br />
end<br />
<br />
registerAnonymousEventHandler("sysGamepadConnected", noticeConnection)<br />
registerAnonymousEventHandler("sysGamepadDisconnected", noticeDisconnection)<br />
registerAnonymousEventHandler("sysGamepadButtonPress", noticeButtonPress)<br />
registerAnonymousEventHandler("sysGamepadButtonRelease", noticeButtonRelease)<br />
registerAnonymousEventHandler("sysGamepadAxisMove", noticeAxis)<br />
</syntaxhighlight><br />
<br />
===sysGamepadDisconnected===<br />
<br />
Raised when a [https://en.wikipedia.org/wiki/Gamepad gamepad] is disconnected<br />
<br />
Event handlers receive device ID as an argument.<br />
<br />
{{MudletVersion|3.3}}<br />
{{note}} Gamepad functions [[#Gamepad_functionality|not fully]] supported.<br />
<br />
===sysGetHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking Functions#getHTTP|getHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
This event is also raised when a post/put/delete request redirects to a ''GET''.<br />
<br />
See also [[#sysGetHttpError|sysGetHttpError]].<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
===sysGetHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#getHTTP|getHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysGetHttpDone|sysGetHttpDone]].<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
===sysInstall===<br />
<br />
Raised right after a module or package is installed by any means. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed package or module as additional argument.<br />
<br />
{{note}}Installed modules will raise this event handler each time the synced profile is opened. [[sysInstallModule]] and [[sysInstallPackage]] are not raised by opening profiles.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
<syntaxhighlight lang="lua"><br />
function myScriptInstalled(_, name)<br />
-- stop if what got installed isn't my thing<br />
if name ~= "my script name here" then return end<br />
<br />
print("Hey, thanks for installing my thing!")<br />
end<br />
registerAnonymousEventHandler("sysInstallPackage", myScriptInstalled)<br />
</syntaxhighlight><br />
<br />
===sysInstallModule===<br />
<br />
Raised right after a module is installed through the module dialog. This can be used to display post-installation information or setup things.<br />
<br />
See also [[sysLuaInstallModule]] for when a module is installed via Lua.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysInstallPackage===<br />
<br />
Raised right after a package is installed by any means. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed package as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysIrcMessage===<br />
<br />
Raised when the IRC client receives an IRC message. The sender's name, channel name, and their message are passed as arguments to this event. <br />
<br />
Starting with Mudlet 3.3, this event changes slightly to provide more information from IRC network messages. Data such as status codes, command responses, or error messages sent by the IRC Server may be formatted as plain text by the client and posted to lua via this event. <br />
<br />
* sender: may be the nick name of an IRC user or the name of the IRC server host, as retrievable by [[Manual:Networking_Functions#getIrcConnectedHost|getIrcConnectedHost()]] <br />
* channel: may not always contain a channel name, but will be the name of the target/recipient of a message or action. In some networks the name may be that of a service (like ''"Auth"'' for example) <br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function onIrcMessage(_, sender, target, message)<br />
echo(string.format('(%s) %s says, "%s"\n', target, sender, message))<br />
end<br />
<br />
registerAnonymousEventHandler("sysIrcMessage", onIrcMessage)<br />
</syntaxhighlight><br />
<br />
To send a message, see [[Manual:Networking_Functions#sendIrc|sendIrc()]].<br />
<br />
===sysLabelDeleted===<br />
<br />
Raised after a label is deleted, with the former label's name as an argument.<br />
<br />
<br />
===sysLoadEvent===<br />
<br />
Raised after Mudlet is done loading the profile, after all of the scripts, packages, and modules are installed. Note that when it does so, it also compiles and runs all scripts - which could be a good idea to initialize everything at once, but beware - scripts are also run when saved. Hence, hooking only on the sysLoadEvent would prevent multiple re-loads as you’re editing the script.<br />
<br />
===sysLuaInstallModule===<br />
<br />
Raised right after a module is installed through the Lua installModule() command. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysLuaUninstallModule===<br />
<br />
Raised right before a module is removed through the lua uninstallModule command. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysManualLocationSetEvent===<br />
<br />
Raised whenever the "set location" command (on the 2D mapper context menu) is used to reposition the current "player room". It provides the room ID of the new room ID that the player has been moved to.<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
===sysMapDownloadEvent===<br />
<br />
Raised whenever an [[Standards:MMP|MMP map]] is downloaded and loaded in.<br />
<br />
===sysMediaFinished===<br />
<br />
Raised when media finishes playing. This can be used in a music player for example to start the next song.<br />
<br />
Event handlers receive the media file name and the file path as additional arguments.<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
===sysPathChanged===<br />
<br />
Raised whenever file or directory added through [[Manual:Lua_Functions#addFileWatch|addFileWatch()]] is modified.<br />
<br />
For directories this event is emitted when the directory at a specified path is modified (e.g., when a file is added or deleted) or removed from disk. Note that if there are several changes during a short period of time, some of the changes might not emit this signal. However, the last change in the sequence of changes will always generate this signal.<br />
<br />
For files this event is emitted when the file at the specified path is modified, renamed or removed from disk.<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", herbsChangedHandler)<br />
</syntaxhighlight><br />
<br />
===sysPostHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#postHTTP|postHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysPostHttpError|sysPostHttpError]].<br />
<br />
===sysPostHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#postHTTP|postHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysPostHttpDone|sysPostHttpDone]].<br />
<br />
===sysProfileFocusChangeEvent===<br />
<br />
:Raised whenever a profile becomes or stops being the foreground one when multi-playing, whether multi-view (show all profiles side-by-side) is active or not. The event comes with a second ''boolean'' argument which is ''true'' if the profile is now the one that has the focus, i.e. will receive keystrokes entered from the keyboard, or ''false'' if the focus has just switched from it to another profile.<br />
<br />
{{MudletVersion|4.17.0}}<br />
<br />
===sysProtocolDisabled===<br />
<br />
Raised whenever a communications protocol is disabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.<br />
<br />
===sysProtocolEnabled===<br />
<br />
Raised whenever a communications protocol is enabled, with the protocol name passed as an argument. Current values Mudlet will use for this are: GMCP, MDSP, ATCP, MXP, and channel102.<br />
<br />
<syntaxhighlight lang="lua"><br />
function onProtocolEnabled(_, protocol)<br />
if protocol == "GMCP" then<br />
print("GMCP enabled! Now we can use GMCP data.")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
===sysPutHttpDone===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#putHTTP|putHTTP()]] request completes successfully. Arguments with the event are the URL that the request was sent to and the response body (if it's less than 10k characters).<br />
<br />
See also [[#sysPutHttpError|sysPutHttpError]].<br />
<br />
===sysPutHttpError===<br />
<br />
Raised whenever a [[Manual:Networking_Functions#putHTTP|putHTTP()]] request fails. Arguments are the error message and the URL that the request was sent to.<br />
<br />
See also [[#sysPutHttpDone|sysPutHttpDone]].<br />
<br />
===sysSoundFinished===<br />
<br />
This event is obsolete in Mudlet 4.15. Please replace this with [[Manual:Event_Engine#sysMediaFinished|sysMediaFinished()]]<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysSpeedwalkFinished===<br />
<br />
Raised when a speedwalk finishes, either one started by speedwalk() or the generic mapping script<br />
<br />
===sysSpeedwalkPaused===<br />
<br />
Raised when a speedwalk is paused, either via pauseSpeedwalk() or the generic mapping script.<br />
<br />
===sysSpeedwalkResumed===<br />
<br />
Raised when a speedwalk is resumed after pausing, whether it's the generic mapping script or the resumeSpeedwalk() function<br />
<br />
===sysSpeedwalkStarted===<br />
<br />
Raised when a speedwalk is started, either by the speedwalk() function or the generic mapping script<br />
<br />
===sysSpeedwalkStopped===<br />
<br />
Raised when a speedwalk is stopped prematurely by stopSpeedwalk() or the generic mapping script<br />
<br />
===sysSyncInstallModule===<br />
<br />
Raised right after a module is installed through the "sync" mechanism. This can be used to display post-installation information or setup things.<br />
<br />
Event handlers receive the name of the installed module as well as the file name as additional arguments.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysSyncUninstallModule===<br />
<br />
Raised right before a module is removed through the "sync" mechanism. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysTelnetEvent===<br />
<br />
Raised whenever an unsupported telnet option is encountered, allowing you to handle it yourself. The arguments that get passed with the event are type, telnet option, and the message. <br />
<br />
===sysUninstall===<br />
<br />
Raised right before a module or package is uninstalled by any means. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed package or module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUninstallModule===<br />
<br />
Raised right before a module is removed through the module dialog. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed module as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUninstallPackage===<br />
<br />
Raised right before a package is removed by any means. This can be used to display post-removal information or for cleanup.<br />
<br />
Event handlers receive the name of the removed package as additional argument.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
===sysUnzipDone===<br />
<br />
Raised when a zip file is successfully unzipped using unzipAsync()<br />
<br />
Event handlers receive the zip file name and the unzip path as additional arguments.<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
===sysUnzipError===<br />
<br />
Raised when a zip file fails to unzip using unzipAsync()<br />
<br />
Event handlers receive the zip file name and the unzip path as additional arguments.<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
===sysUserWindowResizeEvent===<br />
<br />
Raised when a userwindow is resized, with the new height and width coordinates and the windowname passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.<br />
<br />
See alsoː [[#sysWindowResizeEvent|sysWindowResizeEvent]]<br />
<br />
Example<br />
<br />
This sample code will echo whenever a resize happened with the new dimensions:<br />
<br />
<syntaxhighlight lang="lua"><br />
function resizeEvent( event, x, y, windowname )<br />
echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.." windowname="..windowname.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
===sysWindowMousePressEvent===<br />
<br />
Raised when a mouse button is pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release). The button number, the x,y coordinates of the click and the windowname are reported.<br />
<br />
{{note}}Windowname reported in Mudlet 4.9+<br />
<br />
See alsoː [[#sysWindowMouseReleaseEvent|sysWindowMouseReleaseEvent]]<br />
<br />
Example<br />
<br />
<syntaxhighlight lang="lua"><br />
function onClickHandler( event, button, x, y, windowname )<br />
echo("CLICK event:"..event.." button="..button.." x="..x.." y="..y.." windowname="..windowname.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
===sysWindowMouseReleaseEvent===<br />
<br />
Raised when a mouse button is released after being pressed down anywhere on the main window (note that a click is composed of a mouse press and mouse release).<br />
<br />
See [[#sysWindowMousePressEvent|sysWindowMousePressEvent]] for example use.<br />
<br />
===sysWindowResizeEvent===<br />
<br />
Raised when the main window is resized, or when one of the borders is resized, with the new height and width coordinates passed to the event. A common usecase for this event is to move/resize your UI elements according to the new dimensions.<br />
<br />
See alsoː [[#sysUserWindowResizeEvent|sysUserWindowResizeEvent]]<br />
<br />
Example<br />
<br />
This sample code will echo whenever a resize happened with the new dimensions:<br />
<br />
<syntaxhighlight lang="lua"><br />
function resizeEvent( event, x, y )<br />
echo("RESIZE EVENT: event="..event.." x="..x.." y="..y.."\n")<br />
end<br />
</syntaxhighlight><br />
<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Geyser&diff=20332Manual:Geyser2023-03-02T07:37:50Z<p>Kebap: /* Image on a label */ Don't mention Windows version number</p>
<hr />
<div><br><br />
{{TOC right}}<br />
<br />
= Introduction =<br />
<br />
The Geyser Layout Manager is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
=== Motivation ===<br />
<br />
Mudlet makes the creation of label, miniconsoles and gauges a quick and easy thing. Mudlet provides a nice signal when window resize events happen. To help with complex window management, Geyser steps in.<br />
<br />
=== Main Geyser Features ===<br />
<br />
Geyser is based on traditional GUI concepts and should feel similar to using Java's Swing. The biggest difference is in how positions are specified.<br />
<br />
* All window positions are specified relative to their container - nothing new there. However, window positions can also take on percentages and negative pixel and character values. For instance, a window could be constrained to have a height of 50% of its container and a width such that the window's right edge is always 20 characters from its container's right edge. See examples below and the demos/tests that come with Geyser.<br />
* All windows under Geyser control are automatically resized as necessary when the main Mudlet window is resized. Once you create a window and assign it to a container, you never have to worry about positioning it again. Nonetheless, it's very easy to shift the container that a window is in, maintaining its constraints so that it resizes as needed according to the dimensions of the new container.<br />
* Due to the container hierarchy, hiding a container window automatically hides all its contained windows too. The same for show. With clever construction and labels with callbacks, this lets one make complex GUI elements that are minimizable or maximizable or ...<br />
* However, there is always some overhead for automation systems and Geyser is no exception. Fortunately, most of the overhead is during window creation and resize events - not things that happen frequently.<br />
<br />
=== Getting pictures for your stuff ===<br />
You can find good, freely-available assets for your UI here:<br />
* [https://kenney.nl/assets?q=2d kenney.nl]<br />
* [https://opengameart.org/ opengameart.org]<br />
* [https://game-icons.net/ game-icons.net]<br />
<br />
=== Constraints format ===<br />
<br />
Geyser position constraints are a string composed of a number and a format type. For example, "10px" means 10 pixels, either pixels from the origin (e.g. x or y) or a value for the width or height. A negative number indicates distance from a container's right or bottom border depending on whether is a constraint for x/width or y/height, respectively. Percentages for width and height are in terms of the container's dimensions and negative values are converted to the equivalent positive value. A 100% width subwindow with an x-coordinate of 10 will have part of itself displayed outside the confines of its container. There is no hard limit on maximum window size, just as with regular Mudlet windows. If a number, n, is passed as a constraint instead of a string, it is assumed to be equivalent to "npx". Any Lua table that contains entries for x, y, width and height in the proper format can be used for Geyser constructors and setting constraints. Just like in Mudlet, 0,0 coordinates mean the top-left corner.<br />
<br />
The following is a valid example for coordinates of a Geyser object:<br />
<br />
<syntaxhighlight lang="lua"><br />
{x = "20px", y = "-10c", width = "40%", height = 30}<br />
</syntaxhighlight><br />
<br />
=== Math in Geyser ===<br />
You can also use math in your Geyser constraints just to line things up just right! Want to have a label occupy full height but not the first 30 pixels? You can:<br />
<br />
<syntaxhighlight lang="lua"><br />
footer = Geyser.Label:new({<br />
name = "footer",<br />
x = 0, y = 30,<br />
height = "100%-30px",<br />
}, main_window)<br />
</syntaxhighlight><br />
<br />
= Geyser elements =<br />
The purpose of this document is to go through every Geyser element and provide practical examples on how they are used. Read it from top to bottom, preferably doing all of the examples to understand how they work!<br />
<br />
== Technical manual ==<br />
<br />
See https://www.mudlet.org/geyser/files/index.html for a brief and technical overview of all Geyser elements and their functions.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html Geyser.Container]==<br />
An invisible, organizing object in Geyser - use it to divide your screen and position elements accordingly. '''[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html See here]''' for all of the functions that are available to you to use.<br />
<br />
A container is also the base class - which means that everything (labels, miniconsoles and gauges) can use its functions, since everything else is at heart a container.<br />
<br />
=== Creating a container ===<br />
To get started with a container, here's an example that'll create a 200px border on the left side of Mudlet for you, and make a container cover all of it - so you can place other visual elements inside it:<br />
<br />
<syntaxhighlight lang="lua"><br />
setBorderLeft(200)<br />
left_container = Geyser.Container:new({<br />
name = "left_container", -- give it a unique name here<br />
x=0, y=0, -- have it start at the top-left corner of mudlet<br />
width = 200, height="100%", -- with a width of 200, and a height of the full screen, hence 100%<br />
})<br />
</syntaxhighlight><br />
<br />
Right away, you'll see space appear on the left side. It'll be black, as the container is an invisible unit by itself. You can make sure it's there by making it flash by doing this from the input line:<br />
<br />
<syntaxhighlight lang="lua">lua left_container:flash()</syntaxhighlight><br />
<br />
The command will cause your container to flash for a moment for you, revealing itself.<br />
<br />
{{Note}} If you hide a container and create new Geyser elements within it, they'll be shown automatically for you.<br />
<br />
=== Container within a container ===<br />
You can place containers within other containers by specifying which "parent" the new container should have when you create one. Given our [[#Creating a container|previous example]], you can split the left side into two halves like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
left_container_top = Geyser.Container:new({<br />
name = "left_container_top",<br />
x=0, y=0, -- this container occupies the top, so it starts top-left as well<br />
width = "100%", height="50%", -- but only uses up half of the height<br />
}, left_container) -- this is the important bit - it says that left_container_top should be inside left_container<br />
<br />
left_container_bottom = Geyser.Container:new({<br />
name = "left_container_bottom",<br />
x=0, y="50%", -- this container starts halfway down the first one<br />
width = "100%", height="50%", -- and has the same half height of the original container<br />
}, left_container) <br />
</syntaxhighlight><br />
<br />
=== Aligning relative to bottom or right sides ===<br />
The aligning point within Mudlet is the top-left corner, and it's the same for the elements they are aligned - the position you specify is used by the top-left corner of the element.<br />
<br />
Using Geyser, you can align to the opposite side as well, using the coordinates in negatives, while keeping the dimensions of the object in mind. For example, if you want to align a box that's 20px wide on the usual left side, you'd give it a width of 20 and an x value of 0. If you'd like to align it on the right side, then you'd give it an x value of -20. The box will spawn 20px away from the right side and "grow" to the right by 20px.<br />
<br />
<syntaxhighlight lang="lua"><br />
right_container = Geyser.Container:new({<br />
name = "right_container",<br />
x="-20%", y=0, -- makes the container start 20% of the screen away from the right side<br />
width = "20%", height="50%", -- filling it up until the end<br />
}) <br />
</syntaxhighlight><br />
<br />
Do make sure to account for the scrollbar, as Mudlet UI elements can overlap it. You can also move the scrollbar with [[Manual:UI_Functions#setBorderRight|setBorderRight()]].<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html Geyser.Label]==<br />
Labels allow you to use pictures in your interface, as well as nicely-formatted text - see docs for label [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html functions].<br />
<br />
=== Basic label ===<br />
<br />
Here's an example to get you started with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
</syntaxhighlight><br />
<br />
This labels '''x''' coordinate is specified as 50% - and because it's not attached to any container, this implies that the window will start halfway at the main window. You can tell it's not attached to a container because there's nothing in between the last ''}'' and '')'', the place where the container goes.<br />
<br />
The '''y''' coordinate is 0 - which means that the label will start at the top of the screen. With the width being 50%, the label will occupy 50% of the screen - and since it starts at the halfway point, it means it'll occupy the entire right side. A height of 100% means that it'll stretch from the top to the full bottom.<br />
<br />
Here's what that'll look like:<br />
<br />
[[File:Simple-label.png|center|600px]]<br />
<br />
<br />
Playing around with the starting location and dimensions, we can also place it in the center of the screen with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
})<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
[[File:Simple_label_centered.png|center|600px]]<br />
<br />
To change the message on a label, you can use the ''mylabel:echo()'' function, where ''mylabel'' is the name of the label you gave it:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("hello!")<br />
</syntaxhighlight><br />
<br />
To get rid of the label, use the '':hide()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:hide()<br />
</syntaxhighlight><br />
<br />
=== Coloring text ===<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black", -- default text colour<br />
color = "SeaGreen" -- default label background<br />
})<br />
<br />
-- You can also change colour of text on demand with:<br />
testlabel:echo[[<p style="color:blue;">You can change the text color of a whole sentence or paragraph...</p><p>...or you can change the text color of one <span style="color:green;">word</span> or even a single l<span style="color:red;">e</span>tter.</p>]]<br />
</syntaxhighlight><br />
<br />
=== Setting the font size ===<br />
<br />
To set a different font size for your Label, use the ''setFontSize()'' method. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel:setFontSize(14)<br />
</syntaxhighlight><br />
<br />
The font size is set in Pt, so anything above 30 will likely be too large to be useful.<br />
<br />
=== Label inside a container ===<br />
<br />
Once you've got your containers and mastered the basic labels, you can drop labels into your nicely-organized containers. Doing so is similar to nesting containers:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
}, left_container_bottom) -- this is where we tell it what container to go into<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
That label is exactly the same as the one above that goes across the screen, except it's in our bottom-left container - so it looks appropriately different:<br />
<br />
[[File:Label in a container.png|center]]<br />
<br />
=== Image on a label ===<br />
One of the more amazing things labels allow you to do is put pictures anywhere on your Mudlet screen, that blend in very well. To do so, once the label is created, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setBackgroundImage setBackgroundImage()] function with the exact path to the image ([[File:Skullface.png]]):<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 0, y = "-14px",<br />
width = "16px", height = "14px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/skullface.png]]) -- update location to actual image location on your computer<br />
</syntaxhighlight><br />
<br />
This'll plop the picture to the bottom-left of your screen. To make the picture show, download the skullface picture above - save it to your desktop, and adjust the location of the image within [[]]'s to what it is on your computer. For example, if you saved this on your Windows desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[C:/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
(yes, that's / and not \ - \ has been known not to work)<br />
<br />
If you saved this on your Mac desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
If you saved this on your Ubuntu desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/home/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
Using this basic building block, you can work up to making yourself a UI!<br />
<br />
=== Stretching an image on a label ===<br />
If you'd like your image not to keep its original size, but instead use up the available space of the label - you can use the [http://doc.qt.io/qt-5/stylesheet-reference.html#border-image border-image] stylesheet property to do so.<br />
<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- change the location to your picture<br />
-- on windows, use / to separate folders still, not \<br />
label:setStyleSheet[[<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);<br />
]]<br />
</syntaxhighlight><br />
<br />
{{note}} If you're on a Mudlet earlier than 3.15 and are having difficulty with the image coming up, it may be because of strange differences between Qt's CSS engine which does not affect mudlet's Lua. You may want to try appending :gsub("\\","/") to your string including getMudletHomeDir() (e.g. <code>getMudletHomeDir():gsub("\\","/")</code>). No longer necessary after Mudlet 3.15.<br />
<br />
=== Aligning an image within a label ===<br />
You can use background-image in combination with background-position to align an image within a label (if, say, the image is much smaller than the label).<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this will set and align an image top-right of the label<br />
if stunning then<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-ok.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
else<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-no.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
end<br />
</syntaxhighlight><br />
<br />
=== Showing / hiding a label ===<br />
You can show and hide labels, as you can any container, miniconsole or a gauge in Geyser with [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:show Geyser.Container:show()] and [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:hide Geyser.Container:hide()]. Remember that since labels are a type of a container, all container functions work on them.<br />
<br />
Hiding a label will allow you to click through on what is below the label, as well as free up the visual space for something else.<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- hide the label with:<br />
testlabel:hide()<br />
<br />
-- show the label with:<br />
testlabel:show()<br />
</syntaxhighlight><br />
<br />
=== Clickable images ===<br />
Tacking onto the fact that you can plop images anywhere on your Mudlet screen now, you can also make them react to your clicks. You can do so with the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setClickCallback setClickCallback()] function - by giving it a function to call when your label is clicked, you'll make it react.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "-215px", y = "0px",<br />
width = "200px", height = "200px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/qubodup-opengameart-cc0-200px-missile_icon.png]]) -- update location to actual image location on your computer<br />
picture_label:setClickCallback("on_bomb_press")<br />
<br />
function on_bomb_press()<br />
send("say BOOM!")<br />
end<br />
</syntaxhighlight><br />
<br />
That's it! Pressing on the image will make the ''on_bomb_press()'' function go off, which will do its code of ''send("say BOOM!")''. Download the picture for use [http://opengameart.org/content/missile-rts-icon here].<br />
<br />
[[File:Clickable_image.png|500px|center]]<br />
<br />
=== Styling labels ===<br />
Besides putting text or images on labels, you can also style them using Qt's stylesheets feature. Doing so allows you to create various graphics that make the label look more appealing:<br />
<br />
[[File:Label_styling_examples.png|center]]<br />
<br />
To set a stylesheet on a label, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setStyleSheet Geyser.Label:setStyleSheet()] function on your label, describing the stylesheet you'd like to give it. A stylesheet consists of properties you set - for example the background color, borders, padding, and so forth. You describe properties in the following format: ''property name''''':'''''values''''';'''. See here for a [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties list of all supported properties]. For example, to make your labels background be yellow, you'd use the background-color property:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "mylabel",<br />
x = "50%", y = "50%",<br />
width = 200, height = 100<br />
})<br />
<br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet.png|center]]<br />
<br />
Which is nice, but not particularly impressive.<br />
<br />
Scrolling down the list of properties, you'll come along a border one. Plopping it into our stylesheet nets the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
border: 5px solid white;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border.png|center]]<br />
<br />
Which gives a border!<br />
<br />
Fiddling with it some more and applying new properties we find on that page, we get a rounded border on our label:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: grey;<br />
border-width: 15px;<br />
border-style: solid;<br />
border-color: green;<br />
border-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border_radius.png|center]]<br />
<br />
Which'll conclude our exploration for now. Try out all of the other possible options available there - there's loads, from [http://doc.qt.io/qt-5/stylesheet-reference.html#border-style funky borders], to tiling images and fancy color combinations using gradients.<br />
<br />
You should also check out [[Manual:Geyser#Geyser.StyleSheet|Geyser.StyleSheet]] for a way to manage your stylesheets with adjustable properties and the ability to take defaults from another stylesheet.<br />
<br />
=== Adding a tooltip to a label ===<br />
<br />
Since Mudlet 4.6, you can now add a tooltip to labels and gauges. You can start by making a simple label and echoing some text to it:<br />
<br />
<syntaxhighlight lang="lua"><br />
testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = "50%",<br />
y = "50%",<br />
height = "25%",<br />
width = "25%",<br />
})<br />
testLabel:echo("This is on the label!")<br />
testLabel:setAlignment("center")<br />
-- sets the tooltip text<br />
testLabel:setToolTip("This is the tooltip", "10")<br />
<br />
<br />
-- optionally - you can customise the tooltip, too!<br />
testLabel:setStyleSheet("QToolTip{background: yellow; color: blue; border:none;}")<br />
</syntaxhighlight><br />
<br />
Without tooltip<br />
[[File:TestLabelForTooltips.png|thumb|center]]<br />
<br />
With tooltip<br />
<br />
[[File:LabelTooltip.png|thumb|center]]<br />
<br />
=== Avoid stylesheet inheritance by tooltip ===<br />
<br />
{{note}} If you set a new stylesheet for a label and with that a background image it is possible that through inheritance the tooltip also has this stylesheet image.<br />
<br />
To avoid this specify that the stylesheet is meant for the Label by using QLabel{...} in your Label stylesheet for exampleː<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- by using QLabel{...} the stylesheet won't be given to the tooltip as well<br />
label:setStyleSheet[[<br />
QLabel{<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);}<br />
]]<br />
</syntaxhighlight><br />
<br />
<br />
=== Aligning text/images inside a label ===<br />
By default, text is [http://qt-project.org/doc/qt-5/qlabel.html#alignment-prop centered vertically and left aligned] in a label. To align it to a specific side, use the stylesheets we learnt about earlier with the qproperty-alignment:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- specify one property this way:<br />
mylabel:setStyleSheet([[qproperty-alignment: 'AlignTop';]])<br />
<br />
-- or multiple ones separated with a |, for example this will align text to top-left:<br />
mylabel:setStyleSheet([[<br />
qproperty-alignment: 'AlignLeft | AlignTop';<br />
]])<br />
<br />
mylabel:echo("hi!")<br />
</syntaxhighlight><br />
<br />
[[File:Text_aligned.png|center]]<br />
<br />
=== Enabling wordwrap in a label ===<br />
If you need to enable word wrapping in a label (which by default is off), add the following line to the labels stylesheet:<br />
<br />
qproperty-wordWrap: true;<br />
<br />
As an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
If you'd like to set multiple properties, set them all at once - not via multiple :setStyleSheet() calls:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background: red;<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Adding a hover effect to a label ===<br />
The labels support adding stylesheets for specific cases, such as when a mouse is [http://doc.qt.io/qt-5/stylesheet-reference.html#hover-ps hovering] over them. To make this work, you provide CSS for when the label is in its usual state, and for when it is hovered over:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this example will add a border to the label when it is hovered over<br />
mylabell:setStyleSheet([[<br />
QLabel{ border-radius: 4px; }<br />
QLabel::hover{<br />
background-color: rgba(0,0,0,0%);<br />
border: 4px double green;<br />
border-radius: 4px;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Checkboxes ===<br />
Combining the fact that you can click on a label with an image to do something with the fact that you can change pictures on a label at will, you can make an image that changes itself when you click on it.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "50%", y = "50%",<br />
width = "21px", height = "19px"<br />
})<br />
-- a little trick we do to make the background of the label be transparent<br />
picture_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
picture_label:setClickCallback("on_checkbox_press")<br />
<br />
function on_checkbox_press()<br />
if checkbox_ticked then<br />
checkbox_ticked = false<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_unticked.png]])<br />
echo("Checkbox unticked.\n")<br />
else<br />
checkbox_ticked = true<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
echo("Checkbox TICKED!\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
The ''on_checkbox_press()'' function this time keeps the track of the checkbox with the ''checkbox_ticked'' variable and sets the image appropriately. You can download the ticked ([[File:Checkbox_ticked.png]]) and unticked images ([[File:Checkbox_unticked.png]]) or the [http://wiki.mudlet.org/images/6/6d/Checkbox.mpackage whole package] altogether.<br />
<br />
[[File:Checkbox_demo.png|500px|center]]<br />
<br />
=== Animated labels with sprites ===<br />
You can animate sprite packs using timers. Assuming you have the sprite pack downloaded, try this example:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 10, y = "-24px",<br />
width = "16px", height = "14px",<br />
})<br />
<br />
santa_counter = nil<br />
<br />
function animate_santa()<br />
santa_counter = (santa_counter or 0) + 1<br />
if santa_counter > 8 then santa_counter = 1 end<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/santa/santa]]..santa_counter..[[.png]]) -- update location to actual image location on your computer<br />
santa_timer = tempTimer(.16, animate_santa)<br />
end<br />
<br />
animate_santa()<br />
</syntaxhighlight><br />
<br />
The completed package is available [http://wiki.mudlet.org/images/6/6b/Dancing-santa.mpackage here], install it and do '''start/end animation''' to watch.<br />
<br />
=== Inserting extra spaces and newlines ===<br />
Echoing text into Mudlet and Geyser labels is different from miniconsoles and the main window, due to their nature. One of the differences is that extra spaces in a label, by default, get compressed down to one. '''To add extra spaces in a label''', replace extra spaces with '''&amp;nbsp;''' or by wrapping your text with them inside '''<nowiki><pre>my text here</pre></nowiki>'''.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this won't work, it'll show as one space:<br />
mylabel:echo("You -> point")<br />
<br />
-- but this would, because it replaces all spaces with &nbsp before echoing<br />
mylabel:echo(string.gsub("You -> point", " ", "&nbsp;"))<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- here is another way to go about this - and it additionally makes the font be monospaced:<br />
mylabel:echo("<pre>You -> point</pre>")<br />
</syntaxhighlight><br />
<br />
'''To add a new line in a label''' (aka linebreak), use '''<nowiki><br></nowiki>''' (instead of ''\n'' as you are used to in an echo).<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("These<br>words<br>are<br>split")<br />
</syntaxhighlight><br />
<br />
=== Transparent labels ===<br />
One of the possible ways of achieving transparency on a label is to add <code>background-color: rgba(0,0,0,0%);</code> to its stylesheet. Here's an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
my_transparent_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
</syntaxhighlight><br />
<br />
Want to get transparency in a miniconsole? You can [[Manual:Geyser#Change_your_miniconsole_background_image|do that as well]].<br />
<br />
=== Custom mouse cursor ===<br />
You can change the shape of the cursor when it's over your label with:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCursor("Forbidden") -- will change your mouse cursor to "forbidden" (as in "can't do this") cursor<br />
</syntaxhighlight><br />
Possible cursor shapes are [[CursorShapes| available here]], and you can import this [[Media:Cursor grid.zip|demo package]] to try them all out.<br />
<br />
It is also possible to change the mouse cursor to a custom made cursor by:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCustomCursor(getMudletHomeDir().."/custom_cursor.png")<br />
</syntaxhighlight><br />
It is recommended that the custom cursor is a png with size of 32x32 to be supported on all systems.<br />
<br />
[[File:Changecursoroverlabel.gif]]<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
=== Flyout Labels ===<br />
<br />
Flyout labels allow you to create 'dropdown' or 'flyout' menus - menus that reveal more items once you hover your mouse over them. To create flyout labels:<br />
# add <code>nestable=true</code> (left click to open menu) or <code>nestflyout=true</code> (mouse hover to open menu) to your main label.<br />
# use [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] on your main label to add flyout labels to it.<br />
## [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] uses the same arguments as when creating a new label but also takes the '''layoutDir''' option to specify in which direction and axis should the labels align, where 2 letters combine into the option: first letter R for right, L for left, T for top, B for bottom, followed by the orientation: V for vertical or H for horizontal. So options are: <code>layoutDir="RV"</code>, <code>layoutDir="RH"</code>, <code>layoutDir="LV"</code>, <code>layoutDir="LH"</code>, and so on.<br />
# optionally, add <code>flyOut=true</code> to your flyout labels to make the labels dissapear when the mouse isn't hovering over them anymore.<br />
<br />
Note that the main flyout label cannot go into a container and needs to be on its own.<br />
<br />
{{note}} Requires Mudlet 3.0.<br />
<br />
==== Demo ====<br />
Here's an example that follows the steps above:<br />
<br />
<syntaxhighlight lang="lua"><br />
label0 = Geyser.Label:new({name="label0", <br />
x="50%",y="50%",height=50,width=300,nestable=true, <br />
message="<center>Clicky clicky</center>"})<br />
<br />
-- and add 3 labels to it with RV layout - so Right of the label, aligned Vertically<br />
label1 = label0:addChild({name="label1",height=30,width=70, layoutDir="RV", flyOut=true, message="label one"})<br />
label1:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label2 = label0:addChild({name="label2",height=30,width=70, layoutDir="RV", flyOut=true, message="label two"}) <br />
label2:setStyleSheet([[background-color: green; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label3 = label0:addChild({name="label3",height=30,width=70, layoutDir="RV", flyOut=true, message="label three"})<br />
label3:setStyleSheet([[background-color: red; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
</syntaxhighlight><br />
<br />
A more thorough example. Try it out to see what you can create with flyout labels:<br />
<syntaxhighlight lang="lua"><br />
-- create a label with a nestable=true property to say that it can nest labels<br />
mainlabel = Geyser.Label:new({name="testa", x=400,y=50,height=50,width=300,nestflyout=true, message="<center>HOVER HERE TO SEE FLY-OUT LABELS!</center>"})<br />
<br />
-- create 15 labels and store them in a table <br />
table_for_flyout_labels = {}<br />
for i=1,15 do<br />
-- options to layoutDir are the direction the window should go (R for right, L for left, T for top, B for bottom), followed by how the nested labels should be oriented (V for vertical or H for horizontal). So "BH" here means it'll go on the bottom of the label, while expanding horizontally<br />
table_for_flyout_labels[i] = mainlabel:addChild({name="test"..tostring(i),height=30,width=70, layoutDir="BH", flyOut=true, message="test"..tostring(i)})<br />
<br />
table_for_flyout_labels[i]:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px;]])<br />
end<br />
<br />
-- make the test5 label look a bit special as it has got a surprise<br />
table_for_flyout_labels[5]:echo("Hover here")<br />
<br />
-- add even more nested labels to the 5th label!<br />
even_more_flyout_labels = {}<br />
for i=1,60 do<br />
-- here, the layout will be to the right of it, while expanding vertically<br />
even_more_flyout_labels[i]=table_for_flyout_labels[5]:addChild({name="hover label "..tostring(i),height=30,width=100, layoutDir="RV", flyOut=true, message="label "..tostring(i)})<br />
even_more_flyout_labels[i]:setClickCallback("testFunc", even_more_flyout_labels[i].name)<br />
even_more_flyout_labels[i]:setStyleSheet([[background-color: grey; border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]])<br />
end<br />
<br />
function testFunc(name)<br />
display(name)<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look something like this: <br />
<br />
[[File:Flyout_labels_demo.png|150px]]<br />
<br />
==== Demo of layouts ====<br />
Here's another demo that explains all of the layout styles quite well:<br />
<syntaxhighlight lang="lua"><br />
local directions = {"R", "L", "T", "B"}<br />
local orientations = {"V", "H"}<br />
local mappings = {R = "right", L = "left", T = "top", B = "bottom", V = "vertical", H = "horizontal"}<br />
<br />
local combinations, combination_labels = {}, {}<br />
for _, direction in pairs(directions) do<br />
for _, orientation in pairs(orientations) do<br />
combinations[#combinations+1] = direction..orientation<br />
end<br />
end<br />
<br />
local function get_foreground_text_colour(r,g,b)<br />
local luminosity = (0.2126 * ((r/255)^2.2)) + (0.7152 * ((g/255)^2.2)) + (0.0722 * ((b /255)^2.2))<br />
if luminosity > 0.5 then<br />
return "black"<br />
else<br />
return "white"<br />
end<br />
end<br />
<br />
local function get_random_colour_rgb()<br />
return math.random(1,255), math.random(1,255), math.random(1,255)<br />
end<br />
<br />
-- create a label with a nestable=true property to say that it can nest labels<br />
all_possible_combinations_label = Geyser.Label:new({name="all_possible_combinations_label", x=0,y="-400",height=50,width=500,<br />
nestable = true, message="<center>Click to see a listing of possible combinations</center>"})<br />
<br />
for i = 1, #combinations do<br />
local combination = combinations[i]<br />
combination_labels[i] = all_possible_combinations_label:addChild({name="combo_"..combination,height=30,width=150, nestable = true, flyOut=true, layoutDir="BH", message="<center>Combination "..combination.."</center>"})<br />
<br />
local r,g,b = get_random_colour_rgb()<br />
local text_colour = get_foreground_text_colour(r,g,b)<br />
<br />
local combination_labels_children = {}<br />
for ii = 1, 3 do<br />
combination_labels_children[ii] = combination_labels[i]:addChild({<br />
name="combo_"..combination.."_"..ii, height = 30, width = 150, layoutDir=combination, flyOut = true,<br />
message = string.format("<center><b>%s</b>%s+<b>%s</b>%s layout</center>", <br />
combination:sub(1,1), mappings[combination:sub(1,1)]:sub(2), combination:sub(2,2), mappings[combination:sub(2,2)]:sub(2)),<br />
fgColor = text_colour})<br />
<br />
combination_labels_children[ii]:setStyleSheet(string.format([[background-color:rgb(%d, %d, %d); border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]], r,g,b))<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look like this:<br />
<br />
[[File:Flyoutlabels-layout-demo.png]]<br />
<br />
=== Geyser.Label right click menu ===<br />
{{MudletVersion|4.10}}<br />
<br />
You can create a right click menu for a label just by using the function (assuming your label name is 'myLabel'):<br />
<syntaxhighlight lang="lua"> myLabelːcreateRightClickMenu({MenuItems = menuTable}) -- scroll down for a fuller example with more details </syntaxhighlight><br />
<br />
The menu table comprises of all the items and their names. To create a parent menu just create a nested table of names.<br />
<br />
Example of a menuTable:<br />
<syntaxhighlight lang="lua"> menuTable = {"First Item", "Second Item (Parent)", {"First ChildItem", "Second ChildItem"}, "Third Item"} </syntaxhighlight><br />
<br />
The menu would look like thisː<br />
<br />
[[File:RCDemo1.gif|250px]]<br />
<br />
You can give more constraints to further style and enhance your right click menu.<br />
<br />
==== Style your right click menu ====<br />
Your right click menu has 2 default styles integratedː "light" and "dark" which are defined by the constraint "Style".<br />
<br />
To set a default style just give the constraint Style the preferred value, for exampleː<br />
<syntaxhighlight lang="lua"> Style = "dark" </syntaxhighlight><br />
<br />
To give different levels of your menu different style just add the number of the level to the constraint, for exampleː<br />
<syntaxhighlight lang="lua"> Style2 = "light" -- Gives the second level of your menu the "light" style</syntaxhighlight><br />
<br />
For adding your own stylesheet use the constraint MenuStyle (use the same method as above to define stylesheets for different levels)<br />
<syntaxhighlight lang="lua"> MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]] <br />
-- Gives the second level of your menu this stylesheet</syntaxhighlight><br />
<br />
The same methods are used for defining the format, width and height for the menu item.<br />
<syntaxhighlight lang="lua"> <br />
MenuWidth = 70 -- standard menu width if nothing else is given<br />
MenuWidth2 = 80 -- menu width for the second level <br />
MenuFormat1 = "c10" -- menu format for the first level (format works like any other label echo format, in this case c is center and 10 is the font-size)<br />
MenuHeight = 30<br />
</syntaxhighlight><br />
<br />
==== Set onClick action for your menu item ====<br />
To set an action if your menu item is clicked use the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<syntaxhighlight lang="lua"> <br />
myLabelːsetMenuAction("First Item", function() echo("Clicked on the first item\n") end<br />
myLabelːsetMenuAction("Second Item (Parent).First ChildItem", function() echo("Clicked on the first child item\n") end) -- To set an action to a child item find it by using "Parent.Child" as name (only one parent is needed to be given the parents parent is not needed)<br />
</syntaxhighlight><br />
<br />
==== Access an menu item directly ====<br />
The simplest way to access a menu item directly is by just using the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<br />
For example to change the menu item textː<br />
<syntaxhighlight lang="lua"> <br />
myLabelːfindMenuElement("First Item"):echo([[my first Item]])<br />
</syntaxhighlight><br />
<br />
==== Right click menu example ====<br />
Better then any further explanation is probably this practical example. <br />
<br />
<syntaxhighlight lang="lua"> <br />
-- create the label the right click menu will be in<br />
myRightClickLabel = myRightClickLabel or Geyser.Label:new({<br />
name = "myRightClickLabel", message = "Please right click!", <br />
format = "cb15", x=10, y=10, width ="30%", height = "15%", <br />
color = "purple"})<br />
<br />
-- right click menu creation with custom styleheet on level2 and default "Dark" style <br />
myRightClickLabel:createRightClickMenu({<br />
MenuItems = {"Emergency", "Drink",{"ManaPotion","HealthPotion"}, "Disappear", "Cast",{"Blindness", "Blink"}}, <br />
Style = "Dark", <br />
MenuWidth2 = 80, <br />
MenuFormat1 = "c10",<br />
MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]]<br />
})<br />
<br />
myRightClickLabel:setMenuAction("Emergency", function() <br />
cecho("<red:pink>[Emergency Mode] Run as fast as possible!\n") <br />
send("emergency") <br />
closeAllLevels(myRightClickLabel) -- this can be used to close the right click menu if clicked on this item<br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.ManaPotion", function()<br />
cecho("<blue>Drinking my mana potion.\n") <br />
send("drink mp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.HealthPotion", function() <br />
cecho("<red>Drinking my health potion.\n") <br />
send("drink hp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Disappear", function() <br />
cecho("<grey>Disappearing.. \n") <br />
send("disappear") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blindness", function() <br />
cecho("<light_blue>Casting blindness \n") <br />
send("cast blindness enemy") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blink", function() <br />
cecho("<light_blue>Casting blink \n") <br />
send("cast blink") <br />
end )<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
<br />
[[File:Right click example demo.gif]]<br />
<br />
==== Add right click menu to label with already existing left click action ====<br />
If your label has an already existing left click action you'll have to create the right click menu<br />
"before" creating the labels "setClickCallBack" action and then just put into your labels onClick function<br />
(assuming your label name is 'myLabel' and 'event' is the last parameter of your onClick function)<br />
<br />
<syntaxhighlight lang="lua"> <br />
myLabel:onRightClick(event)<br />
</syntaxhighlight><br />
<br />
=== Geyser name ===<br />
Make sure to give your Geyser Labels, miniconsoles, and userwindows a <code>name</code> - while it'll technically work without one, items will be duplicated when you re-save them if they're lacking a name.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserStyleSheet.html Geyser.StyleSheet]==<br />
<br />
Allows you to create a managed stylesheet to make it easier to set and change properties. Also allows you to inherit properties from another stylesheet, making it easier to manage multiple styles at once.<br />
<br />
=== Basic Usage ===<br />
<br />
Here's an example to get you started. This creates a basic stylesheet to set the background color black and the foreground/text color to green, then applies it to a Geyser Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
local testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = 100,<br />
y = 100,<br />
height = 100,<br />
width = 300,<br />
stylesheet = stylesheet:getCSS(),<br />
})<br />
<br />
-- Alternate method of creating a stylesheet using a table of properties<br />
local stylesheet = Geyser.StyleSheet:new({<br />
['background-color'] = "black",<br />
['color'] = "green",<br />
})<br />
</syntaxhighlight><br />
<br />
=== Getting the CSS string === <br />
<br />
As shown above, you can use getCSS to get the stylesheet as a string.<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getCSS())<br />
--[[<br />
"background-color: black;\ncolor: green;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Including a target ===<br />
<br />
You can include a 'target' for your stylesheet to be applied to, such as QLabel, QPlainTextEdit, etc.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- QPlainTextEdit is useful for styling command lines in particular, to keep the style from bleeding into any associated miniconsole or userwindow.<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
QPlainTextEdit {<br />
background-color: black;<br />
color: green;<br />
}]])<br />
<br />
-- or as an optional third argument. Passing nil for the parent explicitly <br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]], nil, "QPlainTextEdit")<br />
<br />
-- or using the setTarget function after the fact<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
stylesheet:setTarget("QPlainTextEdit")<br />
</syntaxhighlight><br />
<br />
=== Changing a property ===<br />
<br />
Assuming you started with the example above, if you wanted to change the background color to purple you would do the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("background-color", "purple")<br />
testLabel:setStyleSheet(stylesheet:getCSS())<br />
</syntaxhighlight><br />
<br />
Or if you wanted to set the font, you would do:<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", [["Ubuntu Mono"]])<br />
</syntaxhighlight><br />
<br />
Note the way we set the font with the double quotes included in the string, this is because the quotes have to be there in the final stylesheet. You could use single quotes instead of the bracket notation as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", '"Ubuntu Mono"')<br />
</syntaxhighlight><br />
<br />
=== Getting the value of a property ===<br />
<br />
Again assuming you started with the example code above it's as easy as<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:get("color") -- will return "green"<br />
</syntaxhighlight><br />
<br />
=== Getting a table of properties and their values ===<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Setting the properties via table ===<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setStyleTable({<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"',<br />
})<br />
</syntaxhighlight><br />
<br />
=== Resetting the style with a string ===<br />
<br />
Creating a new Geyser.StyleSheet would break any inheritance for stylesheets which had this one as a parent (see below), so if you wish to reset the style via CSS string you should use :setCSS<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setCSS([[<br />
background-color: black;<br />
color: green;<br />
font: "Ubuntu Mono";<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Inheriting properties ===<br />
<br />
As with most things Geyser, just pass the parent in when you create the new stylesheet<br />
<br />
<syntaxhighlight lang="lua"><br />
local childsheet = Geyser.StyleSheet:new("color: blue;", stylesheet)<br />
display(childsheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "blue",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
<br />
display(childsheet:get("background-color")<br />
--"purple"<br />
<br />
-- show only properties set in this stylesheet, without inheritance<br />
display(childsheet:getStyleTable(false))<br />
--[[<br />
{<br />
color = "blue"<br />
}<br />
--]]<br />
<br />
-- can do the same for the CSS string<br />
display(childsheet:getCSS(false))<br />
--[[<br />
"color: blue;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html Geyser.MiniConsole]==<br />
This allows you to spawn a Mudlet miniconsole - unlike labels, these aren't as styleable, but they do format text better. They make a good fit for text-based menus, chat and map capture, and other things.<br />
<br />
Spawning one is very similar to other Geyser elements - paste this into a new script:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x="70%", y="50%",<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="30%", height="50%",<br />
})<br />
</syntaxhighlight><br />
<br />
This'll make you one at the bottom-right of the screen. The miniconsole will have a grey background by default, but you can set it to any color you'd like with [http://www.mudlet.org/geyser/files/geyser/GeyserWindow.html#Geyser.Window:setColor miniconsole:setColor()]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setColor("black") -- give it a nice black background<br />
</syntaxhighlight><br />
<br />
A special dimension property that MiniConsoles have is a character - instead of specifying a miniconsole to be % of a container or a certain number of pixels, you can specify it as a certain number of characters. You do this by using "c" at the end of a number. This way, you can, for example, specify miniconsole to be 10 letters long and 2 lines high:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="70%", y="50%",<br />
wrapAt = 10,<br />
width="10c", height="2c",<br />
})<br />
flatbox:setColor("red")<br />
flatbox:echo("ABCDEFGHIJ") -- that is 10 letters<br />
</syntaxhighlight><br />
<br />
=== Adding text ===<br />
You can use [[Manual:Technical_Manual#echo|echo()]] the same way with a miniconsole to add text as to the usual window:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("hello!")<br />
</syntaxhighlight><br />
<br />
As well as [[Manual:Technical_Manual#cecho|cecho]], [[Manual:Technical_Manual#decho|decho]], or [[Manual:Technical_Manual#hecho|hecho]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:cecho("<green>hey, <blue>colored <red>text!\n")<br />
</syntaxhighlight><br />
<br />
=== Copying lines with color ===<br />
To copy a line over to the miniconsole, as it is from the game with all colors preserved, you can [[Manual:UI_Functions#selectCurrentLine|select]], [[Manual:UI_Functions#copy|copy]], and [[Manual:UI_Functions#appendBuffer|append]] it. For an example, try making a trigger with this as the ''perl regex'' pattern type:<br />
<br />
<syntaxhighlight lang="lua"><br />
^<br />
</syntaxhighlight><br />
<br />
That'll make the trigger go off on every line. Then give it the following script (assumed you have made the HelloWorld miniconsole from earlier):<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
... and you'll see all MUD output duplicated exactly as it is to the miniconsole. Amazing! It's very efficient as well, so you can have many miniconsoles, even in spam, not lag you down.<br />
<br />
=== Clearing the miniconsole ===<br />
Clearing the miniconsole just requires using the following script (assumes you have made the HelloWorld miniconsole from earlier):<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:clear()<br />
</syntaxhighlight><br />
<br />
=== Doing edits in copied lines ===<br />
Sometimes you'll want to edit the line before stuffing it into the miniconsole. For example, if you're making a chat capture, you'd want to condense a really long org name into something that's more space-friendly.<br />
<br />
To do so, you'd use the [[Manual:Technical_Manual#selectString|selectString()]] the text you'd like to modify, [[Manual:Technical_Manual#replace|replace()]] it with a different one:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Your", 1) -- select the word you'd like to replace - in this case, 'Your'<br />
setBgColor(getBgColor()) -- preserve the background color in the replacement<br />
setFgColor(getFgColor()) -- preserve the foreground color in the replacement<br />
replace("Mine") -- replace the selection with the wird 'Mine'<br />
<br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
=== Gagging from the main window ===<br />
If you'd like to gag the line from the main window so it only shows up in your miniconsole, [[Manual:Technical_Manual#deleteLine|delete]] it after moving it over:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=== Clickable menus ===<br />
Using the [[Manual:Technical_Manual#echoLink|echoLink]], [[Manual:Technical_Manual#insertLink|insertLink]] and [[Manual:Technical_Manual#setLink|setLink]] functions, you can turn text into one that reacts on a click. Combined with your power of placing text anywhere on the screen with a miniconsole, you can make menus with options. Here is one such example, where selecting an item causes an echo to happen:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="20%", y="80%",<br />
width="40c", height="4c",<br />
})<br />
flatbox:setColor("red")<br />
clearWindow("flatbox")<br />
<br />
flatbox:cecho("<white:red>Choose one of the following options:\n")<br />
<br />
flatbox:fg("white")<br />
flatbox:bg("red")<br />
<br />
for _, fruit in ipairs{"banana", "apple", "orange"} do<br />
echoLink("flatbox", "* "..fruit:title().."\n", [[echo("You picked ]]..fruit..[[\n")]], "The "..fruit.." option", true)<br />
end<br />
<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
This will produce something like the following:<br />
<br />
[[File:Fruit_menu.png|center]]<br />
<br />
=== Change your miniconsole background image ===<br />
{{MudletVersion|4.10}}<br />
<br />
To set a custom background image for your miniconsole, use [https://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html#Geyser.MiniConsole:setBackgroundImage :setBackgroundImage()]:<br />
<syntaxhighlight lang="lua"><br />
miniconsole_withBgImg = Geyser.MiniConsole:new({name = "BackgroundonConsole", x="50%", y="50%", width = "20%", height = "40%"})<br />
miniconsole_withBgImg:setBackgroundImage(":/Mudlet_splashscreen_development.png", "center")<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:decho("<:0,0,0,130> This is a decho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:hecho("#,80000000 This is a hecho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:decho("<:0,0,0> This is a decho test with no transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:hecho("#,000000 This is a hecho test with no transparent background\n")<br />
end<br />
</syntaxhighlight><br />
<br />
=== Enable and use your miniconsole command line ===<br />
{{MudletVersion|4.10}}<br />
<br />
Every miniconsole has a hidden command line. Enable it with:<br />
<syntaxhighlight lang="lua"><br />
HelloWorldContainer = HelloWorldContainer or Adjustable.Container:new({name="HelloWorldContainer", titleText = "Container with a command line"})<br />
<br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "purple",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, HelloWorldContainer)<br />
<br />
HelloWorld:enableCommandLine()<br />
</syntaxhighlight><br />
<br />
=== Set an action to your miniconsole command line ===<br />
If no action is set to your miniconsole command line the commands are send to the game the same way as for the main command line. Aliases still work as usual, and if you have command echo enabled in preferences, it'll show in both miniconsole and the main window.<br />
<br />
It is also possible to set an action to your command line, this enables you to use the command line as custom text input.<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:enableCommandLine()<br />
local function channelChat(text)<br />
send("chat "..text)<br />
HelloWorld:echo("[chat] " ..text.."\n")<br />
end<br />
<br />
HelloWorld:setCmdAction(channelChat)<br />
</syntaxhighlight><br />
<br />
This will send your miniconsole command line input to the chat channel.<br />
<br />
More complicated/sophisticated actions are possible, setCmdAction works the same way as the Label clickCallback functions - that is, you can pass arguments to it.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html Geyser.Gauge]==<br />
<!--<br />
This is a composite window. Gauge duplicates the functionality of the built in Mudlet gauges, but in a clean and easily extended way. Internally, a Geyser Gauge is a container holding two Labels, front and back, which are initially scaled to fill the entire Gauge container. Hence, a gauge, g, can be given callbacks with the g.front:setClickCallback() method.<br />
<br />
The backgroundColor parameter initially sets the colors of the gauge, but of course the front and back components can be accessed individually as labels for high control over their looks. Gauges can be horizontal or vertical and decrease in value left to right, right to left, down up or up down depending on the value of the orientation parameter.<br />
--><br />
<br />
A Gauge allows you to represent numbers on a scale - and most typically, you've seen it be used as your standard hp/mana/whatever bar. A basic bar is made similarly to other Geyser elements. To set the value on the gauge that it should represent, use the [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] function:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="5%",<br />
})<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
That'll spawn you a pretty basic gauge with a horizontal orientation and a grey colour - and as a test, with a random value.<br />
<br />
[[File:Basic_gauge.png|center]]<br />
<br />
=== Updating a gauge ===<br />
You'd want your gauge to stay in sync with your actual values. To make that happen, you want to call [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] whenever the value that the gauge is tracking changes.<br />
<br />
So for example, if you make a health bar - wherever you get your new health at (be it prompt, gmcp, atcp or whatever), update the gauge as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- theoretical example<br />
current_health, max_health = tonumber(matches[2]), tonumber(matches[3])<br />
<br />
-- update the bar<br />
hp_bar:setValue(current_health, max_health)<br />
</syntaxhighlight><br />
<br />
You can also write down how much health have you got on the bar with:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local hp = math.random(1,100) <br />
hpbar:setValue(current_health, max_health, "<b>"..max_health.."hp</b>")<br />
<br />
-- example using GMCP in IRE games:<br />
hpbar:setValue((100/gmcp.Char.Vitals.maxhp)*gmcp.Char.Vitals.hp,100,gmcp.Char.Vitals.hp)<br />
</syntaxhighlight><br />
<br />
[[File:Hpbar_basic.png|center]]<br />
<br />
=== Styling a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. Combining this with Geyser:Label.setStyleSheet, you can improve the visuals of your gauges by using Qt-supported CSS. The syntax for specifying CSS is a bit different - it requires a semicolon after every property, and is done in the format of ''property name''''':'''''values''''';'''. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here] and you can use [https://build-system.fman.io/qt-designer-download Qt Designer] to create them. Practical example:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #98f041, stop: 0.1 #8cf029, stop: 0.49 #66cc00, stop: 0.5 #52a300, stop: 1 #66cc00);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #78bd33, stop: 0.1 #6ebd20, stop: 0.49 #4c9900, stop: 0.5 #387000, stop: 1 #4c9900);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge.png|center]]<br />
<br />
The same style can be adjusted by colors to red as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f04141, stop: 0.1 #ef2929, stop: 0.49 #cc0000, stop: 0.5 #a40000, stop: 1 #cc0000);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bd3333, stop: 0.1 #bd2020, stop: 0.49 #990000, stop: 0.5 #700000, stop: 1 #990000);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge_red.png|center]]<br />
<br />
=== Updating a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. To make a gauge clickable you can set a ClickCallBack on the top label which is ''mygauge.text'' example: <syntaxhighlight lang="lua">mygauge.text:setClickCallback("functionName", variableToSendToFunctionName)</syntaxhighlight><br><br />
If you would like to have different click events for the top or back of a gauge you can enable clickThrough for the top or ''mygauge.text'' label example<br />
<br />
<syntaxhighlight lang="lua"><br />
mygauge.text:enableClickthrough()<br />
mygauge.front:setClickCallback("functionOne", variableToSendToFunctionOne)<br />
mygauge.back:setClickCallback("functionTwo", variableToSendToFunctionTwo)<br />
</syntaxhighlight><br />
<br />
<br />
=== Tooltips on gauges ===<br />
Tooltips are available since Mudlet 4.6 as explained in above section [[#Adding_a_tooltip_to_a_label]], and as gauges are really only made up of labels as well, you could add a tooltip then by just using <syntaxhighlight lang="lua">mygauge.text:setToolTip("This is the gauge's tooltip", "10")</syntaxhighlight> the same as it's handled for clickback.<br />
<br />
== HBox/VBox ==<br />
<br />
These are special types of containers. Every window in these is horizontally or vertically aligned in the order they were added.<br />
<br />
{{MudletVersion|2.0}}<br />
<br />
== Geyser.UserWindow ==<br />
Allows you to use Mudlets UserWindows within Geyser, which allows you to use all the functionality of a MiniConsole in its basic form.<br />
The big advantage is the possibility to add other Geyser Elements like Labels, MiniConsole, Gauges, Mappers to the UserWindow.<br />
The UserWindow then can act as container for those elements with all the perks of dynamic resizing or any other Geyser functionality.<br />
<br />
{{MudletVersion|4.6.1}}<br />
<br />
===Basic floating userwindow ===<br />
This will create a movable floating userwindow.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "TestUserWindow",<br />
titleText ="My Test UserWindow", -- only available since Mudlet 4.8+<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
</syntaxhighlight><br />
<br />
You can change the title of the userwindow by using the parameger titleText and the functions below (as of Mudlet 4.8+)ː<br />
<br />
To set a new title after creation useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setTitle("My new title Text")<br />
</syntaxhighlight><br />
<br />
To revert to the standard title useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:resetTitle()<br />
</syntaxhighlight><br />
<br />
To '''save the position''' of the userwindow - say in case you've dragged it onto another monitor and would like it to stay there when you restart Mudlet - use [[Manual:UI_Functions#saveWindowLayout|saveWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
saveWindowLayout()<br />
</syntaxhighlight><br />
<br />
To restore it afterwards, use [[Manual:UI_Functions#loadWindowLayout|loadWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create your userwindows first with Geyser.UserWindow:new<br />
-- then restore them to the positions they were at:<br />
loadWindowLayout()<br />
</syntaxhighlight><br />
<br />
=== Docked UserWindow ===<br />
To create the window docked at the right side,<br />
set the variable docked (at creation of the container) to true.<br />
Be aware that with this variable set to true the position and the size at creation of the userwindow will be ignored.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true<br />
<br />
})<br />
</syntaxhighlight><br />
<br />
Since Mudlet 4.8+ it is also possible to choose the docking Position of the UserWindow at creation and by function withː<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true,<br />
dockPosition = "top" -- Possible dockPositions are left "l", right "r", top "t", bottom "b" and floating "f" <br />
})<br />
</syntaxhighlight><br />
<br />
To change it for a already created UserWindow use the function setDockPosition(dockPosition) likeː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setDockPosition("left")<br />
</syntaxhighlight><br />
<br />
=== Disable/enable UserWindow autoDock ===<br />
{{MudletVersion|4.8}}<br />
<br />
The auto docking feature can be really annoying at times. To disable it use the functionsː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:disableAutoDock() -- disables autoDock. Docking still possible with ːsetDockPosition<br />
testuserwindow:enableAutoDock() -- reenables autoDock<br />
</syntaxhighlight><br />
<br />
=== Styling the UserWindow border and title area ===<br />
{{MudletVersion|4.10}}<br />
{{note}} available on Linux only<br />
<br />
Geyser.UserWindows can accept a stylesheet to change the appearance of the border and title area and make<br />
the UserWindow look more appealing. This unfortunately only works in Linux, as in macOS and Windows, it is the OS theme that is used here. <br />
<br />
<syntaxhighlight lang="lua"><br />
myUserWindow = myUserWindow or Geyser.UserWindow:new({<br />
name = "myUserWindow", titleText = "myUserWindow", autoDock = false<br />
})<br />
<br />
myUserWindow:setStyleSheet( <br />
[[QDockWidget{<br />
border: 1px solid green; /* UserWindow border style */<br />
font: bold 15pt "Arial"; /* Font of the titleBar */<br />
color: rgb(0,0,150); /* Font color */<br />
}<br />
<br />
QDockWidget::title{ <br />
background-color: rgb(0,255,150); /* TitleBar color */<br />
border: 2px solid red; /* TitleBar border */<br />
border-radius: 2px; /* TitleBar border radius */<br />
text-align: center; /* alignment of the titleText */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
[[File:UserWindowStyleSheet.png]]<br />
<br />
=== UserWindow as Container ===<br />
This is the feature which shows the versatile nature of Geyser.UserWindows.<br />
The UserWindow act as container and is at that possible to dynamically resize the containing Geyser Elments.<br />
Put a label in the UserWindow resize it as rectangle.<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "ParentTestUserWindow",<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
<br />
testuserwindow:setColor("dark_green") -- give the userwindow a bit of color <br />
<br />
labelinuserw = Geyser.Label:new({<br />
name = "LabelinUserWindow",<br />
x=20, y=20,<br />
width = -20, height = -20,<br />
color="light_blue", fontSize=20,<br />
},testuserwindow)<br />
<br />
labelinuserw:echo("This is a label in an userwindow", "black", "c")<br />
</syntaxhighlight><br />
[[File:LabelInUserWindow.png]]<br />
<br />
The same way you are able to add your favorite Geyser Application (like tabbed chat, animated timers, gauges) to an UserWindow.<br />
<br />
Note that you don't need to add MiniConsoles to a UserWindow - as UserWindows already have them built-in.<br />
<br />
[[File:Tabbedchatinuserwindow.png]]<br />
<br />
== Geyser.CommandLine ==<br />
{{MudletVersion|4.10}}<br />
<br />
Allows you to create your custom command lines which can resize/move like any other Geyser object.<br />
<br />
If you just need a command line which is integrated in a miniconsole or userwindow, check out [[Manual:Geyser#Enable and use your miniconsole command line|:enableCommandLine()]].<br />
<br />
=== Creating a Geyser.CommandLine ===<br />
An example to get you startedː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine = myCommandLine or Geyser.CommandLine:new({<br />
name = "myCommandLine", <br />
x = "-20%", y = -40, <br />
width = "20%", height = 40,<br />
stylesheet = "border: 1px solid silver;"<br />
})<br />
</syntaxhighlight><br />
This creates a new command line in the right bottom of your screen.<br />
<br />
=== Bind action to your command line input ===<br />
If you use your previously created command line, any command will just be send to the game, after having been checked for aliases.<br />
<br />
To react to any input in a custom manner, we can set an action to the command line and use the input as parameter.<br />
<br />
Example of a command line changing the background color of your main console (assumes you have created "myCommandLine" from earlier): <br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setAction(<br />
function(commandLineInput)<br />
r, g, b = Geyser.Color.parse(commandLineInput) -- gets the r, g, b values of the color you input to the command line<br />
if b then -- checks if the color is valid<br />
setBackgroundColor(r, g, b)<br />
else<br />
echo("\n"..commandLineInput.." is not a valid color. Try again.")<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
=== Styling a command line ===<br />
You can style your Geyser command line by using Qt-supported CSS. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here].<br />
<br />
Practical example (assuming "myCommandLine" is created)ː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setStyleSheet([[<br />
QPlainTextEdit{ /* QPlainTextEdit is used to prevent the styleSheet bleeding to the right click menu*/<br />
border: 1px solid silver; /* Command line border style */<br />
background-color: rgb(0,255,150); /* Command line background color */<br />
font: bold 12pt "Arial"; /* Font and font-size of your command line */<br />
color: rgb(0,0,150); /* Command line text color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Create an extra command line in Mudlet ===<br />
If your goal is to just have an extra command/input line - say, for role-playing purposes: copy/paste the example below into a new script in Mudletː<br />
<br />
<syntaxhighlight lang="lua"><br />
inputContainer = inputContainer or Adjustable.Container:new({<br />
x = 0, y = "-4c", <br />
name = "InputContainer", padding = 2, <br />
width = "100%", height = "4c", <br />
autoLoad = false<br />
})<br />
<br />
extraCmdLine = extraCmdLine or Geyser.CommandLine:new({<br />
name = "extraCmdLine", <br />
x = 0, y = 0, width = "100%", height = "100%"<br />
}, inputContainer)<br />
<br />
inputContainer:attachToBorder("bottom")<br />
</syntaxhighlight><br />
<br />
This will look likeː <br />
<br />
[[File:AdditionalCommandLine.png|extra command line]]<br />
<br />
== Adjustable.Container ==<br />
{{MudletVersion|4.8}}<br />
<br />
Adjustable Containers are a new "GeyserClass" which act as containers for Geyser elements, but with more flexible and user configurable features. They are referred to as "adjustable" because they can be minimized, loaded, saved, moved, adjusted in size with the mouse pointer, and attached to borders. <br />
<br />
A brief video of [https://www.youtube.com/watch?v=GT2ScizuM48&feature=youtu.be Introduction to Adjustable Containers] is available.<br />
<br />
=== Creating an Adjustable.Container ===<br />
An Adjustable.Container is created just like any other Geyser Object. For example, we might experiment with creating a new Adjustable.Container by running the following line of lua code:<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
</syntaxhighlight><br />
This will create a new Adjustable.Container with the name ''testContainer''. Specifying the adjustable container's name is important for saving. Defining a variable, such as ''testCon'' in our above example, allows functions to be used with the Adjustable.Container.<br />
<br />
Our newly created Adjustable.Container may be used the same way as any other Geyser.Container might. For example, let's put a Geyser.Label in our new testContainer:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
testLabel = Geyser.Label:new({name="myTestLabel", x=0, y=0, height="100%", width="100%", color="green"},testCon)<br />
</syntaxhighlight><br />
<br />
The above code creates a new, green-colored Geyser.Label in the ''testCon'' adjustable.container as shown below:<br />
<br />
[[File:GreenLabelinAdjustableContainer.png]]<br />
<br />
You can also create one for miniconsole:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer = miniconsoleContainer or Adjustable.Container:new({name="miniconsoleContainer"})<br />
myMiniconsole = Geyser.MiniConsole:new({<br />
name="myMiniconsole",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, miniconsoleContainer)<br />
<br />
myMiniconsole:echo("Hello!\n")<br />
</syntaxhighlight><br />
<br />
That will give you:<br />
<br />
[[File:Adjustable container miniconsole.png]]<br />
<br />
=== Key Functions ===<br />
A listing of key functions for the Adjustable.Container module can be found hereː https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html<br />
<br />
To make the Adjustable Container show on screen use the following:<syntaxhighlight lang="lua"><br />
testCon:show() --will cause the Adjustable Container to show if not showing<br />
</syntaxhighlight><br />
<br />
===<div id="valid constraints"> Valid Constraints</div>===<br />
Adjustable Container constraints and their default values can be found at [https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html#Adjustable.Container:new].<br />
<br />
These are in addition to the standard Geyser.Container constraints.<br />
<br />
=== Change Title Text ===<br />
To specify the title text of a new container, use the constraint <code>titleText</code> in the constructor (see [[Manual:Geyser#valid constraints|valid constraints]]).<br />
<br />
To change the title text after a container has already been created, use <code>setTitle</code>. Continuing from the previous example, the title for an existing container named "testCon" might be adjusted in a number of ways: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Title") -- changes the container's title to "Title"<br />
</syntaxhighlight><br />
<br />
A container's title text defaults to the color green, but this can also be adjusted by using <code>setTitle</code>: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Red Title Test","red") -- changes the container's title text to "Red Title Test" and displays the text in the specified color "red".<br />
</syntaxhighlight><br />
<br />
To restore a container's default title text, <code>setTitle</code> is issued without any specified title or color: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle() -- resets the container's title text<br />
</syntaxhighlight><br />
<br />
=== AutoSave and AutoLoad ===<br />
The following Adjustable.Container settings can be saved and loadedː<br />
<br />
<code>x</code>, <code>y</code>, <code>height</code>, <code>width</code>, <code>minimized</code>, <code>locked</code>, <code>lock Style</code>, <code>padding</code>, and <code>hidden</code>.<br />
<br />
These settings will be automatically saved when the Mudlet profile is closed, and automatically loaded when a previous Adjustable.Container is created within the corresponding profile.<br />
<br />
To prevent automatic saving and/or loading of these settings, the <code>autoLoad</code> and <code>autoSave</code> constraints can be included in the constructor. For example, the following code will prevent the settings of the ''testCon2'' Adjustable.Container from being loaded upon creation:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", autoLoad=false})<br />
</syntaxhighlight><br />
<br />
To also prevent the ''testCon2'' Adjustable.Container from automatically saving its settings when the Mudlet profile is closed, the <code>autoSave=false</code> constraint would be added at creation as follows:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCont2 = testCont2 or Adjustable.Container:new({name="testCont2", autoLoad=false, autoSave=false})<br />
</syntaxhighlight><br />
<br />
Automatic saving can also be deactivated after an Adjustable.Container has been created, by invoking <code>testCont:disableAutoSave()</code><br />
<br />
Note that even with autoSave and autoLoad disabled, it is still possible to save and load manually through the right-click menu and/or by using <code>testCont:save()</code> or <code>testCont:load()</code> in a script.<br />
<br />
To save/load all your containers manually at the same time, we use <code>Adjustable.Container:saveAll()</code> and/or <code>Adjustable.Container:loadAll()</code><br />
<br />
=== "All" Functions ===<br />
The following functions affect all Adjustable Containers at the same time.<br />
<br />
{{note}} You must create the Adjustable Containers before these functions will have an effect.<br />
<br />
<code>Adjustable.Container.loadAll()</code> loads all the settings from your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container.saveAll()</code> saves all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:showAll()</code> shows all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:doAll(myfunc)</code> creates a function that will affect all your Adjustable Containers. For example:<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:hide() end) -- hides all your adjustable containers<br />
</syntaxhighlight><br />
<br />
=== Custom Save/Load Directories and Slots ===<br />
{{MudletVersion|4.10}}<br />
<br />
==== Custom Directory ====<br />
If no option set your Adjustable.Container saves/loads its settings in your profile directory.<br />
<br />
It is possible to change the default save/load directory by using for example a different defaultDir as constraint when creating your Adjustable.Container.<br />
<br />
{{note}} This can be especially useful for authors of packages which want to ship their own save files.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = "/home/edru/MyAdjustableContainerSettings/"}) -- noteː the directory will be created if it doesn't exist<br />
</syntaxhighlight><br />
<br />
Example for save files in a package (assuming the packagename is "AdjustableContainerTest" and the settings are saved in "myPersonalAdjSettings"<br />
<syntaxhighlight lang="lua"><br />
local packageName = "AdjustableContainerTest"<br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = string.format("%s/%s/myPersonalAdjSettings/", getMudletHomeDir(), packageName)})<br />
</syntaxhighlight><br />
<br />
==== Custom Slot ====<br />
Another useful addition is to choose a save slot depending on the situation or to reset to a default save state.<br />
<br />
To save to a different slot just add it as parameter when saving.<br />
<br />
For exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːsave("combatSlot")<br />
</syntaxhighlight><br />
<br />
To then load from that slot just useː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːload("combatSlot")<br />
</syntaxhighlight><br />
<br />
{{note}} This also allows package/module authors to choose a "default" save setting to reset to.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
Adjustable.ContainerːsaveAll("default") -- saves the default settings<br />
<br />
-- to reset to default settings then just use<br />
Adjustable.ContainerːloadAll("default") -- loads the default settings<br />
</syntaxhighlight><br />
<br />
This can also be used to change the whole GUI on the fly.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
-- in combat situation use combat settings<br />
Adjustable.ContainerːloadAll("combat") -- loads special combat settings<br />
-- combat is over <br />
Adjustable.ContainerːloadAll("default") --reverts to the default settings<br />
</syntaxhighlight><br />
<br />
==== Delete Save File ====<br />
To delete the save file just useː<br />
<syntaxhighlight lang="lua"><br />
testCont2:deleteSaveFile()<br />
</syntaxhighlight><br />
<br />
===Right-click menu===<br />
Your Adjustable Container has also integrated a right-click menu with the main key functions for easier usability:<br />
<br />
[[File:AdjustableContainerRightClickMenu.png]]<br />
<br />
The right-click menu automatically shows you the possible positions to attach to (top, right, bottom, or left) when it's near one of them. For example, to attach a window to the right of the screen, drag it over to the right - and then the 'Attach to - right' will appear as an option:<br />
<br />
[[File:Adjustable Container - attach to right.png]]<br />
<br />
It also shows the lockstyle selection, which allows you to choose what happens when you press <code>Lock</code>, with 4 lockstyles available by default:<br />
<br />
* standard: this is the default lockstyle, with a small margin on top to keep the right click menu usable.<br />
* light: only hides the min/restore and close labels. Borders and margin are not affected.<br />
* full: the container gets fully locked without any margin left for the right click menu.<br />
* border: keeps the borders of the container visible while locked.<br />
<br />
From Mudlet 4.10+ on it is also possible to change your right-click menu style to dark mode by<br />
<br />
<syntaxhighlight lang="lua"><br />
myAdjustableContainer:changeMenuStyle("dark") -- possible menu styles are "dark" or "light"<br />
</syntaxhighlight><br />
<br />
=== Create a Custom Menu with Custom Items ===<br />
To create a new menu element in your right click menu called "Custom" and add an item to it use:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newCustomItem(name, func)<br />
-- for example<br />
testcontainer:newCustomItem("Hello world", function(self) echo("Hello world\n") self:flash() end)<br />
-- this will write "Hello world" to the main console and flashes your container.<br />
</syntaxhighlight><br />
<br />
=== Add new LockStyles ===<br />
For more advanced users it's possible to add a new Lockstyles by:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newLockStyle(name, func)<br />
-- for example<br />
testcontainer:newLockStyle("NewLockStyle", function(self) self.Inside:move(40, 40) self.Inside:resize(-40,-40) self:setTitle("") end)<br />
</syntaxhighlight><br />
<br />
=== Change Adjustable Container Style ===<br />
Additionally to the standard container constraints Adjustable Containers allow you to change at creation: the internal Label style, the menu style, min/close buttons, the menu text, title text... <br />
<br />
( see [[Manual:Geyser#valid constraints|valid constraints]])<br />
An example of a Adjustable Container with different style.<br />
<syntaxhighlight lang="lua"><br />
testCont =<br />
testCont or<br />
Adjustable.Container:new(<br />
{<br />
name = "TestNewStyleContainer",<br />
adjLabelstyle = "background-color:rgba(220,220,220,100%); border: 5px groove grey;",<br />
buttonstyle=[[<br />
QLabel{ border-radius: 7px; background-color: rgba(140,140,140,100%);}<br />
QLabel::hover{ background-color: rgba(160,160,160,50%);}<br />
]],<br />
buttonFontSize = 10,<br />
buttonsize = 20,<br />
titleText = "My new Style",<br />
titleTxtColor = "black",<br />
padding = 15,<br />
}<br />
)<br />
</syntaxhighlight><br />
This code creates a container which looks like this:<br />
<br />
[[File:NewStyleAdjustableContainer.png|Adjustable Container with different style]]<br />
<br />
<br />
=== Attach your Adjustable Container to a Border ===<br />
The simplest way to attach your container to a border is to move your container near the border you want it to attach and use the <br />
right click menu <code> Attach to:</code><br />
<br />
There is also the function <code> TestCont:attachToBorder("right") -- attach TestCont to the right border </code><br />
<br />
To change the margin between container and border use the constraint <code> attachedMargin </code > or the function <code> TestContːsetBorderMargin(10) -- 10 is the margin in px </code><br />
<br />
{{note}} The border is set in percentages and adjusts with screen-size<br />
<br />
=== Create a moveable border frame ===<br />
{{MudletVersion|4.10}}<br />
<br />
Adjustable Container can be connected to a border and therefore act like a frame.<br />
<br />
This only works if your container is attached to a specific border and the border to connect to has also at least one container attached to it.<br />
Use the function <code>connectToBorder</code><br />
<br />
<syntaxhighlight lang="lua"><br />
TestCont:connectToBorder("left") -- possible borders are "top", "bottom", "right", "left"<br />
</syntaxhighlight><br />
<br />
Minimizing automatically disconnects from a border. Another way is to use the function <code>disconnect</code>.<br />
<br />
{{note}}Connected container are still resizable even if locked.<br />
<br />
If you like to do everything with your right click menu there is the function<br />
<br />
<syntaxhighlight lang="lua"><br />
TestContːaddConnectMenu()<br />
</syntaxhighlight><br />
If you want to add the connect menu items to all Adjustable Containers just<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:addConnectMenu() end)<br />
</syntaxhighlight><br />
<br />
There is also a brief video of how to [https://www.youtube.com/watch?v=Ex-q5zAEfpc connect your Adjustable Container] available.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
GUI = GUI or {}<br />
<br />
GUI.top = Adjustable.Container:new({name = "top", y="0%", height = "10%", autoLoad = false})<br />
GUI.bottom = Adjustable.Container:new({name = "bottom", height = "20%", y = "-20%", autoLoad = false})<br />
GUI.right = Adjustable.Container:new({name = "right", y = "0%", height = "100%", x = "-20%", width = "20%", autoLoad = false})<br />
GUI.left = Adjustable.Container:new({name = "left", x = "0%", y = "0%", height = "100%", width = "20%", autoLoad = false})<br />
<br />
<br />
GUI.top:attachToBorder("top")<br />
GUI.bottom:attachToBorder("bottom")<br />
GUI.left:attachToBorder("left")<br />
GUI.right:attachToBorder("right")<br />
<br />
GUI.top:connectToBorder("left")<br />
GUI.top:connectToBorder("right")<br />
GUI.bottom:connectToBorder("left")<br />
GUI.bottom:connectToBorder("right")<br />
</syntaxhighlight><br />
Here's what the frame will look like:<br />
<br />
[[File:Adjustable_frame.gif]]<br />
<br />
=== Add a scrollable box ===<br />
{{MudletVersion|4.15}}<br />
<br />
To add a scrollable box to an adjustable label, try the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
ScrollContainer = ScrollContainer or Adjustable.Container:new({name = "ScrollContainer"})<br />
ContainerBox = ContainerBox or Geyser.ScrollBox:new({name = "ContainerBox", x = 0, y = 0, height = "100%", width = "100%"}, ScrollContainer)</syntaxhighlight><br />
<br />
[[File:Scrollbox-in-container.png|thumb|center]]<br />
<br />
==Change Container==<br />
{{MudletVersion|4.8}}<br />
<br />
With this command it is possible to change an elements or even a containers location to that from another container.<br />
For example:<br />
<syntaxhighlight lang="lua"><br />
mycontainerone:changeContainer(mycontainertwo)<br />
--puts container one into container two which means container two will be the parent of container one<br />
</syntaxhighlight><br />
It is also possible to change to a container which is not located on the main window:<br />
<syntaxhighlight lang="lua"><br />
myEmco:changeContainer(emco_userwindow)<br />
--puts my tabbed chat Emco into my userwindow<br />
--to put it back to the main window change to a container located on the main window<br />
myEmco:changeContainer(mymainwindow_container)<br />
--or if it the element wasn't in a container use the main Geyser Root container called Geyser<br />
myEmco:changeContainer(Geyser)<br />
</syntaxhighlight><br />
<br />
==Geyser.Mapper==<br />
{{MudletVersion|4.8}}<br />
<br />
It‘s possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation use: (this will create a map window docked at the left corner)<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are "left", "right", "top", "bottom", and "floating".<br><br />
To change the dockPosition after creation use:<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget:setDockPosition("floating")<br />
-- this will change myMapWidget dockPosition to floating <br />
</syntaxhighlight><br />
<br />
= Tutorial =<br />
Note: This tutorial assumes you know how scripts in Mudlet work. If not then you should look at the manual first. Also it only shows how Geyser basically works and explains Geysers special windows. It wont go into detail about the windows that where already in Mudlet.<br />
<br />
=== Hello World ===<br />
Let's start with something simple. A Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_1.png]]<br />
<br />
This code creates a blank Label with a size of 200x50 at a position of 50 points horizontal and vertical from its parent window - which is the main window since we didn't specify any.<br />
<br />
You can manipulate the Label through the normal functions but Geyser.Label:new() returns an object which can be used to manipulate the label directly. So you should store it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local HelloWorld = Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
Then you can, for example print a text on it:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_2.png]]<br />
<br />
You can put a format parameter so that the text is, for example, centered.<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_3.png]]<br />
<br />
The second parameter is the color. We set it to nil which means the labels foreground color will be used.<br />
<br />
The color parameter either accepts a string ("red"), a hex value("#FF0000" or "0xFF0000" or "|cFF0000"), or a decimal value "&lt;255,0,0&gt;"<br />
<br />
Example:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", "red", "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
{{note}} This will automatically set the foreground color, so any echo, without the color parameter set, after that will use the same color.<br />
<br />
You can also set the foreground color with the setFgColor method:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setFgColor("red")<br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
=== Containers ===<br />
<br />
Containers are windows that can contain other windows. Actually, since all other Geyser windows subclass container, every window can do that. But containers do not have any visible content by themselves. <br />
<br />
Let's show that by an example:<br />
<syntaxhighlight lang="lua"><br />
local container = Geyser.Container:new({<br />
name="container",<br />
x=50, y=50,<br />
width=250, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
This will create a container, but if you look at the screen you will see nothing at the positon.<br />
There is a way to make containers visible though:<br />
<syntaxhighlight lang="lua"><br />
container:flash()<br />
</syntaxhighlight><br />
<br />
This will flash the container for a short period of time.<br />
<br />
[[Image:Geyser_Container_1.png]]<br />
<br />
flash() accepts a number as paremeter which defines the time, in seconds, the flash is shown.<br />
<br />
Now, that the container is created, you can add other windows to it. There are 2 ways:<br />
<br />
Directly when creating the window:<br />
<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
},<br />
container)<br />
container_label:echo("This is a label in a container", nil, "c")<br />
</syntaxhighlight><br />
<br />
Later, after the window was created<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
})<br />
container_label:echo("This is a label in a container", nil, "c")<br />
container:add(container_label)<br />
</syntaxhighlight><br />
<br />
Both will lead to the same outcome.<br />
<br />
[[Image:Geyser_Container_2.png]]<br />
<br />
Note that we gave a width and height of "100%" to the constructor of the label. This means that the label will take 100% of the containers width and height. If values are given in percent they will even resize with its parent:<br />
<br />
<syntaxhighlight lang="lua"><br />
container:resize(325, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_3.png]]<br />
<br />
The first parameter is the width, the second the height. If the value is nil the current value is used.<br />
<br />
As said in the "Hello World" tutorial the position is relative to its parent window. That's why we could set both x and y to 0 and it is at the position we wanted - the position of the container.<br />
<br />
When we now move the container the label moves with it:<br />
<syntaxhighlight lang="lua"><br />
container:move(400, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_4.png]]<br />
<br />
The first parameter is the x-, the second the y-position. If the value is nil the current value is used.<br />
<br />
=== VBox and HBox ===<br />
<br />
The VBox and HBox classes are special Containers.<br />
They will automatically align its containing windows vertically or horizontally, respectively, in the order they where added to them.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local HBox = Geyser.HBox:new({<br />
name="HBox",<br />
x=0, y=0,<br />
width=400, height=30,<br />
})<br />
<br />
</syntaxhighlight><br />
<br />
Like containers you won't see them by themselves.<br />
<br />
Adding children works like with containers<br />
<syntaxhighlight lang="lua"><br />
<br />
local label1 = Geyser.Label:new({<br />
name="Label1",<br />
},<br />
HBox)<br />
label1:echo("Label 1", "black", "c")<br />
label1:setColor(255, 0, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_1.png]]<br />
<br />
We didn't set any position or size, but the label gets the same size as the HBox.<br />
<br />
If we add another window:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label2 = Geyser.Label:new({<br />
name="Label2",<br />
},<br />
HBox)<br />
label2:echo("Label 2", "black", "c")<br />
label2:setColor(0, 255, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_2.png]]<br />
<br />
the size will be divided equally between them!<br />
<br />
What if you want a child that takes more or less space than the others?<br />
That's possible too:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label3 = Geyser.Label:new({<br />
name="Label3",<br />
h_stretch_factor=2.0,<br />
},<br />
HBox)<br />
label3:echo("Label 3", nil, "c")<br />
label3:setColor(0, 0, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_3.png]]<br />
<br />
As you can see, Label 3 takes the same space as Label 1 and 2 Together. <br />
That's because we supplied a horizontal stretch factor with "h_stretch_factor=2.0"<br />
<br />
This works also with a vertical stretch factor, just replace "h_stretch_factor" with "v_stretch_factor"<br />
<br />
Now you may have windows that should not be stretched at all.<br />
To accomplish this you have to set the horizontal and/or vertical policy:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local label4 = Geyser.Label:new({<br />
name="Label4",<br />
width="13%",<br />
h_policy=Geyser.Fixed,<br />
},<br />
HBox)<br />
label4:echo("Label 4", "black", "c")<br />
label4:setColor(0, 255, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_4.png]]<br />
<br />
Possible values for the policies are Geyser.Fixed and Geyser.Dynamic (which is the default). They can also be applied to VBox and HBox in exactly the same way.<br />
<br />
Note that, like in the example above, the label will retain relative values (like percent) if used.<br />
<br />
The VBox works like the HBox, only that the child windows are aligned vertically.<br />
<br />
= Walkthroughs =<br />
Here are a few walkthroughs that will show you how to combine Geyser elements to create some simple GUI widgets.<br />
<br />
===Create a Clickable Compass===<br />
[[File: compass.png]]<br />
The following will walk you through the process of creating your own clickable compass using the Geyser framework.<br />
====Setup the image files====<br />
The compass requires a handful of images to work properly. You can find them here: https://www.dropbox.com/sh/53l7xrn4ds35wnq/WpWOziVKmH <br><br />
Download each image and place it in your profile folder. You can find your profile folder with getMudletHomeDir()<br><br />
If you're using Mudlet 2.1+ you can enter '''lua getMudletHomeDir()''' from the command line to return the profile folder path on your computer.<br />
<br />
====Create a new script====<br />
Script Name: '''''compass.resize'''''<br><br />
Registered Event Handlers: '''''sysWindowResizeEvent'''''<p><br />
Every snippet of code will be placed within this script.<br />
====Store the screen size====<br />
We'll want to store the screen size in some local variables so they can be easily referenced to later on.<br />
<syntaxhighlight lang="lua">local mw, mh = getMainWindowSize()</syntaxhighlight><br />
<br />
====Create a global table or namespace====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''compass''''' and everything we make from here on out will be stored within the compass table. We'll also add a few values to it: dirs and ratio. '''''compass.dirs''''' will store each direction while '''''compass.ratio''''' will store the ratio of our screen size so you can 'square up' your compass.<br />
<syntaxhighlight lang="lua">compass = compass or {<br />
dirs = {"nw","n","ne","w","center","e","sw","s","se"},<br />
ratio = mw / mh<br />
}</syntaxhighlight><br />
<br />
====Create the parent label====<br />
[[File: grey.png|thumbnail]]<br />
The 'parent label' refers to the label on the bottom layer. The entire compass will be created within this label. It's container is '''main''' for it's parent is the main window.<br />
<syntaxhighlight lang="lua">compass.back = Geyser.Label:new({<br />
name = "compass.back",<br />
x = "25%",<br />
y = "25%",<br />
width = "10%",<br />
height = "10%",<br />
},main)</syntaxhighlight><br />
<br />
====Set the parent label stylesheet====<br />
[[File: blue.png|thumbnail]]<br />
This will create the blue sphere that makes up most of the compass. The background color is a radial gradient that goes from a deep blue to a brighter shade. The border radius rounds the edges. When the radius is exactly half of the label width it forms a circle. The arrows of the compass actually protrude from the sphere so we give it a margin to suck it in a bit for this effect.<br />
<syntaxhighlight lang="lua">compass.back:setStyleSheet([[<br />
background-color: QRadialGradient(cx:.3,cy:1,radius:1,stop:0 rgb(0,0,50),stop:.5 rgb(0,0,100),stop:1 rgb(0,0,255));<br />
border-radius: ]]..tostring(compass.back:get_width()/2-14)..[[px;<br />
margin: 10px;<br />
]])</syntaxhighlight><br />
<br />
====Create a 3x3 grid====<br />
The compass is split into 9 sections. One for each cardinal direction plus an extra space that sits in the center. This 3x3 grid is created by 3 VBoxes that sit within a single HBox (or vice versa but I flipped a coin and this is what it gave me).<br><br />
So first off, we create the HBox. It will be the same size as its parent, ''compass.back''.<br />
<syntaxhighlight lang="lua"> compass.box = Geyser.HBox:new({<br />
name = "compass.box",<br />
x = 0,<br />
y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},compass.back)</syntaxhighlight><br />
Next, we create our 3 VBoxes. You don't need to specify position or size because these are placed within ''compass.box'', an HBox.<br />
<syntaxhighlight lang="lua"> compass.row1 = Geyser.VBox:new({<br />
name = "compass.row1",<br />
},compass.box)<br />
compass.row2 = Geyser.VBox:new({<br />
name = "compass.row2",<br />
},compass.box)<br />
compass.row3 = Geyser.VBox:new({<br />
name = "compass.row3",<br />
},compass.box)</syntaxhighlight><br />
Finally, we add our 9 labels. Take note that they are split up into even groups of 3. Each group is placed into a different ''compass.row#''<br />
<syntaxhighlight lang="lua"> compass.nw = Geyser.Label:new({<br />
name = "compass.nw",<br />
},compass.row1)<br />
<br />
compass.w = Geyser.Label:new({<br />
name = "compass.w",<br />
},compass.row1)<br />
<br />
compass.sw = Geyser.Label:new({<br />
name = "compass.sw",<br />
},compass.row1)<br />
<br />
compass.n = Geyser.Label:new({<br />
name = "compass.n",<br />
},compass.row2)<br />
<br />
compass.center = Geyser.Label:new({<br />
name = "compass.center",<br />
},compass.row2)<br />
<br />
compass.s = Geyser.Label:new({<br />
name = "compass.s",<br />
},compass.row2)<br />
<br />
compass.ne = Geyser.Label:new({<br />
name = "compass.ne",<br />
},compass.row3)<br />
<br />
compass.e = Geyser.Label:new({<br />
name = "compass.e",<br />
},compass.row3)<br />
<br />
compass.se = Geyser.Label:new({<br />
name = "compass.se",<br />
},compass.row3)</syntaxhighlight><br />
====Create a callback function====<br />
We'll want our compass to head in the direction of the arrow we're clicking. This is where we specify so. When the arrow is clicked, this function will be ran with the arrow direction as the argument.<br />
<syntaxhighlight lang="lua">function compass.click(name)<br />
send(name)<br />
end</syntaxhighlight><br />
====Create the hover functions====<br />
We want our arrows to turn yellow when we hover over them. We do so by simply resetting the label's stylesheet and changing the border image. Don't forget to include the margin as we still want that.<br />
<syntaxhighlight lang="lua">function compass.onEnter(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[hover.png");<br />
margin: 5px;<br />
]])<br />
end<br />
<br />
function compass.onLeave(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[.png");<br />
margin: 5px;<br />
]])<br />
end</syntaxhighlight><br />
====Set the stylesheets in the grid====<br />
[[File: Sample.png|thumb]]<br />
Each of the 9 labels need an image of an arrow. Rather than setting each individually, we'll iterate over the ''compass.dirs'' table we made awhile back and add the respective image to each. The names of images are a reflection of the ''compass.dirs'' table. This keeps it consistent and easy to refer to. During the iteration, the callback, setLabelOnEnter and setLabelOnLeave are also set for each label.<br />
<syntaxhighlight lang="lua">for k,v in pairs(compass.dirs) do<br />
compass[v]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..v..[[.png");<br />
margin: 5px;<br />
]])<br />
compass[v]:setClickCallback("compass.click",v)<br />
setLabelOnEnter("compass."..v,"compass.onEnter",v)<br />
setLabelOnLeave("compass."..v,"compass.onLeave",v)<br />
end</syntaxhighlight><br />
<br />
====Resize the compass into a square====<br />
[[File: final.png|thumb]]<br />
Most screen size ratios aren't a perfect 1:1. This will cause a 10% x 10% label to be far from square. By setting our height (the smaller of the two numbers) to our width, we can resize our compass to a near perfect square. This function is also the name of our script because we want it to run each time sysWindowResizeEvent is raised.<br />
<syntaxhighlight lang="lua">function compass.resize()<br />
compass.back:resize(compass.back.width, compass.back:get_width())<br />
end<br />
<br />
compass.resize()</syntaxhighlight><br />
<br />
===Create a Tabbed Window===<br />
[[File: tabwindow.png]]<br />
The following will walk you through the process of creating your own tabbed window using the Geyser framework.<br />
<br />
====Create a new script====<br />
Script Name: '''''Tabbed Window'''''<br><br />
Every snippet of code will be placed within this script.<br />
====Create a global table====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''menu''''' and everything we make from here on out will be stored within the menu table. We'll also add a few values to it: tabs, color1, color2, width, height and current. <br><br />
''''tabs'''' will be a table that stores all our tab names. If we want our tabs to have different names, we alter this table.<br><br />
''''color1'''' and ''''color2'''' will store the colors of our tabbed window. If we want to change the color of our tabbed window, we alter these values.<br><br />
''''width'''' and ''''height'''' will store the size of our tabbed window. If we want to change the size of the tabbed window, we alter these values.<br><br />
''''current'''' keeps track of which tab is selected. We will set this to the first tab in the table by default. We do this outside the initial table creation so we can easily access menu.tabs<br><br />
<syntaxhighlight lang="lua">menu = menu or {<br />
tabs = {"Tab1","Tab2","Tab3","Tab4"},<br />
color1 = "rgb(0,0,70)",<br />
color2 = "rgb(0,0,50)",<br />
width = "20%",<br />
height = "40%",<br />
}<br />
menu.current = menu.current or menu.tabs[1]</syntaxhighlight><br />
<br />
====Create the main container====<br />
Our tabbed window will need a container. This will be the bottom layer. Containers are invisible so no need to set a stylesheet.<br />
<syntaxhighlight lang="lua">menu.container = Geyser.Container:new({<br />
name = "menu.back",<br />
x = "50%", y = "25%",<br />
width = menu.width,<br />
height = menu.height,<br />
},main)</syntaxhighlight><br />
====Create an HBox====<br />
All of our tabs will be evenly spaced. So we'll create an HBox to sit at the top of our container.<br />
<syntaxhighlight lang="lua">menu.header = Geyser.HBox:new({<br />
name = "menu.header",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "10%",<br />
},menu.container)</syntaxhighlight><br />
====Create a label====<br />
This label will serve as a container for each window. It sits right underneath the HBox we just created for the tabs.<br />
<syntaxhighlight lang="lua">menu.footer = Geyser.Label:new({<br />
name = "menu.footer",<br />
x = 0, y = "10%",<br />
width = "100%",<br />
height = "90%",<br />
},menu.container)</syntaxhighlight><br />
We don't want this to be a big grey box at startup, so we'll set the stylesheet to appear like the rest of the windows.<br />
<syntaxhighlight lang="lua"><br />
menu.footer:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])</syntaxhighlight><br />
Each window actually has two labels. One for the light blue background, and another for the dark blue center. This will create that dark blue center.<br />
<syntaxhighlight lang="lua">menu.center = Geyser.Label:new({<br />
name = "menu.center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
menu.center:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])</syntaxhighlight><br />
====Add your tabs and their windows====<br />
Now we'll want to add our tabs and windows. We do this in a single for loop of the ''''menu.tabs'''' table since it holds all our tab names.<br />
<syntaxhighlight lang="lua">for k,v in pairs(menu.tabs) do<br />
</syntaxhighlight><br />
This will create the tabs. Each tab will be named: menu.<tabname>tab<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"] = Geyser.Label:new({<br />
name = "menu."..v.."tab",<br />
},menu.header)<br />
</syntaxhighlight><br />
Here is where we set the tab stylesheet. Each tab has a rounded top, so we set the border-radius of the top-left and top-right to 10px. Each tab has a small space for separation so we give the right and left sides a tiny margin of 1px.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-top-left-radius: 10px;<br />
border-top-right-radius: 10px;<br />
margin-right: 1px;<br />
margin-left: 1px;<br />
]])<br />
</syntaxhighlight><br />
This will display the name of each tab on the tab.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:echo("<center>"..v)<br />
</syntaxhighlight><br />
We need our tabs to do stuff when clicked, so we'll assign it a callback function, '''''menu.click''''', which we'll create later on. Our tab name is the argument.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setClickCallback("menu.click",v)<br />
</syntaxhighlight><br />
Now we create the windows that appear when each tab is clicked. Each window has two labels, one atop the other. The first, which we'll create here, has rounded edges on its bottom.<br />
<syntaxhighlight lang="lua"><br />
menu[v] = Geyser.Label:new({<br />
name = "menu."..v,<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
<br />
menu[v]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
The second label serves as the window's center and has rounded edges on all sides. And a margin of 5px from it's parent, the label we just created. When adding stuff to your windows, this is the label you'll want to use. '''''menu.<tabname>center'''''<br />
<syntaxhighlight lang="lua"><br />
menu[v.."center"] = Geyser.Label:new({<br />
name = "menu."..v.."center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu[v])<br />
</syntaxhighlight><syntaxhighlight lang="lua"><br />
menu[v.."center"]:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])<br />
</syntaxhighlight><br />
Finally, we hide all the windows and end the for loop.<br />
<syntaxhighlight lang="lua"><br />
menu[v]:hide()<br />
end</syntaxhighlight><br />
====Create a callback function====<br />
The last step is to create our callback function for when a tab is clicked. This will hide that tab that is stored in '''''menu.current''''', set menu.current to the clicked tab, and then show the menu.current tab.<br />
<syntaxhighlight lang="lua">function menu.click(tab)<br />
menu[menu.current]:hide()<br />
menu.current = tab<br />
menu[menu.current]:show()<br />
end</syntaxhighlight><br />
====Adding content to your windows====<br />
Add content to '''menu.<tab name>center'''<br />
So if we wanted to display our gold in a window we could:<syntaxhighlight lang="lua">menu.Tab1center:echo(myGold)</syntaxhighlight><br />
If we wanted to add a map to a window we could:<br />
<syntaxhighlight lang="lua">myMap = Geyser.Mapper:new({<br />
name = "myMap",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.Tab2center)</syntaxhighlight><br />
<br />
===Create a Window with a resize label===<br />
<br />
Previous tutorial is now done much simpler [[Manual:Geyser#Adjustable.Container|Adjustable containers]], have a look at those instead.<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Geyser&diff=20331Manual:Geyser2023-03-02T07:35:07Z<p>Kebap: Use Template:MudletVersion</p>
<hr />
<div><br><br />
{{TOC right}}<br />
<br />
= Introduction =<br />
<br />
The Geyser Layout Manager is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
=== Motivation ===<br />
<br />
Mudlet makes the creation of label, miniconsoles and gauges a quick and easy thing. Mudlet provides a nice signal when window resize events happen. To help with complex window management, Geyser steps in.<br />
<br />
=== Main Geyser Features ===<br />
<br />
Geyser is based on traditional GUI concepts and should feel similar to using Java's Swing. The biggest difference is in how positions are specified.<br />
<br />
* All window positions are specified relative to their container - nothing new there. However, window positions can also take on percentages and negative pixel and character values. For instance, a window could be constrained to have a height of 50% of its container and a width such that the window's right edge is always 20 characters from its container's right edge. See examples below and the demos/tests that come with Geyser.<br />
* All windows under Geyser control are automatically resized as necessary when the main Mudlet window is resized. Once you create a window and assign it to a container, you never have to worry about positioning it again. Nonetheless, it's very easy to shift the container that a window is in, maintaining its constraints so that it resizes as needed according to the dimensions of the new container.<br />
* Due to the container hierarchy, hiding a container window automatically hides all its contained windows too. The same for show. With clever construction and labels with callbacks, this lets one make complex GUI elements that are minimizable or maximizable or ...<br />
* However, there is always some overhead for automation systems and Geyser is no exception. Fortunately, most of the overhead is during window creation and resize events - not things that happen frequently.<br />
<br />
=== Getting pictures for your stuff ===<br />
You can find good, freely-available assets for your UI here:<br />
* [https://kenney.nl/assets?q=2d kenney.nl]<br />
* [https://opengameart.org/ opengameart.org]<br />
* [https://game-icons.net/ game-icons.net]<br />
<br />
=== Constraints format ===<br />
<br />
Geyser position constraints are a string composed of a number and a format type. For example, "10px" means 10 pixels, either pixels from the origin (e.g. x or y) or a value for the width or height. A negative number indicates distance from a container's right or bottom border depending on whether is a constraint for x/width or y/height, respectively. Percentages for width and height are in terms of the container's dimensions and negative values are converted to the equivalent positive value. A 100% width subwindow with an x-coordinate of 10 will have part of itself displayed outside the confines of its container. There is no hard limit on maximum window size, just as with regular Mudlet windows. If a number, n, is passed as a constraint instead of a string, it is assumed to be equivalent to "npx". Any Lua table that contains entries for x, y, width and height in the proper format can be used for Geyser constructors and setting constraints. Just like in Mudlet, 0,0 coordinates mean the top-left corner.<br />
<br />
The following is a valid example for coordinates of a Geyser object:<br />
<br />
<syntaxhighlight lang="lua"><br />
{x = "20px", y = "-10c", width = "40%", height = 30}<br />
</syntaxhighlight><br />
<br />
=== Math in Geyser ===<br />
You can also use math in your Geyser constraints just to line things up just right! Want to have a label occupy full height but not the first 30 pixels? You can:<br />
<br />
<syntaxhighlight lang="lua"><br />
footer = Geyser.Label:new({<br />
name = "footer",<br />
x = 0, y = 30,<br />
height = "100%-30px",<br />
}, main_window)<br />
</syntaxhighlight><br />
<br />
= Geyser elements =<br />
The purpose of this document is to go through every Geyser element and provide practical examples on how they are used. Read it from top to bottom, preferably doing all of the examples to understand how they work!<br />
<br />
== Technical manual ==<br />
<br />
See https://www.mudlet.org/geyser/files/index.html for a brief and technical overview of all Geyser elements and their functions.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html Geyser.Container]==<br />
An invisible, organizing object in Geyser - use it to divide your screen and position elements accordingly. '''[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html See here]''' for all of the functions that are available to you to use.<br />
<br />
A container is also the base class - which means that everything (labels, miniconsoles and gauges) can use its functions, since everything else is at heart a container.<br />
<br />
=== Creating a container ===<br />
To get started with a container, here's an example that'll create a 200px border on the left side of Mudlet for you, and make a container cover all of it - so you can place other visual elements inside it:<br />
<br />
<syntaxhighlight lang="lua"><br />
setBorderLeft(200)<br />
left_container = Geyser.Container:new({<br />
name = "left_container", -- give it a unique name here<br />
x=0, y=0, -- have it start at the top-left corner of mudlet<br />
width = 200, height="100%", -- with a width of 200, and a height of the full screen, hence 100%<br />
})<br />
</syntaxhighlight><br />
<br />
Right away, you'll see space appear on the left side. It'll be black, as the container is an invisible unit by itself. You can make sure it's there by making it flash by doing this from the input line:<br />
<br />
<syntaxhighlight lang="lua">lua left_container:flash()</syntaxhighlight><br />
<br />
The command will cause your container to flash for a moment for you, revealing itself.<br />
<br />
{{Note}} If you hide a container and create new Geyser elements within it, they'll be shown automatically for you.<br />
<br />
=== Container within a container ===<br />
You can place containers within other containers by specifying which "parent" the new container should have when you create one. Given our [[#Creating a container|previous example]], you can split the left side into two halves like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
left_container_top = Geyser.Container:new({<br />
name = "left_container_top",<br />
x=0, y=0, -- this container occupies the top, so it starts top-left as well<br />
width = "100%", height="50%", -- but only uses up half of the height<br />
}, left_container) -- this is the important bit - it says that left_container_top should be inside left_container<br />
<br />
left_container_bottom = Geyser.Container:new({<br />
name = "left_container_bottom",<br />
x=0, y="50%", -- this container starts halfway down the first one<br />
width = "100%", height="50%", -- and has the same half height of the original container<br />
}, left_container) <br />
</syntaxhighlight><br />
<br />
=== Aligning relative to bottom or right sides ===<br />
The aligning point within Mudlet is the top-left corner, and it's the same for the elements they are aligned - the position you specify is used by the top-left corner of the element.<br />
<br />
Using Geyser, you can align to the opposite side as well, using the coordinates in negatives, while keeping the dimensions of the object in mind. For example, if you want to align a box that's 20px wide on the usual left side, you'd give it a width of 20 and an x value of 0. If you'd like to align it on the right side, then you'd give it an x value of -20. The box will spawn 20px away from the right side and "grow" to the right by 20px.<br />
<br />
<syntaxhighlight lang="lua"><br />
right_container = Geyser.Container:new({<br />
name = "right_container",<br />
x="-20%", y=0, -- makes the container start 20% of the screen away from the right side<br />
width = "20%", height="50%", -- filling it up until the end<br />
}) <br />
</syntaxhighlight><br />
<br />
Do make sure to account for the scrollbar, as Mudlet UI elements can overlap it. You can also move the scrollbar with [[Manual:UI_Functions#setBorderRight|setBorderRight()]].<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html Geyser.Label]==<br />
Labels allow you to use pictures in your interface, as well as nicely-formatted text - see docs for label [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html functions].<br />
<br />
=== Basic label ===<br />
<br />
Here's an example to get you started with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
</syntaxhighlight><br />
<br />
This labels '''x''' coordinate is specified as 50% - and because it's not attached to any container, this implies that the window will start halfway at the main window. You can tell it's not attached to a container because there's nothing in between the last ''}'' and '')'', the place where the container goes.<br />
<br />
The '''y''' coordinate is 0 - which means that the label will start at the top of the screen. With the width being 50%, the label will occupy 50% of the screen - and since it starts at the halfway point, it means it'll occupy the entire right side. A height of 100% means that it'll stretch from the top to the full bottom.<br />
<br />
Here's what that'll look like:<br />
<br />
[[File:Simple-label.png|center|600px]]<br />
<br />
<br />
Playing around with the starting location and dimensions, we can also place it in the center of the screen with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
})<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
[[File:Simple_label_centered.png|center|600px]]<br />
<br />
To change the message on a label, you can use the ''mylabel:echo()'' function, where ''mylabel'' is the name of the label you gave it:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("hello!")<br />
</syntaxhighlight><br />
<br />
To get rid of the label, use the '':hide()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:hide()<br />
</syntaxhighlight><br />
<br />
=== Coloring text ===<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black", -- default text colour<br />
color = "SeaGreen" -- default label background<br />
})<br />
<br />
-- You can also change colour of text on demand with:<br />
testlabel:echo[[<p style="color:blue;">You can change the text color of a whole sentence or paragraph...</p><p>...or you can change the text color of one <span style="color:green;">word</span> or even a single l<span style="color:red;">e</span>tter.</p>]]<br />
</syntaxhighlight><br />
<br />
=== Setting the font size ===<br />
<br />
To set a different font size for your Label, use the ''setFontSize()'' method. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel:setFontSize(14)<br />
</syntaxhighlight><br />
<br />
The font size is set in Pt, so anything above 30 will likely be too large to be useful.<br />
<br />
=== Label inside a container ===<br />
<br />
Once you've got your containers and mastered the basic labels, you can drop labels into your nicely-organized containers. Doing so is similar to nesting containers:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
}, left_container_bottom) -- this is where we tell it what container to go into<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
That label is exactly the same as the one above that goes across the screen, except it's in our bottom-left container - so it looks appropriately different:<br />
<br />
[[File:Label in a container.png|center]]<br />
<br />
=== Image on a label ===<br />
One of the more amazing things labels allow you to do is put pictures anywhere on your Mudlet screen, that blend in very well. To do so, once the label is created, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setBackgroundImage setBackgroundImage()] function with the exact path to the image ([[File:Skullface.png]]):<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 0, y = "-14px",<br />
width = "16px", height = "14px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/skullface.png]]) -- update location to actual image location on your computer<br />
</syntaxhighlight><br />
<br />
This'll plop the picture to the bottom-left of your screen. To make the picture show, download the skullface picture above - save it to your desktop, and adjust the location of the image within [[]]'s to what it is on your computer. For example, if you saved this on your Windows 7 desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[C:/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
(yes, that's / and not \ - \ has been known not to work)<br />
<br />
If you saved this on your Mac desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
If you saved this on your Ubuntu desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/home/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
Using this basic building block, you can work up to making yourself a UI!<br />
<br />
=== Stretching an image on a label ===<br />
If you'd like your image not to keep its original size, but instead use up the available space of the label - you can use the [http://doc.qt.io/qt-5/stylesheet-reference.html#border-image border-image] stylesheet property to do so.<br />
<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- change the location to your picture<br />
-- on windows, use / to separate folders still, not \<br />
label:setStyleSheet[[<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);<br />
]]<br />
</syntaxhighlight><br />
<br />
{{note}} If you're on a Mudlet earlier than 3.15 and are having difficulty with the image coming up, it may be because of strange differences between Qt's CSS engine which does not affect mudlet's Lua. You may want to try appending :gsub("\\","/") to your string including getMudletHomeDir() (e.g. <code>getMudletHomeDir():gsub("\\","/")</code>). No longer necessary after Mudlet 3.15.<br />
<br />
=== Aligning an image within a label ===<br />
You can use background-image in combination with background-position to align an image within a label (if, say, the image is much smaller than the label).<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this will set and align an image top-right of the label<br />
if stunning then<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-ok.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
else<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-no.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
end<br />
</syntaxhighlight><br />
<br />
=== Showing / hiding a label ===<br />
You can show and hide labels, as you can any container, miniconsole or a gauge in Geyser with [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:show Geyser.Container:show()] and [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:hide Geyser.Container:hide()]. Remember that since labels are a type of a container, all container functions work on them.<br />
<br />
Hiding a label will allow you to click through on what is below the label, as well as free up the visual space for something else.<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- hide the label with:<br />
testlabel:hide()<br />
<br />
-- show the label with:<br />
testlabel:show()<br />
</syntaxhighlight><br />
<br />
=== Clickable images ===<br />
Tacking onto the fact that you can plop images anywhere on your Mudlet screen now, you can also make them react to your clicks. You can do so with the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setClickCallback setClickCallback()] function - by giving it a function to call when your label is clicked, you'll make it react.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "-215px", y = "0px",<br />
width = "200px", height = "200px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/qubodup-opengameart-cc0-200px-missile_icon.png]]) -- update location to actual image location on your computer<br />
picture_label:setClickCallback("on_bomb_press")<br />
<br />
function on_bomb_press()<br />
send("say BOOM!")<br />
end<br />
</syntaxhighlight><br />
<br />
That's it! Pressing on the image will make the ''on_bomb_press()'' function go off, which will do its code of ''send("say BOOM!")''. Download the picture for use [http://opengameart.org/content/missile-rts-icon here].<br />
<br />
[[File:Clickable_image.png|500px|center]]<br />
<br />
=== Styling labels ===<br />
Besides putting text or images on labels, you can also style them using Qt's stylesheets feature. Doing so allows you to create various graphics that make the label look more appealing:<br />
<br />
[[File:Label_styling_examples.png|center]]<br />
<br />
To set a stylesheet on a label, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setStyleSheet Geyser.Label:setStyleSheet()] function on your label, describing the stylesheet you'd like to give it. A stylesheet consists of properties you set - for example the background color, borders, padding, and so forth. You describe properties in the following format: ''property name''''':'''''values''''';'''. See here for a [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties list of all supported properties]. For example, to make your labels background be yellow, you'd use the background-color property:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "mylabel",<br />
x = "50%", y = "50%",<br />
width = 200, height = 100<br />
})<br />
<br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet.png|center]]<br />
<br />
Which is nice, but not particularly impressive.<br />
<br />
Scrolling down the list of properties, you'll come along a border one. Plopping it into our stylesheet nets the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
border: 5px solid white;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border.png|center]]<br />
<br />
Which gives a border!<br />
<br />
Fiddling with it some more and applying new properties we find on that page, we get a rounded border on our label:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: grey;<br />
border-width: 15px;<br />
border-style: solid;<br />
border-color: green;<br />
border-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border_radius.png|center]]<br />
<br />
Which'll conclude our exploration for now. Try out all of the other possible options available there - there's loads, from [http://doc.qt.io/qt-5/stylesheet-reference.html#border-style funky borders], to tiling images and fancy color combinations using gradients.<br />
<br />
You should also check out [[Manual:Geyser#Geyser.StyleSheet|Geyser.StyleSheet]] for a way to manage your stylesheets with adjustable properties and the ability to take defaults from another stylesheet.<br />
<br />
=== Adding a tooltip to a label ===<br />
<br />
Since Mudlet 4.6, you can now add a tooltip to labels and gauges. You can start by making a simple label and echoing some text to it:<br />
<br />
<syntaxhighlight lang="lua"><br />
testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = "50%",<br />
y = "50%",<br />
height = "25%",<br />
width = "25%",<br />
})<br />
testLabel:echo("This is on the label!")<br />
testLabel:setAlignment("center")<br />
-- sets the tooltip text<br />
testLabel:setToolTip("This is the tooltip", "10")<br />
<br />
<br />
-- optionally - you can customise the tooltip, too!<br />
testLabel:setStyleSheet("QToolTip{background: yellow; color: blue; border:none;}")<br />
</syntaxhighlight><br />
<br />
Without tooltip<br />
[[File:TestLabelForTooltips.png|thumb|center]]<br />
<br />
With tooltip<br />
<br />
[[File:LabelTooltip.png|thumb|center]]<br />
<br />
=== Avoid stylesheet inheritance by tooltip ===<br />
<br />
{{note}} If you set a new stylesheet for a label and with that a background image it is possible that through inheritance the tooltip also has this stylesheet image.<br />
<br />
To avoid this specify that the stylesheet is meant for the Label by using QLabel{...} in your Label stylesheet for exampleː<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- by using QLabel{...} the stylesheet won't be given to the tooltip as well<br />
label:setStyleSheet[[<br />
QLabel{<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);}<br />
]]<br />
</syntaxhighlight><br />
<br />
<br />
=== Aligning text/images inside a label ===<br />
By default, text is [http://qt-project.org/doc/qt-5/qlabel.html#alignment-prop centered vertically and left aligned] in a label. To align it to a specific side, use the stylesheets we learnt about earlier with the qproperty-alignment:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- specify one property this way:<br />
mylabel:setStyleSheet([[qproperty-alignment: 'AlignTop';]])<br />
<br />
-- or multiple ones separated with a |, for example this will align text to top-left:<br />
mylabel:setStyleSheet([[<br />
qproperty-alignment: 'AlignLeft | AlignTop';<br />
]])<br />
<br />
mylabel:echo("hi!")<br />
</syntaxhighlight><br />
<br />
[[File:Text_aligned.png|center]]<br />
<br />
=== Enabling wordwrap in a label ===<br />
If you need to enable word wrapping in a label (which by default is off), add the following line to the labels stylesheet:<br />
<br />
qproperty-wordWrap: true;<br />
<br />
As an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
If you'd like to set multiple properties, set them all at once - not via multiple :setStyleSheet() calls:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background: red;<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Adding a hover effect to a label ===<br />
The labels support adding stylesheets for specific cases, such as when a mouse is [http://doc.qt.io/qt-5/stylesheet-reference.html#hover-ps hovering] over them. To make this work, you provide CSS for when the label is in its usual state, and for when it is hovered over:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this example will add a border to the label when it is hovered over<br />
mylabell:setStyleSheet([[<br />
QLabel{ border-radius: 4px; }<br />
QLabel::hover{<br />
background-color: rgba(0,0,0,0%);<br />
border: 4px double green;<br />
border-radius: 4px;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Checkboxes ===<br />
Combining the fact that you can click on a label with an image to do something with the fact that you can change pictures on a label at will, you can make an image that changes itself when you click on it.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "50%", y = "50%",<br />
width = "21px", height = "19px"<br />
})<br />
-- a little trick we do to make the background of the label be transparent<br />
picture_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
picture_label:setClickCallback("on_checkbox_press")<br />
<br />
function on_checkbox_press()<br />
if checkbox_ticked then<br />
checkbox_ticked = false<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_unticked.png]])<br />
echo("Checkbox unticked.\n")<br />
else<br />
checkbox_ticked = true<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
echo("Checkbox TICKED!\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
The ''on_checkbox_press()'' function this time keeps the track of the checkbox with the ''checkbox_ticked'' variable and sets the image appropriately. You can download the ticked ([[File:Checkbox_ticked.png]]) and unticked images ([[File:Checkbox_unticked.png]]) or the [http://wiki.mudlet.org/images/6/6d/Checkbox.mpackage whole package] altogether.<br />
<br />
[[File:Checkbox_demo.png|500px|center]]<br />
<br />
=== Animated labels with sprites ===<br />
You can animate sprite packs using timers. Assuming you have the sprite pack downloaded, try this example:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 10, y = "-24px",<br />
width = "16px", height = "14px",<br />
})<br />
<br />
santa_counter = nil<br />
<br />
function animate_santa()<br />
santa_counter = (santa_counter or 0) + 1<br />
if santa_counter > 8 then santa_counter = 1 end<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/santa/santa]]..santa_counter..[[.png]]) -- update location to actual image location on your computer<br />
santa_timer = tempTimer(.16, animate_santa)<br />
end<br />
<br />
animate_santa()<br />
</syntaxhighlight><br />
<br />
The completed package is available [http://wiki.mudlet.org/images/6/6b/Dancing-santa.mpackage here], install it and do '''start/end animation''' to watch.<br />
<br />
=== Inserting extra spaces and newlines ===<br />
Echoing text into Mudlet and Geyser labels is different from miniconsoles and the main window, due to their nature. One of the differences is that extra spaces in a label, by default, get compressed down to one. '''To add extra spaces in a label''', replace extra spaces with '''&amp;nbsp;''' or by wrapping your text with them inside '''<nowiki><pre>my text here</pre></nowiki>'''.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this won't work, it'll show as one space:<br />
mylabel:echo("You -> point")<br />
<br />
-- but this would, because it replaces all spaces with &nbsp before echoing<br />
mylabel:echo(string.gsub("You -> point", " ", "&nbsp;"))<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- here is another way to go about this - and it additionally makes the font be monospaced:<br />
mylabel:echo("<pre>You -> point</pre>")<br />
</syntaxhighlight><br />
<br />
'''To add a new line in a label''' (aka linebreak), use '''<nowiki><br></nowiki>''' (instead of ''\n'' as you are used to in an echo).<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("These<br>words<br>are<br>split")<br />
</syntaxhighlight><br />
<br />
=== Transparent labels ===<br />
One of the possible ways of achieving transparency on a label is to add <code>background-color: rgba(0,0,0,0%);</code> to its stylesheet. Here's an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
my_transparent_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
</syntaxhighlight><br />
<br />
Want to get transparency in a miniconsole? You can [[Manual:Geyser#Change_your_miniconsole_background_image|do that as well]].<br />
<br />
=== Custom mouse cursor ===<br />
You can change the shape of the cursor when it's over your label with:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCursor("Forbidden") -- will change your mouse cursor to "forbidden" (as in "can't do this") cursor<br />
</syntaxhighlight><br />
Possible cursor shapes are [[CursorShapes| available here]], and you can import this [[Media:Cursor grid.zip|demo package]] to try them all out.<br />
<br />
It is also possible to change the mouse cursor to a custom made cursor by:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCustomCursor(getMudletHomeDir().."/custom_cursor.png")<br />
</syntaxhighlight><br />
It is recommended that the custom cursor is a png with size of 32x32 to be supported on all systems.<br />
<br />
[[File:Changecursoroverlabel.gif]]<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
=== Flyout Labels ===<br />
<br />
Flyout labels allow you to create 'dropdown' or 'flyout' menus - menus that reveal more items once you hover your mouse over them. To create flyout labels:<br />
# add <code>nestable=true</code> (left click to open menu) or <code>nestflyout=true</code> (mouse hover to open menu) to your main label.<br />
# use [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] on your main label to add flyout labels to it.<br />
## [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] uses the same arguments as when creating a new label but also takes the '''layoutDir''' option to specify in which direction and axis should the labels align, where 2 letters combine into the option: first letter R for right, L for left, T for top, B for bottom, followed by the orientation: V for vertical or H for horizontal. So options are: <code>layoutDir="RV"</code>, <code>layoutDir="RH"</code>, <code>layoutDir="LV"</code>, <code>layoutDir="LH"</code>, and so on.<br />
# optionally, add <code>flyOut=true</code> to your flyout labels to make the labels dissapear when the mouse isn't hovering over them anymore.<br />
<br />
Note that the main flyout label cannot go into a container and needs to be on its own.<br />
<br />
{{note}} Requires Mudlet 3.0.<br />
<br />
==== Demo ====<br />
Here's an example that follows the steps above:<br />
<br />
<syntaxhighlight lang="lua"><br />
label0 = Geyser.Label:new({name="label0", <br />
x="50%",y="50%",height=50,width=300,nestable=true, <br />
message="<center>Clicky clicky</center>"})<br />
<br />
-- and add 3 labels to it with RV layout - so Right of the label, aligned Vertically<br />
label1 = label0:addChild({name="label1",height=30,width=70, layoutDir="RV", flyOut=true, message="label one"})<br />
label1:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label2 = label0:addChild({name="label2",height=30,width=70, layoutDir="RV", flyOut=true, message="label two"}) <br />
label2:setStyleSheet([[background-color: green; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label3 = label0:addChild({name="label3",height=30,width=70, layoutDir="RV", flyOut=true, message="label three"})<br />
label3:setStyleSheet([[background-color: red; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
</syntaxhighlight><br />
<br />
A more thorough example. Try it out to see what you can create with flyout labels:<br />
<syntaxhighlight lang="lua"><br />
-- create a label with a nestable=true property to say that it can nest labels<br />
mainlabel = Geyser.Label:new({name="testa", x=400,y=50,height=50,width=300,nestflyout=true, message="<center>HOVER HERE TO SEE FLY-OUT LABELS!</center>"})<br />
<br />
-- create 15 labels and store them in a table <br />
table_for_flyout_labels = {}<br />
for i=1,15 do<br />
-- options to layoutDir are the direction the window should go (R for right, L for left, T for top, B for bottom), followed by how the nested labels should be oriented (V for vertical or H for horizontal). So "BH" here means it'll go on the bottom of the label, while expanding horizontally<br />
table_for_flyout_labels[i] = mainlabel:addChild({name="test"..tostring(i),height=30,width=70, layoutDir="BH", flyOut=true, message="test"..tostring(i)})<br />
<br />
table_for_flyout_labels[i]:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px;]])<br />
end<br />
<br />
-- make the test5 label look a bit special as it has got a surprise<br />
table_for_flyout_labels[5]:echo("Hover here")<br />
<br />
-- add even more nested labels to the 5th label!<br />
even_more_flyout_labels = {}<br />
for i=1,60 do<br />
-- here, the layout will be to the right of it, while expanding vertically<br />
even_more_flyout_labels[i]=table_for_flyout_labels[5]:addChild({name="hover label "..tostring(i),height=30,width=100, layoutDir="RV", flyOut=true, message="label "..tostring(i)})<br />
even_more_flyout_labels[i]:setClickCallback("testFunc", even_more_flyout_labels[i].name)<br />
even_more_flyout_labels[i]:setStyleSheet([[background-color: grey; border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]])<br />
end<br />
<br />
function testFunc(name)<br />
display(name)<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look something like this: <br />
<br />
[[File:Flyout_labels_demo.png|150px]]<br />
<br />
==== Demo of layouts ====<br />
Here's another demo that explains all of the layout styles quite well:<br />
<syntaxhighlight lang="lua"><br />
local directions = {"R", "L", "T", "B"}<br />
local orientations = {"V", "H"}<br />
local mappings = {R = "right", L = "left", T = "top", B = "bottom", V = "vertical", H = "horizontal"}<br />
<br />
local combinations, combination_labels = {}, {}<br />
for _, direction in pairs(directions) do<br />
for _, orientation in pairs(orientations) do<br />
combinations[#combinations+1] = direction..orientation<br />
end<br />
end<br />
<br />
local function get_foreground_text_colour(r,g,b)<br />
local luminosity = (0.2126 * ((r/255)^2.2)) + (0.7152 * ((g/255)^2.2)) + (0.0722 * ((b /255)^2.2))<br />
if luminosity > 0.5 then<br />
return "black"<br />
else<br />
return "white"<br />
end<br />
end<br />
<br />
local function get_random_colour_rgb()<br />
return math.random(1,255), math.random(1,255), math.random(1,255)<br />
end<br />
<br />
-- create a label with a nestable=true property to say that it can nest labels<br />
all_possible_combinations_label = Geyser.Label:new({name="all_possible_combinations_label", x=0,y="-400",height=50,width=500,<br />
nestable = true, message="<center>Click to see a listing of possible combinations</center>"})<br />
<br />
for i = 1, #combinations do<br />
local combination = combinations[i]<br />
combination_labels[i] = all_possible_combinations_label:addChild({name="combo_"..combination,height=30,width=150, nestable = true, flyOut=true, layoutDir="BH", message="<center>Combination "..combination.."</center>"})<br />
<br />
local r,g,b = get_random_colour_rgb()<br />
local text_colour = get_foreground_text_colour(r,g,b)<br />
<br />
local combination_labels_children = {}<br />
for ii = 1, 3 do<br />
combination_labels_children[ii] = combination_labels[i]:addChild({<br />
name="combo_"..combination.."_"..ii, height = 30, width = 150, layoutDir=combination, flyOut = true,<br />
message = string.format("<center><b>%s</b>%s+<b>%s</b>%s layout</center>", <br />
combination:sub(1,1), mappings[combination:sub(1,1)]:sub(2), combination:sub(2,2), mappings[combination:sub(2,2)]:sub(2)),<br />
fgColor = text_colour})<br />
<br />
combination_labels_children[ii]:setStyleSheet(string.format([[background-color:rgb(%d, %d, %d); border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]], r,g,b))<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look like this:<br />
<br />
[[File:Flyoutlabels-layout-demo.png]]<br />
<br />
=== Geyser.Label right click menu ===<br />
{{MudletVersion|4.10}}<br />
<br />
You can create a right click menu for a label just by using the function (assuming your label name is 'myLabel'):<br />
<syntaxhighlight lang="lua"> myLabelːcreateRightClickMenu({MenuItems = menuTable}) -- scroll down for a fuller example with more details </syntaxhighlight><br />
<br />
The menu table comprises of all the items and their names. To create a parent menu just create a nested table of names.<br />
<br />
Example of a menuTable:<br />
<syntaxhighlight lang="lua"> menuTable = {"First Item", "Second Item (Parent)", {"First ChildItem", "Second ChildItem"}, "Third Item"} </syntaxhighlight><br />
<br />
The menu would look like thisː<br />
<br />
[[File:RCDemo1.gif|250px]]<br />
<br />
You can give more constraints to further style and enhance your right click menu.<br />
<br />
==== Style your right click menu ====<br />
Your right click menu has 2 default styles integratedː "light" and "dark" which are defined by the constraint "Style".<br />
<br />
To set a default style just give the constraint Style the preferred value, for exampleː<br />
<syntaxhighlight lang="lua"> Style = "dark" </syntaxhighlight><br />
<br />
To give different levels of your menu different style just add the number of the level to the constraint, for exampleː<br />
<syntaxhighlight lang="lua"> Style2 = "light" -- Gives the second level of your menu the "light" style</syntaxhighlight><br />
<br />
For adding your own stylesheet use the constraint MenuStyle (use the same method as above to define stylesheets for different levels)<br />
<syntaxhighlight lang="lua"> MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]] <br />
-- Gives the second level of your menu this stylesheet</syntaxhighlight><br />
<br />
The same methods are used for defining the format, width and height for the menu item.<br />
<syntaxhighlight lang="lua"> <br />
MenuWidth = 70 -- standard menu width if nothing else is given<br />
MenuWidth2 = 80 -- menu width for the second level <br />
MenuFormat1 = "c10" -- menu format for the first level (format works like any other label echo format, in this case c is center and 10 is the font-size)<br />
MenuHeight = 30<br />
</syntaxhighlight><br />
<br />
==== Set onClick action for your menu item ====<br />
To set an action if your menu item is clicked use the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<syntaxhighlight lang="lua"> <br />
myLabelːsetMenuAction("First Item", function() echo("Clicked on the first item\n") end<br />
myLabelːsetMenuAction("Second Item (Parent).First ChildItem", function() echo("Clicked on the first child item\n") end) -- To set an action to a child item find it by using "Parent.Child" as name (only one parent is needed to be given the parents parent is not needed)<br />
</syntaxhighlight><br />
<br />
==== Access an menu item directly ====<br />
The simplest way to access a menu item directly is by just using the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<br />
For example to change the menu item textː<br />
<syntaxhighlight lang="lua"> <br />
myLabelːfindMenuElement("First Item"):echo([[my first Item]])<br />
</syntaxhighlight><br />
<br />
==== Right click menu example ====<br />
Better then any further explanation is probably this practical example. <br />
<br />
<syntaxhighlight lang="lua"> <br />
-- create the label the right click menu will be in<br />
myRightClickLabel = myRightClickLabel or Geyser.Label:new({<br />
name = "myRightClickLabel", message = "Please right click!", <br />
format = "cb15", x=10, y=10, width ="30%", height = "15%", <br />
color = "purple"})<br />
<br />
-- right click menu creation with custom styleheet on level2 and default "Dark" style <br />
myRightClickLabel:createRightClickMenu({<br />
MenuItems = {"Emergency", "Drink",{"ManaPotion","HealthPotion"}, "Disappear", "Cast",{"Blindness", "Blink"}}, <br />
Style = "Dark", <br />
MenuWidth2 = 80, <br />
MenuFormat1 = "c10",<br />
MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]]<br />
})<br />
<br />
myRightClickLabel:setMenuAction("Emergency", function() <br />
cecho("<red:pink>[Emergency Mode] Run as fast as possible!\n") <br />
send("emergency") <br />
closeAllLevels(myRightClickLabel) -- this can be used to close the right click menu if clicked on this item<br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.ManaPotion", function()<br />
cecho("<blue>Drinking my mana potion.\n") <br />
send("drink mp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.HealthPotion", function() <br />
cecho("<red>Drinking my health potion.\n") <br />
send("drink hp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Disappear", function() <br />
cecho("<grey>Disappearing.. \n") <br />
send("disappear") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blindness", function() <br />
cecho("<light_blue>Casting blindness \n") <br />
send("cast blindness enemy") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blink", function() <br />
cecho("<light_blue>Casting blink \n") <br />
send("cast blink") <br />
end )<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
<br />
[[File:Right click example demo.gif]]<br />
<br />
==== Add right click menu to label with already existing left click action ====<br />
If your label has an already existing left click action you'll have to create the right click menu<br />
"before" creating the labels "setClickCallBack" action and then just put into your labels onClick function<br />
(assuming your label name is 'myLabel' and 'event' is the last parameter of your onClick function)<br />
<br />
<syntaxhighlight lang="lua"> <br />
myLabel:onRightClick(event)<br />
</syntaxhighlight><br />
<br />
=== Geyser name ===<br />
Make sure to give your Geyser Labels, miniconsoles, and userwindows a <code>name</code> - while it'll technically work without one, items will be duplicated when you re-save them if they're lacking a name.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserStyleSheet.html Geyser.StyleSheet]==<br />
<br />
Allows you to create a managed stylesheet to make it easier to set and change properties. Also allows you to inherit properties from another stylesheet, making it easier to manage multiple styles at once.<br />
<br />
=== Basic Usage ===<br />
<br />
Here's an example to get you started. This creates a basic stylesheet to set the background color black and the foreground/text color to green, then applies it to a Geyser Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
local testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = 100,<br />
y = 100,<br />
height = 100,<br />
width = 300,<br />
stylesheet = stylesheet:getCSS(),<br />
})<br />
<br />
-- Alternate method of creating a stylesheet using a table of properties<br />
local stylesheet = Geyser.StyleSheet:new({<br />
['background-color'] = "black",<br />
['color'] = "green",<br />
})<br />
</syntaxhighlight><br />
<br />
=== Getting the CSS string === <br />
<br />
As shown above, you can use getCSS to get the stylesheet as a string.<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getCSS())<br />
--[[<br />
"background-color: black;\ncolor: green;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Including a target ===<br />
<br />
You can include a 'target' for your stylesheet to be applied to, such as QLabel, QPlainTextEdit, etc.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- QPlainTextEdit is useful for styling command lines in particular, to keep the style from bleeding into any associated miniconsole or userwindow.<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
QPlainTextEdit {<br />
background-color: black;<br />
color: green;<br />
}]])<br />
<br />
-- or as an optional third argument. Passing nil for the parent explicitly <br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]], nil, "QPlainTextEdit")<br />
<br />
-- or using the setTarget function after the fact<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
stylesheet:setTarget("QPlainTextEdit")<br />
</syntaxhighlight><br />
<br />
=== Changing a property ===<br />
<br />
Assuming you started with the example above, if you wanted to change the background color to purple you would do the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("background-color", "purple")<br />
testLabel:setStyleSheet(stylesheet:getCSS())<br />
</syntaxhighlight><br />
<br />
Or if you wanted to set the font, you would do:<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", [["Ubuntu Mono"]])<br />
</syntaxhighlight><br />
<br />
Note the way we set the font with the double quotes included in the string, this is because the quotes have to be there in the final stylesheet. You could use single quotes instead of the bracket notation as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", '"Ubuntu Mono"')<br />
</syntaxhighlight><br />
<br />
=== Getting the value of a property ===<br />
<br />
Again assuming you started with the example code above it's as easy as<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:get("color") -- will return "green"<br />
</syntaxhighlight><br />
<br />
=== Getting a table of properties and their values ===<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Setting the properties via table ===<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setStyleTable({<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"',<br />
})<br />
</syntaxhighlight><br />
<br />
=== Resetting the style with a string ===<br />
<br />
Creating a new Geyser.StyleSheet would break any inheritance for stylesheets which had this one as a parent (see below), so if you wish to reset the style via CSS string you should use :setCSS<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setCSS([[<br />
background-color: black;<br />
color: green;<br />
font: "Ubuntu Mono";<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Inheriting properties ===<br />
<br />
As with most things Geyser, just pass the parent in when you create the new stylesheet<br />
<br />
<syntaxhighlight lang="lua"><br />
local childsheet = Geyser.StyleSheet:new("color: blue;", stylesheet)<br />
display(childsheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "blue",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
<br />
display(childsheet:get("background-color")<br />
--"purple"<br />
<br />
-- show only properties set in this stylesheet, without inheritance<br />
display(childsheet:getStyleTable(false))<br />
--[[<br />
{<br />
color = "blue"<br />
}<br />
--]]<br />
<br />
-- can do the same for the CSS string<br />
display(childsheet:getCSS(false))<br />
--[[<br />
"color: blue;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html Geyser.MiniConsole]==<br />
This allows you to spawn a Mudlet miniconsole - unlike labels, these aren't as styleable, but they do format text better. They make a good fit for text-based menus, chat and map capture, and other things.<br />
<br />
Spawning one is very similar to other Geyser elements - paste this into a new script:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x="70%", y="50%",<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="30%", height="50%",<br />
})<br />
</syntaxhighlight><br />
<br />
This'll make you one at the bottom-right of the screen. The miniconsole will have a grey background by default, but you can set it to any color you'd like with [http://www.mudlet.org/geyser/files/geyser/GeyserWindow.html#Geyser.Window:setColor miniconsole:setColor()]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setColor("black") -- give it a nice black background<br />
</syntaxhighlight><br />
<br />
A special dimension property that MiniConsoles have is a character - instead of specifying a miniconsole to be % of a container or a certain number of pixels, you can specify it as a certain number of characters. You do this by using "c" at the end of a number. This way, you can, for example, specify miniconsole to be 10 letters long and 2 lines high:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="70%", y="50%",<br />
wrapAt = 10,<br />
width="10c", height="2c",<br />
})<br />
flatbox:setColor("red")<br />
flatbox:echo("ABCDEFGHIJ") -- that is 10 letters<br />
</syntaxhighlight><br />
<br />
=== Adding text ===<br />
You can use [[Manual:Technical_Manual#echo|echo()]] the same way with a miniconsole to add text as to the usual window:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("hello!")<br />
</syntaxhighlight><br />
<br />
As well as [[Manual:Technical_Manual#cecho|cecho]], [[Manual:Technical_Manual#decho|decho]], or [[Manual:Technical_Manual#hecho|hecho]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:cecho("<green>hey, <blue>colored <red>text!\n")<br />
</syntaxhighlight><br />
<br />
=== Copying lines with color ===<br />
To copy a line over to the miniconsole, as it is from the game with all colors preserved, you can [[Manual:UI_Functions#selectCurrentLine|select]], [[Manual:UI_Functions#copy|copy]], and [[Manual:UI_Functions#appendBuffer|append]] it. For an example, try making a trigger with this as the ''perl regex'' pattern type:<br />
<br />
<syntaxhighlight lang="lua"><br />
^<br />
</syntaxhighlight><br />
<br />
That'll make the trigger go off on every line. Then give it the following script (assumed you have made the HelloWorld miniconsole from earlier):<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
... and you'll see all MUD output duplicated exactly as it is to the miniconsole. Amazing! It's very efficient as well, so you can have many miniconsoles, even in spam, not lag you down.<br />
<br />
=== Clearing the miniconsole ===<br />
Clearing the miniconsole just requires using the following script (assumes you have made the HelloWorld miniconsole from earlier):<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:clear()<br />
</syntaxhighlight><br />
<br />
=== Doing edits in copied lines ===<br />
Sometimes you'll want to edit the line before stuffing it into the miniconsole. For example, if you're making a chat capture, you'd want to condense a really long org name into something that's more space-friendly.<br />
<br />
To do so, you'd use the [[Manual:Technical_Manual#selectString|selectString()]] the text you'd like to modify, [[Manual:Technical_Manual#replace|replace()]] it with a different one:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Your", 1) -- select the word you'd like to replace - in this case, 'Your'<br />
setBgColor(getBgColor()) -- preserve the background color in the replacement<br />
setFgColor(getFgColor()) -- preserve the foreground color in the replacement<br />
replace("Mine") -- replace the selection with the wird 'Mine'<br />
<br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
=== Gagging from the main window ===<br />
If you'd like to gag the line from the main window so it only shows up in your miniconsole, [[Manual:Technical_Manual#deleteLine|delete]] it after moving it over:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=== Clickable menus ===<br />
Using the [[Manual:Technical_Manual#echoLink|echoLink]], [[Manual:Technical_Manual#insertLink|insertLink]] and [[Manual:Technical_Manual#setLink|setLink]] functions, you can turn text into one that reacts on a click. Combined with your power of placing text anywhere on the screen with a miniconsole, you can make menus with options. Here is one such example, where selecting an item causes an echo to happen:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="20%", y="80%",<br />
width="40c", height="4c",<br />
})<br />
flatbox:setColor("red")<br />
clearWindow("flatbox")<br />
<br />
flatbox:cecho("<white:red>Choose one of the following options:\n")<br />
<br />
flatbox:fg("white")<br />
flatbox:bg("red")<br />
<br />
for _, fruit in ipairs{"banana", "apple", "orange"} do<br />
echoLink("flatbox", "* "..fruit:title().."\n", [[echo("You picked ]]..fruit..[[\n")]], "The "..fruit.." option", true)<br />
end<br />
<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
This will produce something like the following:<br />
<br />
[[File:Fruit_menu.png|center]]<br />
<br />
=== Change your miniconsole background image ===<br />
{{MudletVersion|4.10}}<br />
<br />
To set a custom background image for your miniconsole, use [https://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html#Geyser.MiniConsole:setBackgroundImage :setBackgroundImage()]:<br />
<syntaxhighlight lang="lua"><br />
miniconsole_withBgImg = Geyser.MiniConsole:new({name = "BackgroundonConsole", x="50%", y="50%", width = "20%", height = "40%"})<br />
miniconsole_withBgImg:setBackgroundImage(":/Mudlet_splashscreen_development.png", "center")<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:decho("<:0,0,0,130> This is a decho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:hecho("#,80000000 This is a hecho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:decho("<:0,0,0> This is a decho test with no transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:hecho("#,000000 This is a hecho test with no transparent background\n")<br />
end<br />
</syntaxhighlight><br />
<br />
=== Enable and use your miniconsole command line ===<br />
{{MudletVersion|4.10}}<br />
<br />
Every miniconsole has a hidden command line. Enable it with:<br />
<syntaxhighlight lang="lua"><br />
HelloWorldContainer = HelloWorldContainer or Adjustable.Container:new({name="HelloWorldContainer", titleText = "Container with a command line"})<br />
<br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "purple",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, HelloWorldContainer)<br />
<br />
HelloWorld:enableCommandLine()<br />
</syntaxhighlight><br />
<br />
=== Set an action to your miniconsole command line ===<br />
If no action is set to your miniconsole command line the commands are send to the game the same way as for the main command line. Aliases still work as usual, and if you have command echo enabled in preferences, it'll show in both miniconsole and the main window.<br />
<br />
It is also possible to set an action to your command line, this enables you to use the command line as custom text input.<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:enableCommandLine()<br />
local function channelChat(text)<br />
send("chat "..text)<br />
HelloWorld:echo("[chat] " ..text.."\n")<br />
end<br />
<br />
HelloWorld:setCmdAction(channelChat)<br />
</syntaxhighlight><br />
<br />
This will send your miniconsole command line input to the chat channel.<br />
<br />
More complicated/sophisticated actions are possible, setCmdAction works the same way as the Label clickCallback functions - that is, you can pass arguments to it.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html Geyser.Gauge]==<br />
<!--<br />
This is a composite window. Gauge duplicates the functionality of the built in Mudlet gauges, but in a clean and easily extended way. Internally, a Geyser Gauge is a container holding two Labels, front and back, which are initially scaled to fill the entire Gauge container. Hence, a gauge, g, can be given callbacks with the g.front:setClickCallback() method.<br />
<br />
The backgroundColor parameter initially sets the colors of the gauge, but of course the front and back components can be accessed individually as labels for high control over their looks. Gauges can be horizontal or vertical and decrease in value left to right, right to left, down up or up down depending on the value of the orientation parameter.<br />
--><br />
<br />
A Gauge allows you to represent numbers on a scale - and most typically, you've seen it be used as your standard hp/mana/whatever bar. A basic bar is made similarly to other Geyser elements. To set the value on the gauge that it should represent, use the [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] function:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="5%",<br />
})<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
That'll spawn you a pretty basic gauge with a horizontal orientation and a grey colour - and as a test, with a random value.<br />
<br />
[[File:Basic_gauge.png|center]]<br />
<br />
=== Updating a gauge ===<br />
You'd want your gauge to stay in sync with your actual values. To make that happen, you want to call [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] whenever the value that the gauge is tracking changes.<br />
<br />
So for example, if you make a health bar - wherever you get your new health at (be it prompt, gmcp, atcp or whatever), update the gauge as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- theoretical example<br />
current_health, max_health = tonumber(matches[2]), tonumber(matches[3])<br />
<br />
-- update the bar<br />
hp_bar:setValue(current_health, max_health)<br />
</syntaxhighlight><br />
<br />
You can also write down how much health have you got on the bar with:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local hp = math.random(1,100) <br />
hpbar:setValue(current_health, max_health, "<b>"..max_health.."hp</b>")<br />
<br />
-- example using GMCP in IRE games:<br />
hpbar:setValue((100/gmcp.Char.Vitals.maxhp)*gmcp.Char.Vitals.hp,100,gmcp.Char.Vitals.hp)<br />
</syntaxhighlight><br />
<br />
[[File:Hpbar_basic.png|center]]<br />
<br />
=== Styling a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. Combining this with Geyser:Label.setStyleSheet, you can improve the visuals of your gauges by using Qt-supported CSS. The syntax for specifying CSS is a bit different - it requires a semicolon after every property, and is done in the format of ''property name''''':'''''values''''';'''. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here] and you can use [https://build-system.fman.io/qt-designer-download Qt Designer] to create them. Practical example:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #98f041, stop: 0.1 #8cf029, stop: 0.49 #66cc00, stop: 0.5 #52a300, stop: 1 #66cc00);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #78bd33, stop: 0.1 #6ebd20, stop: 0.49 #4c9900, stop: 0.5 #387000, stop: 1 #4c9900);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge.png|center]]<br />
<br />
The same style can be adjusted by colors to red as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f04141, stop: 0.1 #ef2929, stop: 0.49 #cc0000, stop: 0.5 #a40000, stop: 1 #cc0000);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bd3333, stop: 0.1 #bd2020, stop: 0.49 #990000, stop: 0.5 #700000, stop: 1 #990000);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge_red.png|center]]<br />
<br />
=== Updating a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. To make a gauge clickable you can set a ClickCallBack on the top label which is ''mygauge.text'' example: <syntaxhighlight lang="lua">mygauge.text:setClickCallback("functionName", variableToSendToFunctionName)</syntaxhighlight><br><br />
If you would like to have different click events for the top or back of a gauge you can enable clickThrough for the top or ''mygauge.text'' label example<br />
<br />
<syntaxhighlight lang="lua"><br />
mygauge.text:enableClickthrough()<br />
mygauge.front:setClickCallback("functionOne", variableToSendToFunctionOne)<br />
mygauge.back:setClickCallback("functionTwo", variableToSendToFunctionTwo)<br />
</syntaxhighlight><br />
<br />
<br />
=== Tooltips on gauges ===<br />
Tooltips are available since Mudlet 4.6 as explained in above section [[#Adding_a_tooltip_to_a_label]], and as gauges are really only made up of labels as well, you could add a tooltip then by just using <syntaxhighlight lang="lua">mygauge.text:setToolTip("This is the gauge's tooltip", "10")</syntaxhighlight> the same as it's handled for clickback.<br />
<br />
== HBox/VBox ==<br />
<br />
These are special types of containers. Every window in these is horizontally or vertically aligned in the order they were added.<br />
<br />
{{MudletVersion|2.0}}<br />
<br />
== Geyser.UserWindow ==<br />
Allows you to use Mudlets UserWindows within Geyser, which allows you to use all the functionality of a MiniConsole in its basic form.<br />
The big advantage is the possibility to add other Geyser Elements like Labels, MiniConsole, Gauges, Mappers to the UserWindow.<br />
The UserWindow then can act as container for those elements with all the perks of dynamic resizing or any other Geyser functionality.<br />
<br />
{{MudletVersion|4.6.1}}<br />
<br />
===Basic floating userwindow ===<br />
This will create a movable floating userwindow.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "TestUserWindow",<br />
titleText ="My Test UserWindow", -- only available since Mudlet 4.8+<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
</syntaxhighlight><br />
<br />
You can change the title of the userwindow by using the parameger titleText and the functions below (as of Mudlet 4.8+)ː<br />
<br />
To set a new title after creation useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setTitle("My new title Text")<br />
</syntaxhighlight><br />
<br />
To revert to the standard title useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:resetTitle()<br />
</syntaxhighlight><br />
<br />
To '''save the position''' of the userwindow - say in case you've dragged it onto another monitor and would like it to stay there when you restart Mudlet - use [[Manual:UI_Functions#saveWindowLayout|saveWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
saveWindowLayout()<br />
</syntaxhighlight><br />
<br />
To restore it afterwards, use [[Manual:UI_Functions#loadWindowLayout|loadWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create your userwindows first with Geyser.UserWindow:new<br />
-- then restore them to the positions they were at:<br />
loadWindowLayout()<br />
</syntaxhighlight><br />
<br />
=== Docked UserWindow ===<br />
To create the window docked at the right side,<br />
set the variable docked (at creation of the container) to true.<br />
Be aware that with this variable set to true the position and the size at creation of the userwindow will be ignored.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true<br />
<br />
})<br />
</syntaxhighlight><br />
<br />
Since Mudlet 4.8+ it is also possible to choose the docking Position of the UserWindow at creation and by function withː<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true,<br />
dockPosition = "top" -- Possible dockPositions are left "l", right "r", top "t", bottom "b" and floating "f" <br />
})<br />
</syntaxhighlight><br />
<br />
To change it for a already created UserWindow use the function setDockPosition(dockPosition) likeː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setDockPosition("left")<br />
</syntaxhighlight><br />
<br />
=== Disable/enable UserWindow autoDock ===<br />
{{MudletVersion|4.8}}<br />
<br />
The auto docking feature can be really annoying at times. To disable it use the functionsː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:disableAutoDock() -- disables autoDock. Docking still possible with ːsetDockPosition<br />
testuserwindow:enableAutoDock() -- reenables autoDock<br />
</syntaxhighlight><br />
<br />
=== Styling the UserWindow border and title area ===<br />
{{MudletVersion|4.10}}<br />
{{note}} available on Linux only<br />
<br />
Geyser.UserWindows can accept a stylesheet to change the appearance of the border and title area and make<br />
the UserWindow look more appealing. This unfortunately only works in Linux, as in macOS and Windows, it is the OS theme that is used here. <br />
<br />
<syntaxhighlight lang="lua"><br />
myUserWindow = myUserWindow or Geyser.UserWindow:new({<br />
name = "myUserWindow", titleText = "myUserWindow", autoDock = false<br />
})<br />
<br />
myUserWindow:setStyleSheet( <br />
[[QDockWidget{<br />
border: 1px solid green; /* UserWindow border style */<br />
font: bold 15pt "Arial"; /* Font of the titleBar */<br />
color: rgb(0,0,150); /* Font color */<br />
}<br />
<br />
QDockWidget::title{ <br />
background-color: rgb(0,255,150); /* TitleBar color */<br />
border: 2px solid red; /* TitleBar border */<br />
border-radius: 2px; /* TitleBar border radius */<br />
text-align: center; /* alignment of the titleText */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
[[File:UserWindowStyleSheet.png]]<br />
<br />
=== UserWindow as Container ===<br />
This is the feature which shows the versatile nature of Geyser.UserWindows.<br />
The UserWindow act as container and is at that possible to dynamically resize the containing Geyser Elments.<br />
Put a label in the UserWindow resize it as rectangle.<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "ParentTestUserWindow",<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
<br />
testuserwindow:setColor("dark_green") -- give the userwindow a bit of color <br />
<br />
labelinuserw = Geyser.Label:new({<br />
name = "LabelinUserWindow",<br />
x=20, y=20,<br />
width = -20, height = -20,<br />
color="light_blue", fontSize=20,<br />
},testuserwindow)<br />
<br />
labelinuserw:echo("This is a label in an userwindow", "black", "c")<br />
</syntaxhighlight><br />
[[File:LabelInUserWindow.png]]<br />
<br />
The same way you are able to add your favorite Geyser Application (like tabbed chat, animated timers, gauges) to an UserWindow.<br />
<br />
Note that you don't need to add MiniConsoles to a UserWindow - as UserWindows already have them built-in.<br />
<br />
[[File:Tabbedchatinuserwindow.png]]<br />
<br />
== Geyser.CommandLine ==<br />
{{MudletVersion|4.10}}<br />
<br />
Allows you to create your custom command lines which can resize/move like any other Geyser object.<br />
<br />
If you just need a command line which is integrated in a miniconsole or userwindow, check out [[Manual:Geyser#Enable and use your miniconsole command line|:enableCommandLine()]].<br />
<br />
=== Creating a Geyser.CommandLine ===<br />
An example to get you startedː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine = myCommandLine or Geyser.CommandLine:new({<br />
name = "myCommandLine", <br />
x = "-20%", y = -40, <br />
width = "20%", height = 40,<br />
stylesheet = "border: 1px solid silver;"<br />
})<br />
</syntaxhighlight><br />
This creates a new command line in the right bottom of your screen.<br />
<br />
=== Bind action to your command line input ===<br />
If you use your previously created command line, any command will just be send to the game, after having been checked for aliases.<br />
<br />
To react to any input in a custom manner, we can set an action to the command line and use the input as parameter.<br />
<br />
Example of a command line changing the background color of your main console (assumes you have created "myCommandLine" from earlier): <br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setAction(<br />
function(commandLineInput)<br />
r, g, b = Geyser.Color.parse(commandLineInput) -- gets the r, g, b values of the color you input to the command line<br />
if b then -- checks if the color is valid<br />
setBackgroundColor(r, g, b)<br />
else<br />
echo("\n"..commandLineInput.." is not a valid color. Try again.")<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
=== Styling a command line ===<br />
You can style your Geyser command line by using Qt-supported CSS. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here].<br />
<br />
Practical example (assuming "myCommandLine" is created)ː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setStyleSheet([[<br />
QPlainTextEdit{ /* QPlainTextEdit is used to prevent the styleSheet bleeding to the right click menu*/<br />
border: 1px solid silver; /* Command line border style */<br />
background-color: rgb(0,255,150); /* Command line background color */<br />
font: bold 12pt "Arial"; /* Font and font-size of your command line */<br />
color: rgb(0,0,150); /* Command line text color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Create an extra command line in Mudlet ===<br />
If your goal is to just have an extra command/input line - say, for role-playing purposes: copy/paste the example below into a new script in Mudletː<br />
<br />
<syntaxhighlight lang="lua"><br />
inputContainer = inputContainer or Adjustable.Container:new({<br />
x = 0, y = "-4c", <br />
name = "InputContainer", padding = 2, <br />
width = "100%", height = "4c", <br />
autoLoad = false<br />
})<br />
<br />
extraCmdLine = extraCmdLine or Geyser.CommandLine:new({<br />
name = "extraCmdLine", <br />
x = 0, y = 0, width = "100%", height = "100%"<br />
}, inputContainer)<br />
<br />
inputContainer:attachToBorder("bottom")<br />
</syntaxhighlight><br />
<br />
This will look likeː <br />
<br />
[[File:AdditionalCommandLine.png|extra command line]]<br />
<br />
== Adjustable.Container ==<br />
{{MudletVersion|4.8}}<br />
<br />
Adjustable Containers are a new "GeyserClass" which act as containers for Geyser elements, but with more flexible and user configurable features. They are referred to as "adjustable" because they can be minimized, loaded, saved, moved, adjusted in size with the mouse pointer, and attached to borders. <br />
<br />
A brief video of [https://www.youtube.com/watch?v=GT2ScizuM48&feature=youtu.be Introduction to Adjustable Containers] is available.<br />
<br />
=== Creating an Adjustable.Container ===<br />
An Adjustable.Container is created just like any other Geyser Object. For example, we might experiment with creating a new Adjustable.Container by running the following line of lua code:<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
</syntaxhighlight><br />
This will create a new Adjustable.Container with the name ''testContainer''. Specifying the adjustable container's name is important for saving. Defining a variable, such as ''testCon'' in our above example, allows functions to be used with the Adjustable.Container.<br />
<br />
Our newly created Adjustable.Container may be used the same way as any other Geyser.Container might. For example, let's put a Geyser.Label in our new testContainer:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
testLabel = Geyser.Label:new({name="myTestLabel", x=0, y=0, height="100%", width="100%", color="green"},testCon)<br />
</syntaxhighlight><br />
<br />
The above code creates a new, green-colored Geyser.Label in the ''testCon'' adjustable.container as shown below:<br />
<br />
[[File:GreenLabelinAdjustableContainer.png]]<br />
<br />
You can also create one for miniconsole:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer = miniconsoleContainer or Adjustable.Container:new({name="miniconsoleContainer"})<br />
myMiniconsole = Geyser.MiniConsole:new({<br />
name="myMiniconsole",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, miniconsoleContainer)<br />
<br />
myMiniconsole:echo("Hello!\n")<br />
</syntaxhighlight><br />
<br />
That will give you:<br />
<br />
[[File:Adjustable container miniconsole.png]]<br />
<br />
=== Key Functions ===<br />
A listing of key functions for the Adjustable.Container module can be found hereː https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html<br />
<br />
To make the Adjustable Container show on screen use the following:<syntaxhighlight lang="lua"><br />
testCon:show() --will cause the Adjustable Container to show if not showing<br />
</syntaxhighlight><br />
<br />
===<div id="valid constraints"> Valid Constraints</div>===<br />
Adjustable Container constraints and their default values can be found at [https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html#Adjustable.Container:new].<br />
<br />
These are in addition to the standard Geyser.Container constraints.<br />
<br />
=== Change Title Text ===<br />
To specify the title text of a new container, use the constraint <code>titleText</code> in the constructor (see [[Manual:Geyser#valid constraints|valid constraints]]).<br />
<br />
To change the title text after a container has already been created, use <code>setTitle</code>. Continuing from the previous example, the title for an existing container named "testCon" might be adjusted in a number of ways: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Title") -- changes the container's title to "Title"<br />
</syntaxhighlight><br />
<br />
A container's title text defaults to the color green, but this can also be adjusted by using <code>setTitle</code>: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Red Title Test","red") -- changes the container's title text to "Red Title Test" and displays the text in the specified color "red".<br />
</syntaxhighlight><br />
<br />
To restore a container's default title text, <code>setTitle</code> is issued without any specified title or color: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle() -- resets the container's title text<br />
</syntaxhighlight><br />
<br />
=== AutoSave and AutoLoad ===<br />
The following Adjustable.Container settings can be saved and loadedː<br />
<br />
<code>x</code>, <code>y</code>, <code>height</code>, <code>width</code>, <code>minimized</code>, <code>locked</code>, <code>lock Style</code>, <code>padding</code>, and <code>hidden</code>.<br />
<br />
These settings will be automatically saved when the Mudlet profile is closed, and automatically loaded when a previous Adjustable.Container is created within the corresponding profile.<br />
<br />
To prevent automatic saving and/or loading of these settings, the <code>autoLoad</code> and <code>autoSave</code> constraints can be included in the constructor. For example, the following code will prevent the settings of the ''testCon2'' Adjustable.Container from being loaded upon creation:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", autoLoad=false})<br />
</syntaxhighlight><br />
<br />
To also prevent the ''testCon2'' Adjustable.Container from automatically saving its settings when the Mudlet profile is closed, the <code>autoSave=false</code> constraint would be added at creation as follows:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCont2 = testCont2 or Adjustable.Container:new({name="testCont2", autoLoad=false, autoSave=false})<br />
</syntaxhighlight><br />
<br />
Automatic saving can also be deactivated after an Adjustable.Container has been created, by invoking <code>testCont:disableAutoSave()</code><br />
<br />
Note that even with autoSave and autoLoad disabled, it is still possible to save and load manually through the right-click menu and/or by using <code>testCont:save()</code> or <code>testCont:load()</code> in a script.<br />
<br />
To save/load all your containers manually at the same time, we use <code>Adjustable.Container:saveAll()</code> and/or <code>Adjustable.Container:loadAll()</code><br />
<br />
=== "All" Functions ===<br />
The following functions affect all Adjustable Containers at the same time.<br />
<br />
{{note}} You must create the Adjustable Containers before these functions will have an effect.<br />
<br />
<code>Adjustable.Container.loadAll()</code> loads all the settings from your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container.saveAll()</code> saves all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:showAll()</code> shows all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:doAll(myfunc)</code> creates a function that will affect all your Adjustable Containers. For example:<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:hide() end) -- hides all your adjustable containers<br />
</syntaxhighlight><br />
<br />
=== Custom Save/Load Directories and Slots ===<br />
{{MudletVersion|4.10}}<br />
<br />
==== Custom Directory ====<br />
If no option set your Adjustable.Container saves/loads its settings in your profile directory.<br />
<br />
It is possible to change the default save/load directory by using for example a different defaultDir as constraint when creating your Adjustable.Container.<br />
<br />
{{note}} This can be especially useful for authors of packages which want to ship their own save files.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = "/home/edru/MyAdjustableContainerSettings/"}) -- noteː the directory will be created if it doesn't exist<br />
</syntaxhighlight><br />
<br />
Example for save files in a package (assuming the packagename is "AdjustableContainerTest" and the settings are saved in "myPersonalAdjSettings"<br />
<syntaxhighlight lang="lua"><br />
local packageName = "AdjustableContainerTest"<br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = string.format("%s/%s/myPersonalAdjSettings/", getMudletHomeDir(), packageName)})<br />
</syntaxhighlight><br />
<br />
==== Custom Slot ====<br />
Another useful addition is to choose a save slot depending on the situation or to reset to a default save state.<br />
<br />
To save to a different slot just add it as parameter when saving.<br />
<br />
For exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːsave("combatSlot")<br />
</syntaxhighlight><br />
<br />
To then load from that slot just useː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːload("combatSlot")<br />
</syntaxhighlight><br />
<br />
{{note}} This also allows package/module authors to choose a "default" save setting to reset to.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
Adjustable.ContainerːsaveAll("default") -- saves the default settings<br />
<br />
-- to reset to default settings then just use<br />
Adjustable.ContainerːloadAll("default") -- loads the default settings<br />
</syntaxhighlight><br />
<br />
This can also be used to change the whole GUI on the fly.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
-- in combat situation use combat settings<br />
Adjustable.ContainerːloadAll("combat") -- loads special combat settings<br />
-- combat is over <br />
Adjustable.ContainerːloadAll("default") --reverts to the default settings<br />
</syntaxhighlight><br />
<br />
==== Delete Save File ====<br />
To delete the save file just useː<br />
<syntaxhighlight lang="lua"><br />
testCont2:deleteSaveFile()<br />
</syntaxhighlight><br />
<br />
===Right-click menu===<br />
Your Adjustable Container has also integrated a right-click menu with the main key functions for easier usability:<br />
<br />
[[File:AdjustableContainerRightClickMenu.png]]<br />
<br />
The right-click menu automatically shows you the possible positions to attach to (top, right, bottom, or left) when it's near one of them. For example, to attach a window to the right of the screen, drag it over to the right - and then the 'Attach to - right' will appear as an option:<br />
<br />
[[File:Adjustable Container - attach to right.png]]<br />
<br />
It also shows the lockstyle selection, which allows you to choose what happens when you press <code>Lock</code>, with 4 lockstyles available by default:<br />
<br />
* standard: this is the default lockstyle, with a small margin on top to keep the right click menu usable.<br />
* light: only hides the min/restore and close labels. Borders and margin are not affected.<br />
* full: the container gets fully locked without any margin left for the right click menu.<br />
* border: keeps the borders of the container visible while locked.<br />
<br />
From Mudlet 4.10+ on it is also possible to change your right-click menu style to dark mode by<br />
<br />
<syntaxhighlight lang="lua"><br />
myAdjustableContainer:changeMenuStyle("dark") -- possible menu styles are "dark" or "light"<br />
</syntaxhighlight><br />
<br />
=== Create a Custom Menu with Custom Items ===<br />
To create a new menu element in your right click menu called "Custom" and add an item to it use:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newCustomItem(name, func)<br />
-- for example<br />
testcontainer:newCustomItem("Hello world", function(self) echo("Hello world\n") self:flash() end)<br />
-- this will write "Hello world" to the main console and flashes your container.<br />
</syntaxhighlight><br />
<br />
=== Add new LockStyles ===<br />
For more advanced users it's possible to add a new Lockstyles by:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newLockStyle(name, func)<br />
-- for example<br />
testcontainer:newLockStyle("NewLockStyle", function(self) self.Inside:move(40, 40) self.Inside:resize(-40,-40) self:setTitle("") end)<br />
</syntaxhighlight><br />
<br />
=== Change Adjustable Container Style ===<br />
Additionally to the standard container constraints Adjustable Containers allow you to change at creation: the internal Label style, the menu style, min/close buttons, the menu text, title text... <br />
<br />
( see [[Manual:Geyser#valid constraints|valid constraints]])<br />
An example of a Adjustable Container with different style.<br />
<syntaxhighlight lang="lua"><br />
testCont =<br />
testCont or<br />
Adjustable.Container:new(<br />
{<br />
name = "TestNewStyleContainer",<br />
adjLabelstyle = "background-color:rgba(220,220,220,100%); border: 5px groove grey;",<br />
buttonstyle=[[<br />
QLabel{ border-radius: 7px; background-color: rgba(140,140,140,100%);}<br />
QLabel::hover{ background-color: rgba(160,160,160,50%);}<br />
]],<br />
buttonFontSize = 10,<br />
buttonsize = 20,<br />
titleText = "My new Style",<br />
titleTxtColor = "black",<br />
padding = 15,<br />
}<br />
)<br />
</syntaxhighlight><br />
This code creates a container which looks like this:<br />
<br />
[[File:NewStyleAdjustableContainer.png|Adjustable Container with different style]]<br />
<br />
<br />
=== Attach your Adjustable Container to a Border ===<br />
The simplest way to attach your container to a border is to move your container near the border you want it to attach and use the <br />
right click menu <code> Attach to:</code><br />
<br />
There is also the function <code> TestCont:attachToBorder("right") -- attach TestCont to the right border </code><br />
<br />
To change the margin between container and border use the constraint <code> attachedMargin </code > or the function <code> TestContːsetBorderMargin(10) -- 10 is the margin in px </code><br />
<br />
{{note}} The border is set in percentages and adjusts with screen-size<br />
<br />
=== Create a moveable border frame ===<br />
{{MudletVersion|4.10}}<br />
<br />
Adjustable Container can be connected to a border and therefore act like a frame.<br />
<br />
This only works if your container is attached to a specific border and the border to connect to has also at least one container attached to it.<br />
Use the function <code>connectToBorder</code><br />
<br />
<syntaxhighlight lang="lua"><br />
TestCont:connectToBorder("left") -- possible borders are "top", "bottom", "right", "left"<br />
</syntaxhighlight><br />
<br />
Minimizing automatically disconnects from a border. Another way is to use the function <code>disconnect</code>.<br />
<br />
{{note}}Connected container are still resizable even if locked.<br />
<br />
If you like to do everything with your right click menu there is the function<br />
<br />
<syntaxhighlight lang="lua"><br />
TestContːaddConnectMenu()<br />
</syntaxhighlight><br />
If you want to add the connect menu items to all Adjustable Containers just<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:addConnectMenu() end)<br />
</syntaxhighlight><br />
<br />
There is also a brief video of how to [https://www.youtube.com/watch?v=Ex-q5zAEfpc connect your Adjustable Container] available.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
GUI = GUI or {}<br />
<br />
GUI.top = Adjustable.Container:new({name = "top", y="0%", height = "10%", autoLoad = false})<br />
GUI.bottom = Adjustable.Container:new({name = "bottom", height = "20%", y = "-20%", autoLoad = false})<br />
GUI.right = Adjustable.Container:new({name = "right", y = "0%", height = "100%", x = "-20%", width = "20%", autoLoad = false})<br />
GUI.left = Adjustable.Container:new({name = "left", x = "0%", y = "0%", height = "100%", width = "20%", autoLoad = false})<br />
<br />
<br />
GUI.top:attachToBorder("top")<br />
GUI.bottom:attachToBorder("bottom")<br />
GUI.left:attachToBorder("left")<br />
GUI.right:attachToBorder("right")<br />
<br />
GUI.top:connectToBorder("left")<br />
GUI.top:connectToBorder("right")<br />
GUI.bottom:connectToBorder("left")<br />
GUI.bottom:connectToBorder("right")<br />
</syntaxhighlight><br />
Here's what the frame will look like:<br />
<br />
[[File:Adjustable_frame.gif]]<br />
<br />
=== Add a scrollable box ===<br />
{{MudletVersion|4.15}}<br />
<br />
To add a scrollable box to an adjustable label, try the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
ScrollContainer = ScrollContainer or Adjustable.Container:new({name = "ScrollContainer"})<br />
ContainerBox = ContainerBox or Geyser.ScrollBox:new({name = "ContainerBox", x = 0, y = 0, height = "100%", width = "100%"}, ScrollContainer)</syntaxhighlight><br />
<br />
[[File:Scrollbox-in-container.png|thumb|center]]<br />
<br />
==Change Container==<br />
{{MudletVersion|4.8}}<br />
<br />
With this command it is possible to change an elements or even a containers location to that from another container.<br />
For example:<br />
<syntaxhighlight lang="lua"><br />
mycontainerone:changeContainer(mycontainertwo)<br />
--puts container one into container two which means container two will be the parent of container one<br />
</syntaxhighlight><br />
It is also possible to change to a container which is not located on the main window:<br />
<syntaxhighlight lang="lua"><br />
myEmco:changeContainer(emco_userwindow)<br />
--puts my tabbed chat Emco into my userwindow<br />
--to put it back to the main window change to a container located on the main window<br />
myEmco:changeContainer(mymainwindow_container)<br />
--or if it the element wasn't in a container use the main Geyser Root container called Geyser<br />
myEmco:changeContainer(Geyser)<br />
</syntaxhighlight><br />
<br />
==Geyser.Mapper==<br />
{{MudletVersion|4.8}}<br />
<br />
It‘s possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation use: (this will create a map window docked at the left corner)<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are "left", "right", "top", "bottom", and "floating".<br><br />
To change the dockPosition after creation use:<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget:setDockPosition("floating")<br />
-- this will change myMapWidget dockPosition to floating <br />
</syntaxhighlight><br />
<br />
= Tutorial =<br />
Note: This tutorial assumes you know how scripts in Mudlet work. If not then you should look at the manual first. Also it only shows how Geyser basically works and explains Geysers special windows. It wont go into detail about the windows that where already in Mudlet.<br />
<br />
=== Hello World ===<br />
Let's start with something simple. A Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_1.png]]<br />
<br />
This code creates a blank Label with a size of 200x50 at a position of 50 points horizontal and vertical from its parent window - which is the main window since we didn't specify any.<br />
<br />
You can manipulate the Label through the normal functions but Geyser.Label:new() returns an object which can be used to manipulate the label directly. So you should store it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local HelloWorld = Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
Then you can, for example print a text on it:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_2.png]]<br />
<br />
You can put a format parameter so that the text is, for example, centered.<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_3.png]]<br />
<br />
The second parameter is the color. We set it to nil which means the labels foreground color will be used.<br />
<br />
The color parameter either accepts a string ("red"), a hex value("#FF0000" or "0xFF0000" or "|cFF0000"), or a decimal value "&lt;255,0,0&gt;"<br />
<br />
Example:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", "red", "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
{{note}} This will automatically set the foreground color, so any echo, without the color parameter set, after that will use the same color.<br />
<br />
You can also set the foreground color with the setFgColor method:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setFgColor("red")<br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
=== Containers ===<br />
<br />
Containers are windows that can contain other windows. Actually, since all other Geyser windows subclass container, every window can do that. But containers do not have any visible content by themselves. <br />
<br />
Let's show that by an example:<br />
<syntaxhighlight lang="lua"><br />
local container = Geyser.Container:new({<br />
name="container",<br />
x=50, y=50,<br />
width=250, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
This will create a container, but if you look at the screen you will see nothing at the positon.<br />
There is a way to make containers visible though:<br />
<syntaxhighlight lang="lua"><br />
container:flash()<br />
</syntaxhighlight><br />
<br />
This will flash the container for a short period of time.<br />
<br />
[[Image:Geyser_Container_1.png]]<br />
<br />
flash() accepts a number as paremeter which defines the time, in seconds, the flash is shown.<br />
<br />
Now, that the container is created, you can add other windows to it. There are 2 ways:<br />
<br />
Directly when creating the window:<br />
<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
},<br />
container)<br />
container_label:echo("This is a label in a container", nil, "c")<br />
</syntaxhighlight><br />
<br />
Later, after the window was created<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
})<br />
container_label:echo("This is a label in a container", nil, "c")<br />
container:add(container_label)<br />
</syntaxhighlight><br />
<br />
Both will lead to the same outcome.<br />
<br />
[[Image:Geyser_Container_2.png]]<br />
<br />
Note that we gave a width and height of "100%" to the constructor of the label. This means that the label will take 100% of the containers width and height. If values are given in percent they will even resize with its parent:<br />
<br />
<syntaxhighlight lang="lua"><br />
container:resize(325, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_3.png]]<br />
<br />
The first parameter is the width, the second the height. If the value is nil the current value is used.<br />
<br />
As said in the "Hello World" tutorial the position is relative to its parent window. That's why we could set both x and y to 0 and it is at the position we wanted - the position of the container.<br />
<br />
When we now move the container the label moves with it:<br />
<syntaxhighlight lang="lua"><br />
container:move(400, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_4.png]]<br />
<br />
The first parameter is the x-, the second the y-position. If the value is nil the current value is used.<br />
<br />
=== VBox and HBox ===<br />
<br />
The VBox and HBox classes are special Containers.<br />
They will automatically align its containing windows vertically or horizontally, respectively, in the order they where added to them.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local HBox = Geyser.HBox:new({<br />
name="HBox",<br />
x=0, y=0,<br />
width=400, height=30,<br />
})<br />
<br />
</syntaxhighlight><br />
<br />
Like containers you won't see them by themselves.<br />
<br />
Adding children works like with containers<br />
<syntaxhighlight lang="lua"><br />
<br />
local label1 = Geyser.Label:new({<br />
name="Label1",<br />
},<br />
HBox)<br />
label1:echo("Label 1", "black", "c")<br />
label1:setColor(255, 0, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_1.png]]<br />
<br />
We didn't set any position or size, but the label gets the same size as the HBox.<br />
<br />
If we add another window:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label2 = Geyser.Label:new({<br />
name="Label2",<br />
},<br />
HBox)<br />
label2:echo("Label 2", "black", "c")<br />
label2:setColor(0, 255, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_2.png]]<br />
<br />
the size will be divided equally between them!<br />
<br />
What if you want a child that takes more or less space than the others?<br />
That's possible too:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label3 = Geyser.Label:new({<br />
name="Label3",<br />
h_stretch_factor=2.0,<br />
},<br />
HBox)<br />
label3:echo("Label 3", nil, "c")<br />
label3:setColor(0, 0, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_3.png]]<br />
<br />
As you can see, Label 3 takes the same space as Label 1 and 2 Together. <br />
That's because we supplied a horizontal stretch factor with "h_stretch_factor=2.0"<br />
<br />
This works also with a vertical stretch factor, just replace "h_stretch_factor" with "v_stretch_factor"<br />
<br />
Now you may have windows that should not be stretched at all.<br />
To accomplish this you have to set the horizontal and/or vertical policy:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local label4 = Geyser.Label:new({<br />
name="Label4",<br />
width="13%",<br />
h_policy=Geyser.Fixed,<br />
},<br />
HBox)<br />
label4:echo("Label 4", "black", "c")<br />
label4:setColor(0, 255, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_4.png]]<br />
<br />
Possible values for the policies are Geyser.Fixed and Geyser.Dynamic (which is the default). They can also be applied to VBox and HBox in exactly the same way.<br />
<br />
Note that, like in the example above, the label will retain relative values (like percent) if used.<br />
<br />
The VBox works like the HBox, only that the child windows are aligned vertically.<br />
<br />
= Walkthroughs =<br />
Here are a few walkthroughs that will show you how to combine Geyser elements to create some simple GUI widgets.<br />
<br />
===Create a Clickable Compass===<br />
[[File: compass.png]]<br />
The following will walk you through the process of creating your own clickable compass using the Geyser framework.<br />
====Setup the image files====<br />
The compass requires a handful of images to work properly. You can find them here: https://www.dropbox.com/sh/53l7xrn4ds35wnq/WpWOziVKmH <br><br />
Download each image and place it in your profile folder. You can find your profile folder with getMudletHomeDir()<br><br />
If you're using Mudlet 2.1+ you can enter '''lua getMudletHomeDir()''' from the command line to return the profile folder path on your computer.<br />
<br />
====Create a new script====<br />
Script Name: '''''compass.resize'''''<br><br />
Registered Event Handlers: '''''sysWindowResizeEvent'''''<p><br />
Every snippet of code will be placed within this script.<br />
====Store the screen size====<br />
We'll want to store the screen size in some local variables so they can be easily referenced to later on.<br />
<syntaxhighlight lang="lua">local mw, mh = getMainWindowSize()</syntaxhighlight><br />
<br />
====Create a global table or namespace====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''compass''''' and everything we make from here on out will be stored within the compass table. We'll also add a few values to it: dirs and ratio. '''''compass.dirs''''' will store each direction while '''''compass.ratio''''' will store the ratio of our screen size so you can 'square up' your compass.<br />
<syntaxhighlight lang="lua">compass = compass or {<br />
dirs = {"nw","n","ne","w","center","e","sw","s","se"},<br />
ratio = mw / mh<br />
}</syntaxhighlight><br />
<br />
====Create the parent label====<br />
[[File: grey.png|thumbnail]]<br />
The 'parent label' refers to the label on the bottom layer. The entire compass will be created within this label. It's container is '''main''' for it's parent is the main window.<br />
<syntaxhighlight lang="lua">compass.back = Geyser.Label:new({<br />
name = "compass.back",<br />
x = "25%",<br />
y = "25%",<br />
width = "10%",<br />
height = "10%",<br />
},main)</syntaxhighlight><br />
<br />
====Set the parent label stylesheet====<br />
[[File: blue.png|thumbnail]]<br />
This will create the blue sphere that makes up most of the compass. The background color is a radial gradient that goes from a deep blue to a brighter shade. The border radius rounds the edges. When the radius is exactly half of the label width it forms a circle. The arrows of the compass actually protrude from the sphere so we give it a margin to suck it in a bit for this effect.<br />
<syntaxhighlight lang="lua">compass.back:setStyleSheet([[<br />
background-color: QRadialGradient(cx:.3,cy:1,radius:1,stop:0 rgb(0,0,50),stop:.5 rgb(0,0,100),stop:1 rgb(0,0,255));<br />
border-radius: ]]..tostring(compass.back:get_width()/2-14)..[[px;<br />
margin: 10px;<br />
]])</syntaxhighlight><br />
<br />
====Create a 3x3 grid====<br />
The compass is split into 9 sections. One for each cardinal direction plus an extra space that sits in the center. This 3x3 grid is created by 3 VBoxes that sit within a single HBox (or vice versa but I flipped a coin and this is what it gave me).<br><br />
So first off, we create the HBox. It will be the same size as its parent, ''compass.back''.<br />
<syntaxhighlight lang="lua"> compass.box = Geyser.HBox:new({<br />
name = "compass.box",<br />
x = 0,<br />
y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},compass.back)</syntaxhighlight><br />
Next, we create our 3 VBoxes. You don't need to specify position or size because these are placed within ''compass.box'', an HBox.<br />
<syntaxhighlight lang="lua"> compass.row1 = Geyser.VBox:new({<br />
name = "compass.row1",<br />
},compass.box)<br />
compass.row2 = Geyser.VBox:new({<br />
name = "compass.row2",<br />
},compass.box)<br />
compass.row3 = Geyser.VBox:new({<br />
name = "compass.row3",<br />
},compass.box)</syntaxhighlight><br />
Finally, we add our 9 labels. Take note that they are split up into even groups of 3. Each group is placed into a different ''compass.row#''<br />
<syntaxhighlight lang="lua"> compass.nw = Geyser.Label:new({<br />
name = "compass.nw",<br />
},compass.row1)<br />
<br />
compass.w = Geyser.Label:new({<br />
name = "compass.w",<br />
},compass.row1)<br />
<br />
compass.sw = Geyser.Label:new({<br />
name = "compass.sw",<br />
},compass.row1)<br />
<br />
compass.n = Geyser.Label:new({<br />
name = "compass.n",<br />
},compass.row2)<br />
<br />
compass.center = Geyser.Label:new({<br />
name = "compass.center",<br />
},compass.row2)<br />
<br />
compass.s = Geyser.Label:new({<br />
name = "compass.s",<br />
},compass.row2)<br />
<br />
compass.ne = Geyser.Label:new({<br />
name = "compass.ne",<br />
},compass.row3)<br />
<br />
compass.e = Geyser.Label:new({<br />
name = "compass.e",<br />
},compass.row3)<br />
<br />
compass.se = Geyser.Label:new({<br />
name = "compass.se",<br />
},compass.row3)</syntaxhighlight><br />
====Create a callback function====<br />
We'll want our compass to head in the direction of the arrow we're clicking. This is where we specify so. When the arrow is clicked, this function will be ran with the arrow direction as the argument.<br />
<syntaxhighlight lang="lua">function compass.click(name)<br />
send(name)<br />
end</syntaxhighlight><br />
====Create the hover functions====<br />
We want our arrows to turn yellow when we hover over them. We do so by simply resetting the label's stylesheet and changing the border image. Don't forget to include the margin as we still want that.<br />
<syntaxhighlight lang="lua">function compass.onEnter(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[hover.png");<br />
margin: 5px;<br />
]])<br />
end<br />
<br />
function compass.onLeave(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[.png");<br />
margin: 5px;<br />
]])<br />
end</syntaxhighlight><br />
====Set the stylesheets in the grid====<br />
[[File: Sample.png|thumb]]<br />
Each of the 9 labels need an image of an arrow. Rather than setting each individually, we'll iterate over the ''compass.dirs'' table we made awhile back and add the respective image to each. The names of images are a reflection of the ''compass.dirs'' table. This keeps it consistent and easy to refer to. During the iteration, the callback, setLabelOnEnter and setLabelOnLeave are also set for each label.<br />
<syntaxhighlight lang="lua">for k,v in pairs(compass.dirs) do<br />
compass[v]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..v..[[.png");<br />
margin: 5px;<br />
]])<br />
compass[v]:setClickCallback("compass.click",v)<br />
setLabelOnEnter("compass."..v,"compass.onEnter",v)<br />
setLabelOnLeave("compass."..v,"compass.onLeave",v)<br />
end</syntaxhighlight><br />
<br />
====Resize the compass into a square====<br />
[[File: final.png|thumb]]<br />
Most screen size ratios aren't a perfect 1:1. This will cause a 10% x 10% label to be far from square. By setting our height (the smaller of the two numbers) to our width, we can resize our compass to a near perfect square. This function is also the name of our script because we want it to run each time sysWindowResizeEvent is raised.<br />
<syntaxhighlight lang="lua">function compass.resize()<br />
compass.back:resize(compass.back.width, compass.back:get_width())<br />
end<br />
<br />
compass.resize()</syntaxhighlight><br />
<br />
===Create a Tabbed Window===<br />
[[File: tabwindow.png]]<br />
The following will walk you through the process of creating your own tabbed window using the Geyser framework.<br />
<br />
====Create a new script====<br />
Script Name: '''''Tabbed Window'''''<br><br />
Every snippet of code will be placed within this script.<br />
====Create a global table====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''menu''''' and everything we make from here on out will be stored within the menu table. We'll also add a few values to it: tabs, color1, color2, width, height and current. <br><br />
''''tabs'''' will be a table that stores all our tab names. If we want our tabs to have different names, we alter this table.<br><br />
''''color1'''' and ''''color2'''' will store the colors of our tabbed window. If we want to change the color of our tabbed window, we alter these values.<br><br />
''''width'''' and ''''height'''' will store the size of our tabbed window. If we want to change the size of the tabbed window, we alter these values.<br><br />
''''current'''' keeps track of which tab is selected. We will set this to the first tab in the table by default. We do this outside the initial table creation so we can easily access menu.tabs<br><br />
<syntaxhighlight lang="lua">menu = menu or {<br />
tabs = {"Tab1","Tab2","Tab3","Tab4"},<br />
color1 = "rgb(0,0,70)",<br />
color2 = "rgb(0,0,50)",<br />
width = "20%",<br />
height = "40%",<br />
}<br />
menu.current = menu.current or menu.tabs[1]</syntaxhighlight><br />
<br />
====Create the main container====<br />
Our tabbed window will need a container. This will be the bottom layer. Containers are invisible so no need to set a stylesheet.<br />
<syntaxhighlight lang="lua">menu.container = Geyser.Container:new({<br />
name = "menu.back",<br />
x = "50%", y = "25%",<br />
width = menu.width,<br />
height = menu.height,<br />
},main)</syntaxhighlight><br />
====Create an HBox====<br />
All of our tabs will be evenly spaced. So we'll create an HBox to sit at the top of our container.<br />
<syntaxhighlight lang="lua">menu.header = Geyser.HBox:new({<br />
name = "menu.header",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "10%",<br />
},menu.container)</syntaxhighlight><br />
====Create a label====<br />
This label will serve as a container for each window. It sits right underneath the HBox we just created for the tabs.<br />
<syntaxhighlight lang="lua">menu.footer = Geyser.Label:new({<br />
name = "menu.footer",<br />
x = 0, y = "10%",<br />
width = "100%",<br />
height = "90%",<br />
},menu.container)</syntaxhighlight><br />
We don't want this to be a big grey box at startup, so we'll set the stylesheet to appear like the rest of the windows.<br />
<syntaxhighlight lang="lua"><br />
menu.footer:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])</syntaxhighlight><br />
Each window actually has two labels. One for the light blue background, and another for the dark blue center. This will create that dark blue center.<br />
<syntaxhighlight lang="lua">menu.center = Geyser.Label:new({<br />
name = "menu.center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
menu.center:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])</syntaxhighlight><br />
====Add your tabs and their windows====<br />
Now we'll want to add our tabs and windows. We do this in a single for loop of the ''''menu.tabs'''' table since it holds all our tab names.<br />
<syntaxhighlight lang="lua">for k,v in pairs(menu.tabs) do<br />
</syntaxhighlight><br />
This will create the tabs. Each tab will be named: menu.<tabname>tab<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"] = Geyser.Label:new({<br />
name = "menu."..v.."tab",<br />
},menu.header)<br />
</syntaxhighlight><br />
Here is where we set the tab stylesheet. Each tab has a rounded top, so we set the border-radius of the top-left and top-right to 10px. Each tab has a small space for separation so we give the right and left sides a tiny margin of 1px.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-top-left-radius: 10px;<br />
border-top-right-radius: 10px;<br />
margin-right: 1px;<br />
margin-left: 1px;<br />
]])<br />
</syntaxhighlight><br />
This will display the name of each tab on the tab.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:echo("<center>"..v)<br />
</syntaxhighlight><br />
We need our tabs to do stuff when clicked, so we'll assign it a callback function, '''''menu.click''''', which we'll create later on. Our tab name is the argument.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setClickCallback("menu.click",v)<br />
</syntaxhighlight><br />
Now we create the windows that appear when each tab is clicked. Each window has two labels, one atop the other. The first, which we'll create here, has rounded edges on its bottom.<br />
<syntaxhighlight lang="lua"><br />
menu[v] = Geyser.Label:new({<br />
name = "menu."..v,<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
<br />
menu[v]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
The second label serves as the window's center and has rounded edges on all sides. And a margin of 5px from it's parent, the label we just created. When adding stuff to your windows, this is the label you'll want to use. '''''menu.<tabname>center'''''<br />
<syntaxhighlight lang="lua"><br />
menu[v.."center"] = Geyser.Label:new({<br />
name = "menu."..v.."center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu[v])<br />
</syntaxhighlight><syntaxhighlight lang="lua"><br />
menu[v.."center"]:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])<br />
</syntaxhighlight><br />
Finally, we hide all the windows and end the for loop.<br />
<syntaxhighlight lang="lua"><br />
menu[v]:hide()<br />
end</syntaxhighlight><br />
====Create a callback function====<br />
The last step is to create our callback function for when a tab is clicked. This will hide that tab that is stored in '''''menu.current''''', set menu.current to the clicked tab, and then show the menu.current tab.<br />
<syntaxhighlight lang="lua">function menu.click(tab)<br />
menu[menu.current]:hide()<br />
menu.current = tab<br />
menu[menu.current]:show()<br />
end</syntaxhighlight><br />
====Adding content to your windows====<br />
Add content to '''menu.<tab name>center'''<br />
So if we wanted to display our gold in a window we could:<syntaxhighlight lang="lua">menu.Tab1center:echo(myGold)</syntaxhighlight><br />
If we wanted to add a map to a window we could:<br />
<syntaxhighlight lang="lua">myMap = Geyser.Mapper:new({<br />
name = "myMap",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.Tab2center)</syntaxhighlight><br />
<br />
===Create a Window with a resize label===<br />
<br />
Previous tutorial is now done much simpler [[Manual:Geyser#Adjustable.Container|Adjustable containers]], have a look at those instead.<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Geyser&diff=20330Manual:Geyser2023-03-02T07:29:59Z<p>Kebap: /* Geyser.UserWindow */ Use Template:MudletVersion</p>
<hr />
<div>{{TOC right}}<br />
<br />
= Introduction =<br />
<br />
The Geyser Layout Manager is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
=== Motivation ===<br />
<br />
Mudlet makes the creation of label, miniconsoles and gauges a quick and easy thing. Mudlet provides a nice signal when window resize events happen. To help with complex window management, Geyser steps in.<br />
<br />
=== Main Geyser Features ===<br />
<br />
Geyser is based on traditional GUI concepts and should feel similar to using Java's Swing. The biggest difference is in how positions are specified.<br />
<br />
* All window positions are specified relative to their container - nothing new there. However, window positions can also take on percentages and negative pixel and character values. For instance, a window could be constrained to have a height of 50% of its container and a width such that the window's right edge is always 20 characters from its container's right edge. See examples below and the demos/tests that come with Geyser.<br />
* All windows under Geyser control are automatically resized as necessary when the main Mudlet window is resized. Once you create a window and assign it to a container, you never have to worry about positioning it again. Nonetheless, it's very easy to shift the container that a window is in, maintaining its constraints so that it resizes as needed according to the dimensions of the new container.<br />
* Due to the container hierarchy, hiding a container window automatically hides all its contained windows too. The same for show. With clever construction and labels with callbacks, this lets one make complex GUI elements that are minimizable or maximizable or ...<br />
* However, there is always some overhead for automation systems and Geyser is no exception. Fortunately, most of the overhead is during window creation and resize events - not things that happen frequently.<br />
<br />
=== Getting pictures for your stuff ===<br />
You can find good, freely-available assets for your UI here:<br />
* [https://kenney.nl/assets?q=2d kenney.nl]<br />
* [https://opengameart.org/ opengameart.org]<br />
* [https://game-icons.net/ game-icons.net]<br />
<br />
=== Constraints format ===<br />
<br />
Geyser position constraints are a string composed of a number and a format type. For example, "10px" means 10 pixels, either pixels from the origin (e.g. x or y) or a value for the width or height. A negative number indicates distance from a container's right or bottom border depending on whether is a constraint for x/width or y/height, respectively. Percentages for width and height are in terms of the container's dimensions and negative values are converted to the equivalent positive value. A 100% width subwindow with an x-coordinate of 10 will have part of itself displayed outside the confines of its container. There is no hard limit on maximum window size, just as with regular Mudlet windows. If a number, n, is passed as a constraint instead of a string, it is assumed to be equivalent to "npx". Any Lua table that contains entries for x, y, width and height in the proper format can be used for Geyser constructors and setting constraints. Just like in Mudlet, 0,0 coordinates mean the top-left corner.<br />
<br />
The following is a valid example for coordinates of a Geyser object:<br />
<br />
<syntaxhighlight lang="lua"><br />
{x = "20px", y = "-10c", width = "40%", height = 30}<br />
</syntaxhighlight><br />
<br />
=== Math in Geyser ===<br />
You can also use math in your Geyser constraints just to line things up just right! Want to have a label occupy full height but not the first 30 pixels? You can:<br />
<br />
<syntaxhighlight lang="lua"><br />
footer = Geyser.Label:new({<br />
name = "footer",<br />
x = 0, y = 30,<br />
height = "100%-30px",<br />
}, main_window)<br />
</syntaxhighlight><br />
<br />
= Geyser elements =<br />
The purpose of this document is to go through every Geyser element and provide practical examples on how they are used. Read it from top to bottom, preferably doing all of the examples to understand how they work!<br />
<br />
== Technical manual ==<br />
<br />
See https://www.mudlet.org/geyser/files/index.html for a brief and technical overview of all Geyser elements and their functions.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html Geyser.Container]==<br />
An invisible, organizing object in Geyser - use it to divide your screen and position elements accordingly. '''[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html See here]''' for all of the functions that are available to you to use.<br />
<br />
A container is also the base class - which means that everything (labels, miniconsoles and gauges) can use its functions, since everything else is at heart a container.<br />
<br />
=== Creating a container ===<br />
To get started with a container, here's an example that'll create a 200px border on the left side of Mudlet for you, and make a container cover all of it - so you can place other visual elements inside it:<br />
<br />
<syntaxhighlight lang="lua"><br />
setBorderLeft(200)<br />
left_container = Geyser.Container:new({<br />
name = "left_container", -- give it a unique name here<br />
x=0, y=0, -- have it start at the top-left corner of mudlet<br />
width = 200, height="100%", -- with a width of 200, and a height of the full screen, hence 100%<br />
})<br />
</syntaxhighlight><br />
<br />
Right away, you'll see space appear on the left side. It'll be black, as the container is an invisible unit by itself. You can make sure it's there by making it flash by doing this from the input line:<br />
<br />
<syntaxhighlight lang="lua">lua left_container:flash()</syntaxhighlight><br />
<br />
The command will cause your container to flash for a moment for you, revealing itself.<br />
<br />
{{Note}} If you hide a container and create new Geyser elements within it, they'll be shown automatically for you.<br />
<br />
=== Container within a container ===<br />
You can place containers within other containers by specifying which "parent" the new container should have when you create one. Given our [[#Creating a container|previous example]], you can split the left side into two halves like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
left_container_top = Geyser.Container:new({<br />
name = "left_container_top",<br />
x=0, y=0, -- this container occupies the top, so it starts top-left as well<br />
width = "100%", height="50%", -- but only uses up half of the height<br />
}, left_container) -- this is the important bit - it says that left_container_top should be inside left_container<br />
<br />
left_container_bottom = Geyser.Container:new({<br />
name = "left_container_bottom",<br />
x=0, y="50%", -- this container starts halfway down the first one<br />
width = "100%", height="50%", -- and has the same half height of the original container<br />
}, left_container) <br />
</syntaxhighlight><br />
<br />
=== Aligning relative to bottom or right sides ===<br />
The aligning point within Mudlet is the top-left corner, and it's the same for the elements they are aligned - the position you specify is used by the top-left corner of the element.<br />
<br />
Using Geyser, you can align to the opposite side as well, using the coordinates in negatives, while keeping the dimensions of the object in mind. For example, if you want to align a box that's 20px wide on the usual left side, you'd give it a width of 20 and an x value of 0. If you'd like to align it on the right side, then you'd give it an x value of -20. The box will spawn 20px away from the right side and "grow" to the right by 20px.<br />
<br />
<syntaxhighlight lang="lua"><br />
right_container = Geyser.Container:new({<br />
name = "right_container",<br />
x="-20%", y=0, -- makes the container start 20% of the screen away from the right side<br />
width = "20%", height="50%", -- filling it up until the end<br />
}) <br />
</syntaxhighlight><br />
<br />
Do make sure to account for the scrollbar, as Mudlet UI elements can overlap it. You can also move the scrollbar with [[Manual:UI_Functions#setBorderRight|setBorderRight()]].<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html Geyser.Label]==<br />
Labels allow you to use pictures in your interface, as well as nicely-formatted text - see docs for label [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html functions].<br />
<br />
=== Basic label ===<br />
<br />
Here's an example to get you started with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
</syntaxhighlight><br />
<br />
This labels '''x''' coordinate is specified as 50% - and because it's not attached to any container, this implies that the window will start halfway at the main window. You can tell it's not attached to a container because there's nothing in between the last ''}'' and '')'', the place where the container goes.<br />
<br />
The '''y''' coordinate is 0 - which means that the label will start at the top of the screen. With the width being 50%, the label will occupy 50% of the screen - and since it starts at the halfway point, it means it'll occupy the entire right side. A height of 100% means that it'll stretch from the top to the full bottom.<br />
<br />
Here's what that'll look like:<br />
<br />
[[File:Simple-label.png|center|600px]]<br />
<br />
<br />
Playing around with the starting location and dimensions, we can also place it in the center of the screen with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
})<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
[[File:Simple_label_centered.png|center|600px]]<br />
<br />
To change the message on a label, you can use the ''mylabel:echo()'' function, where ''mylabel'' is the name of the label you gave it:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("hello!")<br />
</syntaxhighlight><br />
<br />
To get rid of the label, use the '':hide()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:hide()<br />
</syntaxhighlight><br />
<br />
=== Coloring text ===<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black", -- default text colour<br />
color = "SeaGreen" -- default label background<br />
})<br />
<br />
-- You can also change colour of text on demand with:<br />
testlabel:echo[[<p style="color:blue;">You can change the text color of a whole sentence or paragraph...</p><p>...or you can change the text color of one <span style="color:green;">word</span> or even a single l<span style="color:red;">e</span>tter.</p>]]<br />
</syntaxhighlight><br />
<br />
=== Setting the font size ===<br />
<br />
To set a different font size for your Label, use the ''setFontSize()'' method. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel:setFontSize(14)<br />
</syntaxhighlight><br />
<br />
The font size is set in Pt, so anything above 30 will likely be too large to be useful.<br />
<br />
=== Label inside a container ===<br />
<br />
Once you've got your containers and mastered the basic labels, you can drop labels into your nicely-organized containers. Doing so is similar to nesting containers:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
}, left_container_bottom) -- this is where we tell it what container to go into<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
That label is exactly the same as the one above that goes across the screen, except it's in our bottom-left container - so it looks appropriately different:<br />
<br />
[[File:Label in a container.png|center]]<br />
<br />
=== Image on a label ===<br />
One of the more amazing things labels allow you to do is put pictures anywhere on your Mudlet screen, that blend in very well. To do so, once the label is created, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setBackgroundImage setBackgroundImage()] function with the exact path to the image ([[File:Skullface.png]]):<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 0, y = "-14px",<br />
width = "16px", height = "14px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/skullface.png]]) -- update location to actual image location on your computer<br />
</syntaxhighlight><br />
<br />
This'll plop the picture to the bottom-left of your screen. To make the picture show, download the skullface picture above - save it to your desktop, and adjust the location of the image within [[]]'s to what it is on your computer. For example, if you saved this on your Windows 7 desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[C:/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
(yes, that's / and not \ - \ has been known not to work)<br />
<br />
If you saved this on your Mac desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
If you saved this on your Ubuntu desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/home/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
Using this basic building block, you can work up to making yourself a UI!<br />
<br />
=== Stretching an image on a label ===<br />
If you'd like your image not to keep its original size, but instead use up the available space of the label - you can use the [http://doc.qt.io/qt-5/stylesheet-reference.html#border-image border-image] stylesheet property to do so.<br />
<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- change the location to your picture<br />
-- on windows, use / to separate folders still, not \<br />
label:setStyleSheet[[<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);<br />
]]<br />
</syntaxhighlight><br />
<br />
{{note}} If you're on a Mudlet earlier than 3.15 and are having difficulty with the image coming up, it may be because of strange differences between Qt's CSS engine which does not affect mudlet's Lua. You may want to try appending :gsub("\\","/") to your string including getMudletHomeDir() (e.g. <code>getMudletHomeDir():gsub("\\","/")</code>). No longer necessary after Mudlet 3.15.<br />
<br />
=== Aligning an image within a label ===<br />
You can use background-image in combination with background-position to align an image within a label (if, say, the image is much smaller than the label).<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this will set and align an image top-right of the label<br />
if stunning then<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-ok.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
else<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-no.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
end<br />
</syntaxhighlight><br />
<br />
=== Showing / hiding a label ===<br />
You can show and hide labels, as you can any container, miniconsole or a gauge in Geyser with [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:show Geyser.Container:show()] and [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:hide Geyser.Container:hide()]. Remember that since labels are a type of a container, all container functions work on them.<br />
<br />
Hiding a label will allow you to click through on what is below the label, as well as free up the visual space for something else.<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- hide the label with:<br />
testlabel:hide()<br />
<br />
-- show the label with:<br />
testlabel:show()<br />
</syntaxhighlight><br />
<br />
=== Clickable images ===<br />
Tacking onto the fact that you can plop images anywhere on your Mudlet screen now, you can also make them react to your clicks. You can do so with the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setClickCallback setClickCallback()] function - by giving it a function to call when your label is clicked, you'll make it react.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "-215px", y = "0px",<br />
width = "200px", height = "200px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/qubodup-opengameart-cc0-200px-missile_icon.png]]) -- update location to actual image location on your computer<br />
picture_label:setClickCallback("on_bomb_press")<br />
<br />
function on_bomb_press()<br />
send("say BOOM!")<br />
end<br />
</syntaxhighlight><br />
<br />
That's it! Pressing on the image will make the ''on_bomb_press()'' function go off, which will do its code of ''send("say BOOM!")''. Download the picture for use [http://opengameart.org/content/missile-rts-icon here].<br />
<br />
[[File:Clickable_image.png|500px|center]]<br />
<br />
=== Styling labels ===<br />
Besides putting text or images on labels, you can also style them using Qt's stylesheets feature. Doing so allows you to create various graphics that make the label look more appealing:<br />
<br />
[[File:Label_styling_examples.png|center]]<br />
<br />
To set a stylesheet on a label, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setStyleSheet Geyser.Label:setStyleSheet()] function on your label, describing the stylesheet you'd like to give it. A stylesheet consists of properties you set - for example the background color, borders, padding, and so forth. You describe properties in the following format: ''property name''''':'''''values''''';'''. See here for a [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties list of all supported properties]. For example, to make your labels background be yellow, you'd use the background-color property:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "mylabel",<br />
x = "50%", y = "50%",<br />
width = 200, height = 100<br />
})<br />
<br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet.png|center]]<br />
<br />
Which is nice, but not particularly impressive.<br />
<br />
Scrolling down the list of properties, you'll come along a border one. Plopping it into our stylesheet nets the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
border: 5px solid white;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border.png|center]]<br />
<br />
Which gives a border!<br />
<br />
Fiddling with it some more and applying new properties we find on that page, we get a rounded border on our label:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: grey;<br />
border-width: 15px;<br />
border-style: solid;<br />
border-color: green;<br />
border-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border_radius.png|center]]<br />
<br />
Which'll conclude our exploration for now. Try out all of the other possible options available there - there's loads, from [http://doc.qt.io/qt-5/stylesheet-reference.html#border-style funky borders], to tiling images and fancy color combinations using gradients.<br />
<br />
You should also check out [[Manual:Geyser#Geyser.StyleSheet|Geyser.StyleSheet]] for a way to manage your stylesheets with adjustable properties and the ability to take defaults from another stylesheet.<br />
<br />
=== Adding a tooltip to a label ===<br />
<br />
Since Mudlet 4.6, you can now add a tooltip to labels and gauges. You can start by making a simple label and echoing some text to it:<br />
<br />
<syntaxhighlight lang="lua"><br />
testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = "50%",<br />
y = "50%",<br />
height = "25%",<br />
width = "25%",<br />
})<br />
testLabel:echo("This is on the label!")<br />
testLabel:setAlignment("center")<br />
-- sets the tooltip text<br />
testLabel:setToolTip("This is the tooltip", "10")<br />
<br />
<br />
-- optionally - you can customise the tooltip, too!<br />
testLabel:setStyleSheet("QToolTip{background: yellow; color: blue; border:none;}")<br />
</syntaxhighlight><br />
<br />
Without tooltip<br />
[[File:TestLabelForTooltips.png|thumb|center]]<br />
<br />
With tooltip<br />
<br />
[[File:LabelTooltip.png|thumb|center]]<br />
<br />
=== Avoid stylesheet inheritance by tooltip ===<br />
<br />
{{note}} If you set a new stylesheet for a label and with that a background image it is possible that through inheritance the tooltip also has this stylesheet image.<br />
<br />
To avoid this specify that the stylesheet is meant for the Label by using QLabel{...} in your Label stylesheet for exampleː<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- by using QLabel{...} the stylesheet won't be given to the tooltip as well<br />
label:setStyleSheet[[<br />
QLabel{<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);}<br />
]]<br />
</syntaxhighlight><br />
<br />
<br />
=== Aligning text/images inside a label ===<br />
By default, text is [http://qt-project.org/doc/qt-5/qlabel.html#alignment-prop centered vertically and left aligned] in a label. To align it to a specific side, use the stylesheets we learnt about earlier with the qproperty-alignment:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- specify one property this way:<br />
mylabel:setStyleSheet([[qproperty-alignment: 'AlignTop';]])<br />
<br />
-- or multiple ones separated with a |, for example this will align text to top-left:<br />
mylabel:setStyleSheet([[<br />
qproperty-alignment: 'AlignLeft | AlignTop';<br />
]])<br />
<br />
mylabel:echo("hi!")<br />
</syntaxhighlight><br />
<br />
[[File:Text_aligned.png|center]]<br />
<br />
=== Enabling wordwrap in a label ===<br />
If you need to enable word wrapping in a label (which by default is off), add the following line to the labels stylesheet:<br />
<br />
qproperty-wordWrap: true;<br />
<br />
As an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
If you'd like to set multiple properties, set them all at once - not via multiple :setStyleSheet() calls:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background: red;<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Adding a hover effect to a label ===<br />
The labels support adding stylesheets for specific cases, such as when a mouse is [http://doc.qt.io/qt-5/stylesheet-reference.html#hover-ps hovering] over them. To make this work, you provide CSS for when the label is in its usual state, and for when it is hovered over:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this example will add a border to the label when it is hovered over<br />
mylabell:setStyleSheet([[<br />
QLabel{ border-radius: 4px; }<br />
QLabel::hover{<br />
background-color: rgba(0,0,0,0%);<br />
border: 4px double green;<br />
border-radius: 4px;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Checkboxes ===<br />
Combining the fact that you can click on a label with an image to do something with the fact that you can change pictures on a label at will, you can make an image that changes itself when you click on it.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "50%", y = "50%",<br />
width = "21px", height = "19px"<br />
})<br />
-- a little trick we do to make the background of the label be transparent<br />
picture_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
picture_label:setClickCallback("on_checkbox_press")<br />
<br />
function on_checkbox_press()<br />
if checkbox_ticked then<br />
checkbox_ticked = false<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_unticked.png]])<br />
echo("Checkbox unticked.\n")<br />
else<br />
checkbox_ticked = true<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
echo("Checkbox TICKED!\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
The ''on_checkbox_press()'' function this time keeps the track of the checkbox with the ''checkbox_ticked'' variable and sets the image appropriately. You can download the ticked ([[File:Checkbox_ticked.png]]) and unticked images ([[File:Checkbox_unticked.png]]) or the [http://wiki.mudlet.org/images/6/6d/Checkbox.mpackage whole package] altogether.<br />
<br />
[[File:Checkbox_demo.png|500px|center]]<br />
<br />
=== Animated labels with sprites ===<br />
You can animate sprite packs using timers. Assuming you have the sprite pack downloaded, try this example:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 10, y = "-24px",<br />
width = "16px", height = "14px",<br />
})<br />
<br />
santa_counter = nil<br />
<br />
function animate_santa()<br />
santa_counter = (santa_counter or 0) + 1<br />
if santa_counter > 8 then santa_counter = 1 end<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/santa/santa]]..santa_counter..[[.png]]) -- update location to actual image location on your computer<br />
santa_timer = tempTimer(.16, animate_santa)<br />
end<br />
<br />
animate_santa()<br />
</syntaxhighlight><br />
<br />
The completed package is available [http://wiki.mudlet.org/images/6/6b/Dancing-santa.mpackage here], install it and do '''start/end animation''' to watch.<br />
<br />
=== Inserting extra spaces and newlines ===<br />
Echoing text into Mudlet and Geyser labels is different from miniconsoles and the main window, due to their nature. One of the differences is that extra spaces in a label, by default, get compressed down to one. '''To add extra spaces in a label''', replace extra spaces with '''&amp;nbsp;''' or by wrapping your text with them inside '''<nowiki><pre>my text here</pre></nowiki>'''.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this won't work, it'll show as one space:<br />
mylabel:echo("You -> point")<br />
<br />
-- but this would, because it replaces all spaces with &nbsp before echoing<br />
mylabel:echo(string.gsub("You -> point", " ", "&nbsp;"))<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- here is another way to go about this - and it additionally makes the font be monospaced:<br />
mylabel:echo("<pre>You -> point</pre>")<br />
</syntaxhighlight><br />
<br />
'''To add a new line in a label''' (aka linebreak), use '''<nowiki><br></nowiki>''' (instead of ''\n'' as you are used to in an echo).<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("These<br>words<br>are<br>split")<br />
</syntaxhighlight><br />
<br />
=== Transparent labels ===<br />
One of the possible ways of achieving transparency on a label is to add <code>background-color: rgba(0,0,0,0%);</code> to its stylesheet. Here's an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
my_transparent_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
</syntaxhighlight><br />
<br />
Want to get transparency in a miniconsole? You can [[Manual:Geyser#Change_your_miniconsole_background_image|do that as well]].<br />
<br />
=== Custom mouse cursor ===<br />
You can change the shape of the cursor when it's over your label with:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCursor("Forbidden") -- will change your mouse cursor to "forbidden" (as in "can't do this") cursor<br />
</syntaxhighlight><br />
Possible cursor shapes are [[CursorShapes| available here]], and you can import this [[Media:Cursor grid.zip|demo package]] to try them all out.<br />
<br />
It is also possible to change the mouse cursor to a custom made cursor by:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCustomCursor(getMudletHomeDir().."/custom_cursor.png")<br />
</syntaxhighlight><br />
It is recommended that the custom cursor is a png with size of 32x32 to be supported on all systems.<br />
<br />
[[File:Changecursoroverlabel.gif]]<br />
<br />
{{Note}} Available in Mudlet 4.8+<br />
<br />
=== Flyout Labels ===<br />
<br />
Flyout labels allow you to create 'dropdown' or 'flyout' menus - menus that reveal more items once you hover your mouse over them. To create flyout labels:<br />
# add <code>nestable=true</code> (left click to open menu) or <code>nestflyout=true</code> (mouse hover to open menu) to your main label.<br />
# use [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] on your main label to add flyout labels to it.<br />
## [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] uses the same arguments as when creating a new label but also takes the '''layoutDir''' option to specify in which direction and axis should the labels align, where 2 letters combine into the option: first letter R for right, L for left, T for top, B for bottom, followed by the orientation: V for vertical or H for horizontal. So options are: <code>layoutDir="RV"</code>, <code>layoutDir="RH"</code>, <code>layoutDir="LV"</code>, <code>layoutDir="LH"</code>, and so on.<br />
# optionally, add <code>flyOut=true</code> to your flyout labels to make the labels dissapear when the mouse isn't hovering over them anymore.<br />
<br />
Note that the main flyout label cannot go into a container and needs to be on its own.<br />
<br />
{{note}} Requires Mudlet 3.0.<br />
<br />
==== Demo ====<br />
Here's an example that follows the steps above:<br />
<br />
<syntaxhighlight lang="lua"><br />
label0 = Geyser.Label:new({name="label0", <br />
x="50%",y="50%",height=50,width=300,nestable=true, <br />
message="<center>Clicky clicky</center>"})<br />
<br />
-- and add 3 labels to it with RV layout - so Right of the label, aligned Vertically<br />
label1 = label0:addChild({name="label1",height=30,width=70, layoutDir="RV", flyOut=true, message="label one"})<br />
label1:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label2 = label0:addChild({name="label2",height=30,width=70, layoutDir="RV", flyOut=true, message="label two"}) <br />
label2:setStyleSheet([[background-color: green; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label3 = label0:addChild({name="label3",height=30,width=70, layoutDir="RV", flyOut=true, message="label three"})<br />
label3:setStyleSheet([[background-color: red; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
</syntaxhighlight><br />
<br />
A more thorough example. Try it out to see what you can create with flyout labels:<br />
<syntaxhighlight lang="lua"><br />
-- create a label with a nestable=true property to say that it can nest labels<br />
mainlabel = Geyser.Label:new({name="testa", x=400,y=50,height=50,width=300,nestflyout=true, message="<center>HOVER HERE TO SEE FLY-OUT LABELS!</center>"})<br />
<br />
-- create 15 labels and store them in a table <br />
table_for_flyout_labels = {}<br />
for i=1,15 do<br />
-- options to layoutDir are the direction the window should go (R for right, L for left, T for top, B for bottom), followed by how the nested labels should be oriented (V for vertical or H for horizontal). So "BH" here means it'll go on the bottom of the label, while expanding horizontally<br />
table_for_flyout_labels[i] = mainlabel:addChild({name="test"..tostring(i),height=30,width=70, layoutDir="BH", flyOut=true, message="test"..tostring(i)})<br />
<br />
table_for_flyout_labels[i]:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px;]])<br />
end<br />
<br />
-- make the test5 label look a bit special as it has got a surprise<br />
table_for_flyout_labels[5]:echo("Hover here")<br />
<br />
-- add even more nested labels to the 5th label!<br />
even_more_flyout_labels = {}<br />
for i=1,60 do<br />
-- here, the layout will be to the right of it, while expanding vertically<br />
even_more_flyout_labels[i]=table_for_flyout_labels[5]:addChild({name="hover label "..tostring(i),height=30,width=100, layoutDir="RV", flyOut=true, message="label "..tostring(i)})<br />
even_more_flyout_labels[i]:setClickCallback("testFunc", even_more_flyout_labels[i].name)<br />
even_more_flyout_labels[i]:setStyleSheet([[background-color: grey; border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]])<br />
end<br />
<br />
function testFunc(name)<br />
display(name)<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look something like this: <br />
<br />
[[File:Flyout_labels_demo.png|150px]]<br />
<br />
==== Demo of layouts ====<br />
Here's another demo that explains all of the layout styles quite well:<br />
<syntaxhighlight lang="lua"><br />
local directions = {"R", "L", "T", "B"}<br />
local orientations = {"V", "H"}<br />
local mappings = {R = "right", L = "left", T = "top", B = "bottom", V = "vertical", H = "horizontal"}<br />
<br />
local combinations, combination_labels = {}, {}<br />
for _, direction in pairs(directions) do<br />
for _, orientation in pairs(orientations) do<br />
combinations[#combinations+1] = direction..orientation<br />
end<br />
end<br />
<br />
local function get_foreground_text_colour(r,g,b)<br />
local luminosity = (0.2126 * ((r/255)^2.2)) + (0.7152 * ((g/255)^2.2)) + (0.0722 * ((b /255)^2.2))<br />
if luminosity > 0.5 then<br />
return "black"<br />
else<br />
return "white"<br />
end<br />
end<br />
<br />
local function get_random_colour_rgb()<br />
return math.random(1,255), math.random(1,255), math.random(1,255)<br />
end<br />
<br />
-- create a label with a nestable=true property to say that it can nest labels<br />
all_possible_combinations_label = Geyser.Label:new({name="all_possible_combinations_label", x=0,y="-400",height=50,width=500,<br />
nestable = true, message="<center>Click to see a listing of possible combinations</center>"})<br />
<br />
for i = 1, #combinations do<br />
local combination = combinations[i]<br />
combination_labels[i] = all_possible_combinations_label:addChild({name="combo_"..combination,height=30,width=150, nestable = true, flyOut=true, layoutDir="BH", message="<center>Combination "..combination.."</center>"})<br />
<br />
local r,g,b = get_random_colour_rgb()<br />
local text_colour = get_foreground_text_colour(r,g,b)<br />
<br />
local combination_labels_children = {}<br />
for ii = 1, 3 do<br />
combination_labels_children[ii] = combination_labels[i]:addChild({<br />
name="combo_"..combination.."_"..ii, height = 30, width = 150, layoutDir=combination, flyOut = true,<br />
message = string.format("<center><b>%s</b>%s+<b>%s</b>%s layout</center>", <br />
combination:sub(1,1), mappings[combination:sub(1,1)]:sub(2), combination:sub(2,2), mappings[combination:sub(2,2)]:sub(2)),<br />
fgColor = text_colour})<br />
<br />
combination_labels_children[ii]:setStyleSheet(string.format([[background-color:rgb(%d, %d, %d); border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]], r,g,b))<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look like this:<br />
<br />
[[File:Flyoutlabels-layout-demo.png]]<br />
<br />
=== Geyser.Label right click menu ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
You can create a right click menu for a label just by using the function (assuming your label name is 'myLabel'):<br />
<syntaxhighlight lang="lua"> myLabelːcreateRightClickMenu({MenuItems = menuTable}) -- scroll down for a fuller example with more details </syntaxhighlight><br />
<br />
The menu table comprises of all the items and their names. To create a parent menu just create a nested table of names.<br />
<br />
Example of a menuTable:<br />
<syntaxhighlight lang="lua"> menuTable = {"First Item", "Second Item (Parent)", {"First ChildItem", "Second ChildItem"}, "Third Item"} </syntaxhighlight><br />
<br />
The menu would look like thisː<br />
<br />
[[File:RCDemo1.gif|250px]]<br />
<br />
You can give more constraints to further style and enhance your right click menu.<br />
<br />
==== Style your right click menu ====<br />
Your right click menu has 2 default styles integratedː "light" and "dark" which are defined by the constraint "Style".<br />
<br />
To set a default style just give the constraint Style the preferred value, for exampleː<br />
<syntaxhighlight lang="lua"> Style = "dark" </syntaxhighlight><br />
<br />
To give different levels of your menu different style just add the number of the level to the constraint, for exampleː<br />
<syntaxhighlight lang="lua"> Style2 = "light" -- Gives the second level of your menu the "light" style</syntaxhighlight><br />
<br />
For adding your own stylesheet use the constraint MenuStyle (use the same method as above to define stylesheets for different levels)<br />
<syntaxhighlight lang="lua"> MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]] <br />
-- Gives the second level of your menu this stylesheet</syntaxhighlight><br />
<br />
The same methods are used for defining the format, width and height for the menu item.<br />
<syntaxhighlight lang="lua"> <br />
MenuWidth = 70 -- standard menu width if nothing else is given<br />
MenuWidth2 = 80 -- menu width for the second level <br />
MenuFormat1 = "c10" -- menu format for the first level (format works like any other label echo format, in this case c is center and 10 is the font-size)<br />
MenuHeight = 30<br />
</syntaxhighlight><br />
<br />
==== Set onClick action for your menu item ====<br />
To set an action if your menu item is clicked use the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<syntaxhighlight lang="lua"> <br />
myLabelːsetMenuAction("First Item", function() echo("Clicked on the first item\n") end<br />
myLabelːsetMenuAction("Second Item (Parent).First ChildItem", function() echo("Clicked on the first child item\n") end) -- To set an action to a child item find it by using "Parent.Child" as name (only one parent is needed to be given the parents parent is not needed)<br />
</syntaxhighlight><br />
<br />
==== Access an menu item directly ====<br />
The simplest way to access a menu item directly is by just using the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<br />
For example to change the menu item textː<br />
<syntaxhighlight lang="lua"> <br />
myLabelːfindMenuElement("First Item"):echo([[my first Item]])<br />
</syntaxhighlight><br />
<br />
==== Right click menu example ====<br />
Better then any further explanation is probably this practical example. <br />
<br />
<syntaxhighlight lang="lua"> <br />
-- create the label the right click menu will be in<br />
myRightClickLabel = myRightClickLabel or Geyser.Label:new({<br />
name = "myRightClickLabel", message = "Please right click!", <br />
format = "cb15", x=10, y=10, width ="30%", height = "15%", <br />
color = "purple"})<br />
<br />
-- right click menu creation with custom styleheet on level2 and default "Dark" style <br />
myRightClickLabel:createRightClickMenu({<br />
MenuItems = {"Emergency", "Drink",{"ManaPotion","HealthPotion"}, "Disappear", "Cast",{"Blindness", "Blink"}}, <br />
Style = "Dark", <br />
MenuWidth2 = 80, <br />
MenuFormat1 = "c10",<br />
MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]]<br />
})<br />
<br />
myRightClickLabel:setMenuAction("Emergency", function() <br />
cecho("<red:pink>[Emergency Mode] Run as fast as possible!\n") <br />
send("emergency") <br />
closeAllLevels(myRightClickLabel) -- this can be used to close the right click menu if clicked on this item<br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.ManaPotion", function()<br />
cecho("<blue>Drinking my mana potion.\n") <br />
send("drink mp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.HealthPotion", function() <br />
cecho("<red>Drinking my health potion.\n") <br />
send("drink hp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Disappear", function() <br />
cecho("<grey>Disappearing.. \n") <br />
send("disappear") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blindness", function() <br />
cecho("<light_blue>Casting blindness \n") <br />
send("cast blindness enemy") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blink", function() <br />
cecho("<light_blue>Casting blink \n") <br />
send("cast blink") <br />
end )<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
<br />
[[File:Right click example demo.gif]]<br />
<br />
==== Add right click menu to label with already existing left click action ====<br />
If your label has an already existing left click action you'll have to create the right click menu<br />
"before" creating the labels "setClickCallBack" action and then just put into your labels onClick function<br />
(assuming your label name is 'myLabel' and 'event' is the last parameter of your onClick function)<br />
<br />
<syntaxhighlight lang="lua"> <br />
myLabel:onRightClick(event)<br />
</syntaxhighlight><br />
<br />
=== Geyser name ===<br />
Make sure to give your Geyser Labels, miniconsoles, and userwindows a <code>name</code> - while it'll technically work without one, items will be duplicated when you re-save them if they're lacking a name.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserStyleSheet.html Geyser.StyleSheet]==<br />
<br />
Allows you to create a managed stylesheet to make it easier to set and change properties. Also allows you to inherit properties from another stylesheet, making it easier to manage multiple styles at once.<br />
<br />
=== Basic Usage ===<br />
<br />
Here's an example to get you started. This creates a basic stylesheet to set the background color black and the foreground/text color to green, then applies it to a Geyser Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
local testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = 100,<br />
y = 100,<br />
height = 100,<br />
width = 300,<br />
stylesheet = stylesheet:getCSS(),<br />
})<br />
<br />
-- Alternate method of creating a stylesheet using a table of properties<br />
local stylesheet = Geyser.StyleSheet:new({<br />
['background-color'] = "black",<br />
['color'] = "green",<br />
})<br />
</syntaxhighlight><br />
<br />
=== Getting the CSS string === <br />
<br />
As shown above, you can use getCSS to get the stylesheet as a string.<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getCSS())<br />
--[[<br />
"background-color: black;\ncolor: green;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Including a target ===<br />
<br />
You can include a 'target' for your stylesheet to be applied to, such as QLabel, QPlainTextEdit, etc.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- QPlainTextEdit is useful for styling command lines in particular, to keep the style from bleeding into any associated miniconsole or userwindow.<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
QPlainTextEdit {<br />
background-color: black;<br />
color: green;<br />
}]])<br />
<br />
-- or as an optional third argument. Passing nil for the parent explicitly <br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]], nil, "QPlainTextEdit")<br />
<br />
-- or using the setTarget function after the fact<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
stylesheet:setTarget("QPlainTextEdit")<br />
</syntaxhighlight><br />
<br />
=== Changing a property ===<br />
<br />
Assuming you started with the example above, if you wanted to change the background color to purple you would do the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("background-color", "purple")<br />
testLabel:setStyleSheet(stylesheet:getCSS())<br />
</syntaxhighlight><br />
<br />
Or if you wanted to set the font, you would do:<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", [["Ubuntu Mono"]])<br />
</syntaxhighlight><br />
<br />
Note the way we set the font with the double quotes included in the string, this is because the quotes have to be there in the final stylesheet. You could use single quotes instead of the bracket notation as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", '"Ubuntu Mono"')<br />
</syntaxhighlight><br />
<br />
=== Getting the value of a property ===<br />
<br />
Again assuming you started with the example code above it's as easy as<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:get("color") -- will return "green"<br />
</syntaxhighlight><br />
<br />
=== Getting a table of properties and their values ===<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Setting the properties via table ===<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setStyleTable({<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"',<br />
})<br />
</syntaxhighlight><br />
<br />
=== Resetting the style with a string ===<br />
<br />
Creating a new Geyser.StyleSheet would break any inheritance for stylesheets which had this one as a parent (see below), so if you wish to reset the style via CSS string you should use :setCSS<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setCSS([[<br />
background-color: black;<br />
color: green;<br />
font: "Ubuntu Mono";<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Inheriting properties ===<br />
<br />
As with most things Geyser, just pass the parent in when you create the new stylesheet<br />
<br />
<syntaxhighlight lang="lua"><br />
local childsheet = Geyser.StyleSheet:new("color: blue;", stylesheet)<br />
display(childsheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "blue",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
<br />
display(childsheet:get("background-color")<br />
--"purple"<br />
<br />
-- show only properties set in this stylesheet, without inheritance<br />
display(childsheet:getStyleTable(false))<br />
--[[<br />
{<br />
color = "blue"<br />
}<br />
--]]<br />
<br />
-- can do the same for the CSS string<br />
display(childsheet:getCSS(false))<br />
--[[<br />
"color: blue;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html Geyser.MiniConsole]==<br />
This allows you to spawn a Mudlet miniconsole - unlike labels, these aren't as styleable, but they do format text better. They make a good fit for text-based menus, chat and map capture, and other things.<br />
<br />
Spawning one is very similar to other Geyser elements - paste this into a new script:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x="70%", y="50%",<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="30%", height="50%",<br />
})<br />
</syntaxhighlight><br />
<br />
This'll make you one at the bottom-right of the screen. The miniconsole will have a grey background by default, but you can set it to any color you'd like with [http://www.mudlet.org/geyser/files/geyser/GeyserWindow.html#Geyser.Window:setColor miniconsole:setColor()]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setColor("black") -- give it a nice black background<br />
</syntaxhighlight><br />
<br />
A special dimension property that MiniConsoles have is a character - instead of specifying a miniconsole to be % of a container or a certain number of pixels, you can specify it as a certain number of characters. You do this by using "c" at the end of a number. This way, you can, for example, specify miniconsole to be 10 letters long and 2 lines high:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="70%", y="50%",<br />
wrapAt = 10,<br />
width="10c", height="2c",<br />
})<br />
flatbox:setColor("red")<br />
flatbox:echo("ABCDEFGHIJ") -- that is 10 letters<br />
</syntaxhighlight><br />
<br />
=== Adding text ===<br />
You can use [[Manual:Technical_Manual#echo|echo()]] the same way with a miniconsole to add text as to the usual window:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("hello!")<br />
</syntaxhighlight><br />
<br />
As well as [[Manual:Technical_Manual#cecho|cecho]], [[Manual:Technical_Manual#decho|decho]], or [[Manual:Technical_Manual#hecho|hecho]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:cecho("<green>hey, <blue>colored <red>text!\n")<br />
</syntaxhighlight><br />
<br />
=== Copying lines with color ===<br />
To copy a line over to the miniconsole, as it is from the game with all colors preserved, you can [[Manual:UI_Functions#selectCurrentLine|select]], [[Manual:UI_Functions#copy|copy]], and [[Manual:UI_Functions#appendBuffer|append]] it. For an example, try making a trigger with this as the ''perl regex'' pattern type:<br />
<br />
<syntaxhighlight lang="lua"><br />
^<br />
</syntaxhighlight><br />
<br />
That'll make the trigger go off on every line. Then give it the following script (assumed you have made the HelloWorld miniconsole from earlier):<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
... and you'll see all MUD output duplicated exactly as it is to the miniconsole. Amazing! It's very efficient as well, so you can have many miniconsoles, even in spam, not lag you down.<br />
<br />
=== Clearing the miniconsole ===<br />
Clearing the miniconsole just requires using the following script (assumes you have made the HelloWorld miniconsole from earlier):<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:clear()<br />
</syntaxhighlight><br />
<br />
=== Doing edits in copied lines ===<br />
Sometimes you'll want to edit the line before stuffing it into the miniconsole. For example, if you're making a chat capture, you'd want to condense a really long org name into something that's more space-friendly.<br />
<br />
To do so, you'd use the [[Manual:Technical_Manual#selectString|selectString()]] the text you'd like to modify, [[Manual:Technical_Manual#replace|replace()]] it with a different one:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Your", 1) -- select the word you'd like to replace - in this case, 'Your'<br />
setBgColor(getBgColor()) -- preserve the background color in the replacement<br />
setFgColor(getFgColor()) -- preserve the foreground color in the replacement<br />
replace("Mine") -- replace the selection with the wird 'Mine'<br />
<br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
=== Gagging from the main window ===<br />
If you'd like to gag the line from the main window so it only shows up in your miniconsole, [[Manual:Technical_Manual#deleteLine|delete]] it after moving it over:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=== Clickable menus ===<br />
Using the [[Manual:Technical_Manual#echoLink|echoLink]], [[Manual:Technical_Manual#insertLink|insertLink]] and [[Manual:Technical_Manual#setLink|setLink]] functions, you can turn text into one that reacts on a click. Combined with your power of placing text anywhere on the screen with a miniconsole, you can make menus with options. Here is one such example, where selecting an item causes an echo to happen:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="20%", y="80%",<br />
width="40c", height="4c",<br />
})<br />
flatbox:setColor("red")<br />
clearWindow("flatbox")<br />
<br />
flatbox:cecho("<white:red>Choose one of the following options:\n")<br />
<br />
flatbox:fg("white")<br />
flatbox:bg("red")<br />
<br />
for _, fruit in ipairs{"banana", "apple", "orange"} do<br />
echoLink("flatbox", "* "..fruit:title().."\n", [[echo("You picked ]]..fruit..[[\n")]], "The "..fruit.." option", true)<br />
end<br />
<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
This will produce something like the following:<br />
<br />
[[File:Fruit_menu.png|center]]<br />
<br />
=== Change your miniconsole background image ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
To set a custom background image for your miniconsole, use [https://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html#Geyser.MiniConsole:setBackgroundImage :setBackgroundImage()]:<br />
<syntaxhighlight lang="lua"><br />
miniconsole_withBgImg = Geyser.MiniConsole:new({name = "BackgroundonConsole", x="50%", y="50%", width = "20%", height = "40%"})<br />
miniconsole_withBgImg:setBackgroundImage(":/Mudlet_splashscreen_development.png", "center")<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:decho("<:0,0,0,130> This is a decho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:hecho("#,80000000 This is a hecho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:decho("<:0,0,0> This is a decho test with no transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:hecho("#,000000 This is a hecho test with no transparent background\n")<br />
end<br />
</syntaxhighlight><br />
<br />
=== Enable and use your miniconsole command line ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Every miniconsole has a hidden command line. Enable it with:<br />
<syntaxhighlight lang="lua"><br />
HelloWorldContainer = HelloWorldContainer or Adjustable.Container:new({name="HelloWorldContainer", titleText = "Container with a command line"})<br />
<br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "purple",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, HelloWorldContainer)<br />
<br />
HelloWorld:enableCommandLine()<br />
</syntaxhighlight><br />
<br />
=== Set an action to your miniconsole command line ===<br />
If no action is set to your miniconsole command line the commands are send to the game the same way as for the main command line. Aliases still work as usual, and if you have command echo enabled in preferences, it'll show in both miniconsole and the main window.<br />
<br />
It is also possible to set an action to your command line, this enables you to use the command line as custom text input.<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:enableCommandLine()<br />
local function channelChat(text)<br />
send("chat "..text)<br />
HelloWorld:echo("[chat] " ..text.."\n")<br />
end<br />
<br />
HelloWorld:setCmdAction(channelChat)<br />
</syntaxhighlight><br />
<br />
This will send your miniconsole command line input to the chat channel.<br />
<br />
More complicated/sophisticated actions are possible, setCmdAction works the same way as the Label clickCallback functions - that is, you can pass arguments to it.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html Geyser.Gauge]==<br />
<!--<br />
This is a composite window. Gauge duplicates the functionality of the built in Mudlet gauges, but in a clean and easily extended way. Internally, a Geyser Gauge is a container holding two Labels, front and back, which are initially scaled to fill the entire Gauge container. Hence, a gauge, g, can be given callbacks with the g.front:setClickCallback() method.<br />
<br />
The backgroundColor parameter initially sets the colors of the gauge, but of course the front and back components can be accessed individually as labels for high control over their looks. Gauges can be horizontal or vertical and decrease in value left to right, right to left, down up or up down depending on the value of the orientation parameter.<br />
--><br />
<br />
A Gauge allows you to represent numbers on a scale - and most typically, you've seen it be used as your standard hp/mana/whatever bar. A basic bar is made similarly to other Geyser elements. To set the value on the gauge that it should represent, use the [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] function:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="5%",<br />
})<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
That'll spawn you a pretty basic gauge with a horizontal orientation and a grey colour - and as a test, with a random value.<br />
<br />
[[File:Basic_gauge.png|center]]<br />
<br />
=== Updating a gauge ===<br />
You'd want your gauge to stay in sync with your actual values. To make that happen, you want to call [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] whenever the value that the gauge is tracking changes.<br />
<br />
So for example, if you make a health bar - wherever you get your new health at (be it prompt, gmcp, atcp or whatever), update the gauge as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- theoretical example<br />
current_health, max_health = tonumber(matches[2]), tonumber(matches[3])<br />
<br />
-- update the bar<br />
hp_bar:setValue(current_health, max_health)<br />
</syntaxhighlight><br />
<br />
You can also write down how much health have you got on the bar with:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local hp = math.random(1,100) <br />
hpbar:setValue(current_health, max_health, "<b>"..max_health.."hp</b>")<br />
<br />
-- example using GMCP in IRE games:<br />
hpbar:setValue((100/gmcp.Char.Vitals.maxhp)*gmcp.Char.Vitals.hp,100,gmcp.Char.Vitals.hp)<br />
</syntaxhighlight><br />
<br />
[[File:Hpbar_basic.png|center]]<br />
<br />
=== Styling a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. Combining this with Geyser:Label.setStyleSheet, you can improve the visuals of your gauges by using Qt-supported CSS. The syntax for specifying CSS is a bit different - it requires a semicolon after every property, and is done in the format of ''property name''''':'''''values''''';'''. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here] and you can use [https://build-system.fman.io/qt-designer-download Qt Designer] to create them. Practical example:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #98f041, stop: 0.1 #8cf029, stop: 0.49 #66cc00, stop: 0.5 #52a300, stop: 1 #66cc00);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #78bd33, stop: 0.1 #6ebd20, stop: 0.49 #4c9900, stop: 0.5 #387000, stop: 1 #4c9900);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge.png|center]]<br />
<br />
The same style can be adjusted by colors to red as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f04141, stop: 0.1 #ef2929, stop: 0.49 #cc0000, stop: 0.5 #a40000, stop: 1 #cc0000);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bd3333, stop: 0.1 #bd2020, stop: 0.49 #990000, stop: 0.5 #700000, stop: 1 #990000);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge_red.png|center]]<br />
<br />
=== Updating a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. To make a gauge clickable you can set a ClickCallBack on the top label which is ''mygauge.text'' example: <syntaxhighlight lang="lua">mygauge.text:setClickCallback("functionName", variableToSendToFunctionName)</syntaxhighlight><br><br />
If you would like to have different click events for the top or back of a gauge you can enable clickThrough for the top or ''mygauge.text'' label example<br />
<br />
<syntaxhighlight lang="lua"><br />
mygauge.text:enableClickthrough()<br />
mygauge.front:setClickCallback("functionOne", variableToSendToFunctionOne)<br />
mygauge.back:setClickCallback("functionTwo", variableToSendToFunctionTwo)<br />
</syntaxhighlight><br />
<br />
<br />
=== Tooltips on gauges ===<br />
Tooltips are available since Mudlet 4.6 as explained in above section [[#Adding_a_tooltip_to_a_label]], and as gauges are really only made up of labels as well, you could add a tooltip then by just using <syntaxhighlight lang="lua">mygauge.text:setToolTip("This is the gauge's tooltip", "10")</syntaxhighlight> the same as it's handled for clickback.<br />
<br />
== HBox/VBox ==<br />
<br />
These are special types of containers. Every window in these is horizontally or vertically aligned in the order they were added.<br />
<br />
{{MudletVersion|2.0}}<br />
<br />
== Geyser.UserWindow ==<br />
Allows you to use Mudlets UserWindows within Geyser, which allows you to use all the functionality of a MiniConsole in its basic form.<br />
The big advantage is the possibility to add other Geyser Elements like Labels, MiniConsole, Gauges, Mappers to the UserWindow.<br />
The UserWindow then can act as container for those elements with all the perks of dynamic resizing or any other Geyser functionality.<br />
<br />
{{MudletVersion|4.6.1}}<br />
<br />
===Basic floating userwindow ===<br />
This will create a movable floating userwindow.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "TestUserWindow",<br />
titleText ="My Test UserWindow", -- only available since Mudlet 4.8+<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
</syntaxhighlight><br />
<br />
You can change the title of the userwindow by using the parameger titleText and the functions below (as of Mudlet 4.8+)ː<br />
<br />
To set a new title after creation useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setTitle("My new title Text")<br />
</syntaxhighlight><br />
<br />
To revert to the standard title useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:resetTitle()<br />
</syntaxhighlight><br />
<br />
To '''save the position''' of the userwindow - say in case you've dragged it onto another monitor and would like it to stay there when you restart Mudlet - use [[Manual:UI_Functions#saveWindowLayout|saveWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
saveWindowLayout()<br />
</syntaxhighlight><br />
<br />
To restore it afterwards, use [[Manual:UI_Functions#loadWindowLayout|loadWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create your userwindows first with Geyser.UserWindow:new<br />
-- then restore them to the positions they were at:<br />
loadWindowLayout()<br />
</syntaxhighlight><br />
<br />
=== Docked UserWindow ===<br />
To create the window docked at the right side,<br />
set the variable docked (at creation of the container) to true.<br />
Be aware that with this variable set to true the position and the size at creation of the userwindow will be ignored.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true<br />
<br />
})<br />
</syntaxhighlight><br />
<br />
Since Mudlet 4.8+ it is also possible to choose the docking Position of the UserWindow at creation and by function withː<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true,<br />
dockPosition = "top" -- Possible dockPositions are left "l", right "r", top "t", bottom "b" and floating "f" <br />
})<br />
</syntaxhighlight><br />
<br />
To change it for a already created UserWindow use the function setDockPosition(dockPosition) likeː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setDockPosition("left")<br />
</syntaxhighlight><br />
<br />
=== Disable/enable UserWindow autoDock ===<br />
{{note}} available in Mudlet 4.8+<br />
<br />
The auto docking feature can be really annoying at times. To disable it use the functionsː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:disableAutoDock() -- disables autoDock. Docking still possible with ːsetDockPosition<br />
testuserwindow:enableAutoDock() -- reenables autoDock<br />
</syntaxhighlight><br />
<br />
=== Styling the UserWindow border and title area ===<br />
{{note}} available in Mudlet 4.10+ and Linux only<br />
<br />
Geyser.UserWindows can accept a stylesheet to change the appearance of the border and title area and make<br />
the UserWindow look more appealing. This unfortunately only works in Linux, as in macOS and Windows, it is the OS theme that is used here. <br />
<br />
<syntaxhighlight lang="lua"><br />
myUserWindow = myUserWindow or Geyser.UserWindow:new({<br />
name = "myUserWindow", titleText = "myUserWindow", autoDock = false<br />
})<br />
<br />
myUserWindow:setStyleSheet( <br />
[[QDockWidget{<br />
border: 1px solid green; /* UserWindow border style */<br />
font: bold 15pt "Arial"; /* Font of the titleBar */<br />
color: rgb(0,0,150); /* Font color */<br />
}<br />
<br />
QDockWidget::title{ <br />
background-color: rgb(0,255,150); /* TitleBar color */<br />
border: 2px solid red; /* TitleBar border */<br />
border-radius: 2px; /* TitleBar border radius */<br />
text-align: center; /* alignment of the titleText */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
[[File:UserWindowStyleSheet.png]]<br />
<br />
=== UserWindow as Container ===<br />
This is the feature which shows the versatile nature of Geyser.UserWindows.<br />
The UserWindow act as container and is at that possible to dynamically resize the containing Geyser Elments.<br />
Put a label in the UserWindow resize it as rectangle.<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "ParentTestUserWindow",<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
<br />
testuserwindow:setColor("dark_green") -- give the userwindow a bit of color <br />
<br />
labelinuserw = Geyser.Label:new({<br />
name = "LabelinUserWindow",<br />
x=20, y=20,<br />
width = -20, height = -20,<br />
color="light_blue", fontSize=20,<br />
},testuserwindow)<br />
<br />
labelinuserw:echo("This is a label in an userwindow", "black", "c")<br />
</syntaxhighlight><br />
[[File:LabelInUserWindow.png]]<br />
<br />
The same way you are able to add your favorite Geyser Application (like tabbed chat, animated timers, gauges) to an UserWindow.<br />
<br />
Note that you don't need to add MiniConsoles to a UserWindow - as UserWindows already have them built-in.<br />
<br />
[[File:Tabbedchatinuserwindow.png]]<br />
<br />
== Geyser.CommandLine ==<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Allows you to create your custom command lines which can resize/move like any other Geyser object.<br />
<br />
If you just need a command line which is integrated in a miniconsole or userwindow, check out [[Manual:Geyser#Enable and use your miniconsole command line|:enableCommandLine()]].<br />
<br />
=== Creating a Geyser.CommandLine ===<br />
An example to get you startedː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine = myCommandLine or Geyser.CommandLine:new({<br />
name = "myCommandLine", <br />
x = "-20%", y = -40, <br />
width = "20%", height = 40,<br />
stylesheet = "border: 1px solid silver;"<br />
})<br />
</syntaxhighlight><br />
This creates a new command line in the right bottom of your screen.<br />
<br />
=== Bind action to your command line input ===<br />
If you use your previously created command line, any command will just be send to the game, after having been checked for aliases.<br />
<br />
To react to any input in a custom manner, we can set an action to the command line and use the input as parameter.<br />
<br />
Example of a command line changing the background color of your main console (assumes you have created "myCommandLine" from earlier): <br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setAction(<br />
function(commandLineInput)<br />
r, g, b = Geyser.Color.parse(commandLineInput) -- gets the r, g, b values of the color you input to the command line<br />
if b then -- checks if the color is valid<br />
setBackgroundColor(r, g, b)<br />
else<br />
echo("\n"..commandLineInput.." is not a valid color. Try again.")<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
=== Styling a command line ===<br />
You can style your Geyser command line by using Qt-supported CSS. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here].<br />
<br />
Practical example (assuming "myCommandLine" is created)ː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setStyleSheet([[<br />
QPlainTextEdit{ /* QPlainTextEdit is used to prevent the styleSheet bleeding to the right click menu*/<br />
border: 1px solid silver; /* Command line border style */<br />
background-color: rgb(0,255,150); /* Command line background color */<br />
font: bold 12pt "Arial"; /* Font and font-size of your command line */<br />
color: rgb(0,0,150); /* Command line text color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Create an extra command line in Mudlet ===<br />
If your goal is to just have an extra command/input line - say, for role-playing purposes: copy/paste the example below into a new script in Mudletː<br />
<br />
<syntaxhighlight lang="lua"><br />
inputContainer = inputContainer or Adjustable.Container:new({<br />
x = 0, y = "-4c", <br />
name = "InputContainer", padding = 2, <br />
width = "100%", height = "4c", <br />
autoLoad = false<br />
})<br />
<br />
extraCmdLine = extraCmdLine or Geyser.CommandLine:new({<br />
name = "extraCmdLine", <br />
x = 0, y = 0, width = "100%", height = "100%"<br />
}, inputContainer)<br />
<br />
inputContainer:attachToBorder("bottom")<br />
</syntaxhighlight><br />
<br />
This will look likeː <br />
<br />
[[File:AdditionalCommandLine.png|extra command line]]<br />
<br />
== Adjustable.Container ==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
Adjustable Containers are a new "GeyserClass" which act as containers for Geyser elements, but with more flexible and user configurable features. They are referred to as "adjustable" because they can be minimized, loaded, saved, moved, adjusted in size with the mouse pointer, and attached to borders. <br />
<br />
A brief video of [https://www.youtube.com/watch?v=GT2ScizuM48&feature=youtu.be Introduction to Adjustable Containers] is available.<br />
<br />
=== Creating an Adjustable.Container ===<br />
An Adjustable.Container is created just like any other Geyser Object. For example, we might experiment with creating a new Adjustable.Container by running the following line of lua code:<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
</syntaxhighlight><br />
This will create a new Adjustable.Container with the name ''testContainer''. Specifying the adjustable container's name is important for saving. Defining a variable, such as ''testCon'' in our above example, allows functions to be used with the Adjustable.Container.<br />
<br />
Our newly created Adjustable.Container may be used the same way as any other Geyser.Container might. For example, let's put a Geyser.Label in our new testContainer:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
testLabel = Geyser.Label:new({name="myTestLabel", x=0, y=0, height="100%", width="100%", color="green"},testCon)<br />
</syntaxhighlight><br />
<br />
The above code creates a new, green-colored Geyser.Label in the ''testCon'' adjustable.container as shown below:<br />
<br />
[[File:GreenLabelinAdjustableContainer.png]]<br />
<br />
You can also create one for miniconsole:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer = miniconsoleContainer or Adjustable.Container:new({name="miniconsoleContainer"})<br />
myMiniconsole = Geyser.MiniConsole:new({<br />
name="myMiniconsole",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, miniconsoleContainer)<br />
<br />
myMiniconsole:echo("Hello!\n")<br />
</syntaxhighlight><br />
<br />
That will give you:<br />
<br />
[[File:Adjustable container miniconsole.png]]<br />
<br />
=== Key Functions ===<br />
A listing of key functions for the Adjustable.Container module can be found hereː https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html<br />
<br />
To make the Adjustable Container show on screen use the following:<syntaxhighlight lang="lua"><br />
testCon:show() --will cause the Adjustable Container to show if not showing<br />
</syntaxhighlight><br />
<br />
===<div id="valid constraints"> Valid Constraints</div>===<br />
Adjustable Container constraints and their default values can be found at [https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html#Adjustable.Container:new].<br />
<br />
These are in addition to the standard Geyser.Container constraints.<br />
<br />
=== Change Title Text ===<br />
To specify the title text of a new container, use the constraint <code>titleText</code> in the constructor (see [[Manual:Geyser#valid constraints|valid constraints]]).<br />
<br />
To change the title text after a container has already been created, use <code>setTitle</code>. Continuing from the previous example, the title for an existing container named "testCon" might be adjusted in a number of ways: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Title") -- changes the container's title to "Title"<br />
</syntaxhighlight><br />
<br />
A container's title text defaults to the color green, but this can also be adjusted by using <code>setTitle</code>: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Red Title Test","red") -- changes the container's title text to "Red Title Test" and displays the text in the specified color "red".<br />
</syntaxhighlight><br />
<br />
To restore a container's default title text, <code>setTitle</code> is issued without any specified title or color: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle() -- resets the container's title text<br />
</syntaxhighlight><br />
<br />
=== AutoSave and AutoLoad ===<br />
The following Adjustable.Container settings can be saved and loadedː<br />
<br />
<code>x</code>, <code>y</code>, <code>height</code>, <code>width</code>, <code>minimized</code>, <code>locked</code>, <code>lock Style</code>, <code>padding</code>, and <code>hidden</code>.<br />
<br />
These settings will be automatically saved when the Mudlet profile is closed, and automatically loaded when a previous Adjustable.Container is created within the corresponding profile.<br />
<br />
To prevent automatic saving and/or loading of these settings, the <code>autoLoad</code> and <code>autoSave</code> constraints can be included in the constructor. For example, the following code will prevent the settings of the ''testCon2'' Adjustable.Container from being loaded upon creation:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", autoLoad=false})<br />
</syntaxhighlight><br />
<br />
To also prevent the ''testCon2'' Adjustable.Container from automatically saving its settings when the Mudlet profile is closed, the <code>autoSave=false</code> constraint would be added at creation as follows:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCont2 = testCont2 or Adjustable.Container:new({name="testCont2", autoLoad=false, autoSave=false})<br />
</syntaxhighlight><br />
<br />
Automatic saving can also be deactivated after an Adjustable.Container has been created, by invoking <code>testCont:disableAutoSave()</code><br />
<br />
Note that even with autoSave and autoLoad disabled, it is still possible to save and load manually through the right-click menu and/or by using <code>testCont:save()</code> or <code>testCont:load()</code> in a script.<br />
<br />
To save/load all your containers manually at the same time, we use <code>Adjustable.Container:saveAll()</code> and/or <code>Adjustable.Container:loadAll()</code><br />
<br />
=== "All" Functions ===<br />
The following functions affect all Adjustable Containers at the same time.<br />
<br />
{{note}} You must create the Adjustable Containers before these functions will have an effect.<br />
<br />
<code>Adjustable.Container.loadAll()</code> loads all the settings from your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container.saveAll()</code> saves all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:showAll()</code> shows all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:doAll(myfunc)</code> creates a function that will affect all your Adjustable Containers. For example:<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:hide() end) -- hides all your adjustable containers<br />
</syntaxhighlight><br />
<br />
=== Custom Save/Load Directories and Slots ===<br />
{{note}} available in Mudlet 4.10+<br />
==== Custom Directory ====<br />
If no option set your Adjustable.Container saves/loads its settings in your profile directory.<br />
<br />
It is possible to change the default save/load directory by using for example a different defaultDir as constraint when creating your Adjustable.Container.<br />
<br />
{{note}} This can be especially useful for authors of packages which want to ship their own save files.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = "/home/edru/MyAdjustableContainerSettings/"}) -- noteː the directory will be created if it doesn't exist<br />
</syntaxhighlight><br />
<br />
Example for save files in a package (assuming the packagename is "AdjustableContainerTest" and the settings are saved in "myPersonalAdjSettings"<br />
<syntaxhighlight lang="lua"><br />
local packageName = "AdjustableContainerTest"<br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = string.format("%s/%s/myPersonalAdjSettings/", getMudletHomeDir(), packageName)})<br />
</syntaxhighlight><br />
<br />
==== Custom Slot ====<br />
Another useful addition is to choose a save slot depending on the situation or to reset to a default save state.<br />
<br />
To save to a different slot just add it as parameter when saving.<br />
<br />
For exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːsave("combatSlot")<br />
</syntaxhighlight><br />
<br />
To then load from that slot just useː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːload("combatSlot")<br />
</syntaxhighlight><br />
<br />
{{note}} This also allows package/module authors to choose a "default" save setting to reset to.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
Adjustable.ContainerːsaveAll("default") -- saves the default settings<br />
<br />
-- to reset to default settings then just use<br />
Adjustable.ContainerːloadAll("default") -- loads the default settings<br />
</syntaxhighlight><br />
<br />
This can also be used to change the whole GUI on the fly.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
-- in combat situation use combat settings<br />
Adjustable.ContainerːloadAll("combat") -- loads special combat settings<br />
-- combat is over <br />
Adjustable.ContainerːloadAll("default") --reverts to the default settings<br />
</syntaxhighlight><br />
<br />
==== Delete Save File ====<br />
To delete the save file just useː<br />
<syntaxhighlight lang="lua"><br />
testCont2:deleteSaveFile()<br />
</syntaxhighlight><br />
<br />
===Right-click menu===<br />
Your Adjustable Container has also integrated a right-click menu with the main key functions for easier usability:<br />
<br />
[[File:AdjustableContainerRightClickMenu.png]]<br />
<br />
The right-click menu automatically shows you the possible positions to attach to (top, right, bottom, or left) when it's near one of them. For example, to attach a window to the right of the screen, drag it over to the right - and then the 'Attach to - right' will appear as an option:<br />
<br />
[[File:Adjustable Container - attach to right.png]]<br />
<br />
It also shows the lockstyle selection, which allows you to choose what happens when you press <code>Lock</code>, with 4 lockstyles available by default:<br />
<br />
* standard: this is the default lockstyle, with a small margin on top to keep the right click menu usable.<br />
* light: only hides the min/restore and close labels. Borders and margin are not affected.<br />
* full: the container gets fully locked without any margin left for the right click menu.<br />
* border: keeps the borders of the container visible while locked.<br />
<br />
From Mudlet 4.10+ on it is also possible to change your right-click menu style to dark mode by<br />
<br />
<syntaxhighlight lang="lua"><br />
myAdjustableContainer:changeMenuStyle("dark") -- possible menu styles are "dark" or "light"<br />
</syntaxhighlight><br />
<br />
=== Create a Custom Menu with Custom Items ===<br />
To create a new menu element in your right click menu called "Custom" and add an item to it use:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newCustomItem(name, func)<br />
-- for example<br />
testcontainer:newCustomItem("Hello world", function(self) echo("Hello world\n") self:flash() end)<br />
-- this will write "Hello world" to the main console and flashes your container.<br />
</syntaxhighlight><br />
<br />
=== Add new LockStyles ===<br />
For more advanced users it's possible to add a new Lockstyles by:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newLockStyle(name, func)<br />
-- for example<br />
testcontainer:newLockStyle("NewLockStyle", function(self) self.Inside:move(40, 40) self.Inside:resize(-40,-40) self:setTitle("") end)<br />
</syntaxhighlight><br />
<br />
=== Change Adjustable Container Style ===<br />
Additionally to the standard container constraints Adjustable Containers allow you to change at creation: the internal Label style, the menu style, min/close buttons, the menu text, title text... <br />
<br />
( see [[Manual:Geyser#valid constraints|valid constraints]])<br />
An example of a Adjustable Container with different style.<br />
<syntaxhighlight lang="lua"><br />
testCont =<br />
testCont or<br />
Adjustable.Container:new(<br />
{<br />
name = "TestNewStyleContainer",<br />
adjLabelstyle = "background-color:rgba(220,220,220,100%); border: 5px groove grey;",<br />
buttonstyle=[[<br />
QLabel{ border-radius: 7px; background-color: rgba(140,140,140,100%);}<br />
QLabel::hover{ background-color: rgba(160,160,160,50%);}<br />
]],<br />
buttonFontSize = 10,<br />
buttonsize = 20,<br />
titleText = "My new Style",<br />
titleTxtColor = "black",<br />
padding = 15,<br />
}<br />
)<br />
</syntaxhighlight><br />
This code creates a container which looks like this:<br />
<br />
[[File:NewStyleAdjustableContainer.png|Adjustable Container with different style]]<br />
<br />
<br />
=== Attach your Adjustable Container to a Border ===<br />
The simplest way to attach your container to a border is to move your container near the border you want it to attach and use the <br />
right click menu <code> Attach to:</code><br />
<br />
There is also the function <code> TestCont:attachToBorder("right") -- attach TestCont to the right border </code><br />
<br />
To change the margin between container and border use the constraint <code> attachedMargin </code > or the function <code> TestContːsetBorderMargin(10) -- 10 is the margin in px </code><br />
<br />
{{note}} The border is set in percentages and adjusts with screen-size<br />
<br />
=== Create a moveable border frame ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Adjustable Container can be connected to a border and therefore act like a frame.<br />
<br />
This only works if your container is attached to a specific border and the border to connect to has also at least one container attached to it.<br />
Use the function <code>connectToBorder</code><br />
<br />
<syntaxhighlight lang="lua"><br />
TestCont:connectToBorder("left") -- possible borders are "top", "bottom", "right", "left"<br />
</syntaxhighlight><br />
<br />
Minimizing automatically disconnects from a border. Another way is to use the function <code>disconnect</code>.<br />
<br />
{{note}}Connected container are still resizable even if locked.<br />
<br />
If you like to do everything with your right click menu there is the function<br />
<br />
<syntaxhighlight lang="lua"><br />
TestContːaddConnectMenu()<br />
</syntaxhighlight><br />
If you want to add the connect menu items to all Adjustable Containers just<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:addConnectMenu() end)<br />
</syntaxhighlight><br />
<br />
There is also a brief video of how to [https://www.youtube.com/watch?v=Ex-q5zAEfpc connect your Adjustable Container] available.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
GUI = GUI or {}<br />
<br />
GUI.top = Adjustable.Container:new({name = "top", y="0%", height = "10%", autoLoad = false})<br />
GUI.bottom = Adjustable.Container:new({name = "bottom", height = "20%", y = "-20%", autoLoad = false})<br />
GUI.right = Adjustable.Container:new({name = "right", y = "0%", height = "100%", x = "-20%", width = "20%", autoLoad = false})<br />
GUI.left = Adjustable.Container:new({name = "left", x = "0%", y = "0%", height = "100%", width = "20%", autoLoad = false})<br />
<br />
<br />
GUI.top:attachToBorder("top")<br />
GUI.bottom:attachToBorder("bottom")<br />
GUI.left:attachToBorder("left")<br />
GUI.right:attachToBorder("right")<br />
<br />
GUI.top:connectToBorder("left")<br />
GUI.top:connectToBorder("right")<br />
GUI.bottom:connectToBorder("left")<br />
GUI.bottom:connectToBorder("right")<br />
</syntaxhighlight><br />
Here's what the frame will look like:<br />
<br />
[[File:Adjustable_frame.gif]]<br />
<br />
=== Add a scrollable box ===<br />
{{note}} available in Mudlet 4.15+<br />
<br />
To add a scrollable box to an adjustable label, try the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
ScrollContainer = ScrollContainer or Adjustable.Container:new({name = "ScrollContainer"})<br />
ContainerBox = ContainerBox or Geyser.ScrollBox:new({name = "ContainerBox", x = 0, y = 0, height = "100%", width = "100%"}, ScrollContainer)</syntaxhighlight><br />
<br />
[[File:Scrollbox-in-container.png|thumb|center]]<br />
<br />
==Change Container==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
With this command it is possible to change an elements or even a containers location to that from another container.<br />
For example:<br />
<syntaxhighlight lang="lua"><br />
mycontainerone:changeContainer(mycontainertwo)<br />
--puts container one into container two which means container two will be the parent of container one<br />
</syntaxhighlight><br />
It is also possible to change to a container which is not located on the main window:<br />
<syntaxhighlight lang="lua"><br />
myEmco:changeContainer(emco_userwindow)<br />
--puts my tabbed chat Emco into my userwindow<br />
--to put it back to the main window change to a container located on the main window<br />
myEmco:changeContainer(mymainwindow_container)<br />
--or if it the element wasn't in a container use the main Geyser Root container called Geyser<br />
myEmco:changeContainer(Geyser)<br />
</syntaxhighlight><br />
<br />
==Geyser.Mapper==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
It‘s possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation use: (this will create a map window docked at the left corner)<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are "left", "right", "top", "bottom", and "floating".<br><br />
To change the dockPosition after creation use:<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget:setDockPosition("floating")<br />
-- this will change myMapWidget dockPosition to floating <br />
</syntaxhighlight><br />
<br />
= Tutorial =<br />
Note: This tutorial assumes you know how scripts in Mudlet work. If not then you should look at the manual first. Also it only shows how Geyser basically works and explains Geysers special windows. It wont go into detail about the windows that where already in Mudlet.<br />
<br />
=== Hello World ===<br />
Let's start with something simple. A Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_1.png]]<br />
<br />
This code creates a blank Label with a size of 200x50 at a position of 50 points horizontal and vertical from its parent window - which is the main window since we didn't specify any.<br />
<br />
You can manipulate the Label through the normal functions but Geyser.Label:new() returns an object which can be used to manipulate the label directly. So you should store it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local HelloWorld = Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
Then you can, for example print a text on it:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_2.png]]<br />
<br />
You can put a format parameter so that the text is, for example, centered.<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_3.png]]<br />
<br />
The second parameter is the color. We set it to nil which means the labels foreground color will be used.<br />
<br />
The color parameter either accepts a string ("red"), a hex value("#FF0000" or "0xFF0000" or "|cFF0000"), or a decimal value "&lt;255,0,0&gt;"<br />
<br />
Example:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", "red", "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
{{note}} This will automatically set the foreground color, so any echo, without the color parameter set, after that will use the same color.<br />
<br />
You can also set the foreground color with the setFgColor method:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setFgColor("red")<br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
=== Containers ===<br />
<br />
Containers are windows that can contain other windows. Actually, since all other Geyser windows subclass container, every window can do that. But containers do not have any visible content by themselves. <br />
<br />
Let's show that by an example:<br />
<syntaxhighlight lang="lua"><br />
local container = Geyser.Container:new({<br />
name="container",<br />
x=50, y=50,<br />
width=250, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
This will create a container, but if you look at the screen you will see nothing at the positon.<br />
There is a way to make containers visible though:<br />
<syntaxhighlight lang="lua"><br />
container:flash()<br />
</syntaxhighlight><br />
<br />
This will flash the container for a short period of time.<br />
<br />
[[Image:Geyser_Container_1.png]]<br />
<br />
flash() accepts a number as paremeter which defines the time, in seconds, the flash is shown.<br />
<br />
Now, that the container is created, you can add other windows to it. There are 2 ways:<br />
<br />
Directly when creating the window:<br />
<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
},<br />
container)<br />
container_label:echo("This is a label in a container", nil, "c")<br />
</syntaxhighlight><br />
<br />
Later, after the window was created<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
})<br />
container_label:echo("This is a label in a container", nil, "c")<br />
container:add(container_label)<br />
</syntaxhighlight><br />
<br />
Both will lead to the same outcome.<br />
<br />
[[Image:Geyser_Container_2.png]]<br />
<br />
Note that we gave a width and height of "100%" to the constructor of the label. This means that the label will take 100% of the containers width and height. If values are given in percent they will even resize with its parent:<br />
<br />
<syntaxhighlight lang="lua"><br />
container:resize(325, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_3.png]]<br />
<br />
The first parameter is the width, the second the height. If the value is nil the current value is used.<br />
<br />
As said in the "Hello World" tutorial the position is relative to its parent window. That's why we could set both x and y to 0 and it is at the position we wanted - the position of the container.<br />
<br />
When we now move the container the label moves with it:<br />
<syntaxhighlight lang="lua"><br />
container:move(400, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_4.png]]<br />
<br />
The first parameter is the x-, the second the y-position. If the value is nil the current value is used.<br />
<br />
=== VBox and HBox ===<br />
<br />
The VBox and HBox classes are special Containers.<br />
They will automatically align its containing windows vertically or horizontally, respectively, in the order they where added to them.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local HBox = Geyser.HBox:new({<br />
name="HBox",<br />
x=0, y=0,<br />
width=400, height=30,<br />
})<br />
<br />
</syntaxhighlight><br />
<br />
Like containers you won't see them by themselves.<br />
<br />
Adding children works like with containers<br />
<syntaxhighlight lang="lua"><br />
<br />
local label1 = Geyser.Label:new({<br />
name="Label1",<br />
},<br />
HBox)<br />
label1:echo("Label 1", "black", "c")<br />
label1:setColor(255, 0, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_1.png]]<br />
<br />
We didn't set any position or size, but the label gets the same size as the HBox.<br />
<br />
If we add another window:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label2 = Geyser.Label:new({<br />
name="Label2",<br />
},<br />
HBox)<br />
label2:echo("Label 2", "black", "c")<br />
label2:setColor(0, 255, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_2.png]]<br />
<br />
the size will be divided equally between them!<br />
<br />
What if you want a child that takes more or less space than the others?<br />
That's possible too:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label3 = Geyser.Label:new({<br />
name="Label3",<br />
h_stretch_factor=2.0,<br />
},<br />
HBox)<br />
label3:echo("Label 3", nil, "c")<br />
label3:setColor(0, 0, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_3.png]]<br />
<br />
As you can see, Label 3 takes the same space as Label 1 and 2 Together. <br />
That's because we supplied a horizontal stretch factor with "h_stretch_factor=2.0"<br />
<br />
This works also with a vertical stretch factor, just replace "h_stretch_factor" with "v_stretch_factor"<br />
<br />
Now you may have windows that should not be stretched at all.<br />
To accomplish this you have to set the horizontal and/or vertical policy:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local label4 = Geyser.Label:new({<br />
name="Label4",<br />
width="13%",<br />
h_policy=Geyser.Fixed,<br />
},<br />
HBox)<br />
label4:echo("Label 4", "black", "c")<br />
label4:setColor(0, 255, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_4.png]]<br />
<br />
Possible values for the policies are Geyser.Fixed and Geyser.Dynamic (which is the default). They can also be applied to VBox and HBox in exactly the same way.<br />
<br />
Note that, like in the example above, the label will retain relative values (like percent) if used.<br />
<br />
The VBox works like the HBox, only that the child windows are aligned vertically.<br />
<br />
= Walkthroughs =<br />
Here are a few walkthroughs that will show you how to combine Geyser elements to create some simple GUI widgets.<br />
<br />
===Create a Clickable Compass===<br />
[[File: compass.png]]<br />
The following will walk you through the process of creating your own clickable compass using the Geyser framework.<br />
====Setup the image files====<br />
The compass requires a handful of images to work properly. You can find them here: https://www.dropbox.com/sh/53l7xrn4ds35wnq/WpWOziVKmH <br><br />
Download each image and place it in your profile folder. You can find your profile folder with getMudletHomeDir()<br><br />
If you're using Mudlet 2.1+ you can enter '''lua getMudletHomeDir()''' from the command line to return the profile folder path on your computer.<br />
<br />
====Create a new script====<br />
Script Name: '''''compass.resize'''''<br><br />
Registered Event Handlers: '''''sysWindowResizeEvent'''''<p><br />
Every snippet of code will be placed within this script.<br />
====Store the screen size====<br />
We'll want to store the screen size in some local variables so they can be easily referenced to later on.<br />
<syntaxhighlight lang="lua">local mw, mh = getMainWindowSize()</syntaxhighlight><br />
<br />
====Create a global table or namespace====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''compass''''' and everything we make from here on out will be stored within the compass table. We'll also add a few values to it: dirs and ratio. '''''compass.dirs''''' will store each direction while '''''compass.ratio''''' will store the ratio of our screen size so you can 'square up' your compass.<br />
<syntaxhighlight lang="lua">compass = compass or {<br />
dirs = {"nw","n","ne","w","center","e","sw","s","se"},<br />
ratio = mw / mh<br />
}</syntaxhighlight><br />
<br />
====Create the parent label====<br />
[[File: grey.png|thumbnail]]<br />
The 'parent label' refers to the label on the bottom layer. The entire compass will be created within this label. It's container is '''main''' for it's parent is the main window.<br />
<syntaxhighlight lang="lua">compass.back = Geyser.Label:new({<br />
name = "compass.back",<br />
x = "25%",<br />
y = "25%",<br />
width = "10%",<br />
height = "10%",<br />
},main)</syntaxhighlight><br />
<br />
====Set the parent label stylesheet====<br />
[[File: blue.png|thumbnail]]<br />
This will create the blue sphere that makes up most of the compass. The background color is a radial gradient that goes from a deep blue to a brighter shade. The border radius rounds the edges. When the radius is exactly half of the label width it forms a circle. The arrows of the compass actually protrude from the sphere so we give it a margin to suck it in a bit for this effect.<br />
<syntaxhighlight lang="lua">compass.back:setStyleSheet([[<br />
background-color: QRadialGradient(cx:.3,cy:1,radius:1,stop:0 rgb(0,0,50),stop:.5 rgb(0,0,100),stop:1 rgb(0,0,255));<br />
border-radius: ]]..tostring(compass.back:get_width()/2-14)..[[px;<br />
margin: 10px;<br />
]])</syntaxhighlight><br />
<br />
====Create a 3x3 grid====<br />
The compass is split into 9 sections. One for each cardinal direction plus an extra space that sits in the center. This 3x3 grid is created by 3 VBoxes that sit within a single HBox (or vice versa but I flipped a coin and this is what it gave me).<br><br />
So first off, we create the HBox. It will be the same size as its parent, ''compass.back''.<br />
<syntaxhighlight lang="lua"> compass.box = Geyser.HBox:new({<br />
name = "compass.box",<br />
x = 0,<br />
y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},compass.back)</syntaxhighlight><br />
Next, we create our 3 VBoxes. You don't need to specify position or size because these are placed within ''compass.box'', an HBox.<br />
<syntaxhighlight lang="lua"> compass.row1 = Geyser.VBox:new({<br />
name = "compass.row1",<br />
},compass.box)<br />
compass.row2 = Geyser.VBox:new({<br />
name = "compass.row2",<br />
},compass.box)<br />
compass.row3 = Geyser.VBox:new({<br />
name = "compass.row3",<br />
},compass.box)</syntaxhighlight><br />
Finally, we add our 9 labels. Take note that they are split up into even groups of 3. Each group is placed into a different ''compass.row#''<br />
<syntaxhighlight lang="lua"> compass.nw = Geyser.Label:new({<br />
name = "compass.nw",<br />
},compass.row1)<br />
<br />
compass.w = Geyser.Label:new({<br />
name = "compass.w",<br />
},compass.row1)<br />
<br />
compass.sw = Geyser.Label:new({<br />
name = "compass.sw",<br />
},compass.row1)<br />
<br />
compass.n = Geyser.Label:new({<br />
name = "compass.n",<br />
},compass.row2)<br />
<br />
compass.center = Geyser.Label:new({<br />
name = "compass.center",<br />
},compass.row2)<br />
<br />
compass.s = Geyser.Label:new({<br />
name = "compass.s",<br />
},compass.row2)<br />
<br />
compass.ne = Geyser.Label:new({<br />
name = "compass.ne",<br />
},compass.row3)<br />
<br />
compass.e = Geyser.Label:new({<br />
name = "compass.e",<br />
},compass.row3)<br />
<br />
compass.se = Geyser.Label:new({<br />
name = "compass.se",<br />
},compass.row3)</syntaxhighlight><br />
====Create a callback function====<br />
We'll want our compass to head in the direction of the arrow we're clicking. This is where we specify so. When the arrow is clicked, this function will be ran with the arrow direction as the argument.<br />
<syntaxhighlight lang="lua">function compass.click(name)<br />
send(name)<br />
end</syntaxhighlight><br />
====Create the hover functions====<br />
We want our arrows to turn yellow when we hover over them. We do so by simply resetting the label's stylesheet and changing the border image. Don't forget to include the margin as we still want that.<br />
<syntaxhighlight lang="lua">function compass.onEnter(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[hover.png");<br />
margin: 5px;<br />
]])<br />
end<br />
<br />
function compass.onLeave(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[.png");<br />
margin: 5px;<br />
]])<br />
end</syntaxhighlight><br />
====Set the stylesheets in the grid====<br />
[[File: Sample.png|thumb]]<br />
Each of the 9 labels need an image of an arrow. Rather than setting each individually, we'll iterate over the ''compass.dirs'' table we made awhile back and add the respective image to each. The names of images are a reflection of the ''compass.dirs'' table. This keeps it consistent and easy to refer to. During the iteration, the callback, setLabelOnEnter and setLabelOnLeave are also set for each label.<br />
<syntaxhighlight lang="lua">for k,v in pairs(compass.dirs) do<br />
compass[v]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..v..[[.png");<br />
margin: 5px;<br />
]])<br />
compass[v]:setClickCallback("compass.click",v)<br />
setLabelOnEnter("compass."..v,"compass.onEnter",v)<br />
setLabelOnLeave("compass."..v,"compass.onLeave",v)<br />
end</syntaxhighlight><br />
<br />
====Resize the compass into a square====<br />
[[File: final.png|thumb]]<br />
Most screen size ratios aren't a perfect 1:1. This will cause a 10% x 10% label to be far from square. By setting our height (the smaller of the two numbers) to our width, we can resize our compass to a near perfect square. This function is also the name of our script because we want it to run each time sysWindowResizeEvent is raised.<br />
<syntaxhighlight lang="lua">function compass.resize()<br />
compass.back:resize(compass.back.width, compass.back:get_width())<br />
end<br />
<br />
compass.resize()</syntaxhighlight><br />
<br />
===Create a Tabbed Window===<br />
[[File: tabwindow.png]]<br />
The following will walk you through the process of creating your own tabbed window using the Geyser framework.<br />
<br />
====Create a new script====<br />
Script Name: '''''Tabbed Window'''''<br><br />
Every snippet of code will be placed within this script.<br />
====Create a global table====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''menu''''' and everything we make from here on out will be stored within the menu table. We'll also add a few values to it: tabs, color1, color2, width, height and current. <br><br />
''''tabs'''' will be a table that stores all our tab names. If we want our tabs to have different names, we alter this table.<br><br />
''''color1'''' and ''''color2'''' will store the colors of our tabbed window. If we want to change the color of our tabbed window, we alter these values.<br><br />
''''width'''' and ''''height'''' will store the size of our tabbed window. If we want to change the size of the tabbed window, we alter these values.<br><br />
''''current'''' keeps track of which tab is selected. We will set this to the first tab in the table by default. We do this outside the initial table creation so we can easily access menu.tabs<br><br />
<syntaxhighlight lang="lua">menu = menu or {<br />
tabs = {"Tab1","Tab2","Tab3","Tab4"},<br />
color1 = "rgb(0,0,70)",<br />
color2 = "rgb(0,0,50)",<br />
width = "20%",<br />
height = "40%",<br />
}<br />
menu.current = menu.current or menu.tabs[1]</syntaxhighlight><br />
<br />
====Create the main container====<br />
Our tabbed window will need a container. This will be the bottom layer. Containers are invisible so no need to set a stylesheet.<br />
<syntaxhighlight lang="lua">menu.container = Geyser.Container:new({<br />
name = "menu.back",<br />
x = "50%", y = "25%",<br />
width = menu.width,<br />
height = menu.height,<br />
},main)</syntaxhighlight><br />
====Create an HBox====<br />
All of our tabs will be evenly spaced. So we'll create an HBox to sit at the top of our container.<br />
<syntaxhighlight lang="lua">menu.header = Geyser.HBox:new({<br />
name = "menu.header",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "10%",<br />
},menu.container)</syntaxhighlight><br />
====Create a label====<br />
This label will serve as a container for each window. It sits right underneath the HBox we just created for the tabs.<br />
<syntaxhighlight lang="lua">menu.footer = Geyser.Label:new({<br />
name = "menu.footer",<br />
x = 0, y = "10%",<br />
width = "100%",<br />
height = "90%",<br />
},menu.container)</syntaxhighlight><br />
We don't want this to be a big grey box at startup, so we'll set the stylesheet to appear like the rest of the windows.<br />
<syntaxhighlight lang="lua"><br />
menu.footer:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])</syntaxhighlight><br />
Each window actually has two labels. One for the light blue background, and another for the dark blue center. This will create that dark blue center.<br />
<syntaxhighlight lang="lua">menu.center = Geyser.Label:new({<br />
name = "menu.center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
menu.center:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])</syntaxhighlight><br />
====Add your tabs and their windows====<br />
Now we'll want to add our tabs and windows. We do this in a single for loop of the ''''menu.tabs'''' table since it holds all our tab names.<br />
<syntaxhighlight lang="lua">for k,v in pairs(menu.tabs) do<br />
</syntaxhighlight><br />
This will create the tabs. Each tab will be named: menu.<tabname>tab<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"] = Geyser.Label:new({<br />
name = "menu."..v.."tab",<br />
},menu.header)<br />
</syntaxhighlight><br />
Here is where we set the tab stylesheet. Each tab has a rounded top, so we set the border-radius of the top-left and top-right to 10px. Each tab has a small space for separation so we give the right and left sides a tiny margin of 1px.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-top-left-radius: 10px;<br />
border-top-right-radius: 10px;<br />
margin-right: 1px;<br />
margin-left: 1px;<br />
]])<br />
</syntaxhighlight><br />
This will display the name of each tab on the tab.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:echo("<center>"..v)<br />
</syntaxhighlight><br />
We need our tabs to do stuff when clicked, so we'll assign it a callback function, '''''menu.click''''', which we'll create later on. Our tab name is the argument.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setClickCallback("menu.click",v)<br />
</syntaxhighlight><br />
Now we create the windows that appear when each tab is clicked. Each window has two labels, one atop the other. The first, which we'll create here, has rounded edges on its bottom.<br />
<syntaxhighlight lang="lua"><br />
menu[v] = Geyser.Label:new({<br />
name = "menu."..v,<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
<br />
menu[v]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
The second label serves as the window's center and has rounded edges on all sides. And a margin of 5px from it's parent, the label we just created. When adding stuff to your windows, this is the label you'll want to use. '''''menu.<tabname>center'''''<br />
<syntaxhighlight lang="lua"><br />
menu[v.."center"] = Geyser.Label:new({<br />
name = "menu."..v.."center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu[v])<br />
</syntaxhighlight><syntaxhighlight lang="lua"><br />
menu[v.."center"]:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])<br />
</syntaxhighlight><br />
Finally, we hide all the windows and end the for loop.<br />
<syntaxhighlight lang="lua"><br />
menu[v]:hide()<br />
end</syntaxhighlight><br />
====Create a callback function====<br />
The last step is to create our callback function for when a tab is clicked. This will hide that tab that is stored in '''''menu.current''''', set menu.current to the clicked tab, and then show the menu.current tab.<br />
<syntaxhighlight lang="lua">function menu.click(tab)<br />
menu[menu.current]:hide()<br />
menu.current = tab<br />
menu[menu.current]:show()<br />
end</syntaxhighlight><br />
====Adding content to your windows====<br />
Add content to '''menu.<tab name>center'''<br />
So if we wanted to display our gold in a window we could:<syntaxhighlight lang="lua">menu.Tab1center:echo(myGold)</syntaxhighlight><br />
If we wanted to add a map to a window we could:<br />
<syntaxhighlight lang="lua">myMap = Geyser.Mapper:new({<br />
name = "myMap",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.Tab2center)</syntaxhighlight><br />
<br />
===Create a Window with a resize label===<br />
<br />
Previous tutorial is now done much simpler [[Manual:Geyser#Adjustable.Container|Adjustable containers]], have a look at those instead.<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Geyser&diff=20329Manual:Geyser2023-03-02T07:29:09Z<p>Kebap: /* HBox/VBox */ Use Template:MudletVersion</p>
<hr />
<div>{{TOC right}}<br />
<br />
= Introduction =<br />
<br />
The Geyser Layout Manager is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
=== Motivation ===<br />
<br />
Mudlet makes the creation of label, miniconsoles and gauges a quick and easy thing. Mudlet provides a nice signal when window resize events happen. To help with complex window management, Geyser steps in.<br />
<br />
=== Main Geyser Features ===<br />
<br />
Geyser is based on traditional GUI concepts and should feel similar to using Java's Swing. The biggest difference is in how positions are specified.<br />
<br />
* All window positions are specified relative to their container - nothing new there. However, window positions can also take on percentages and negative pixel and character values. For instance, a window could be constrained to have a height of 50% of its container and a width such that the window's right edge is always 20 characters from its container's right edge. See examples below and the demos/tests that come with Geyser.<br />
* All windows under Geyser control are automatically resized as necessary when the main Mudlet window is resized. Once you create a window and assign it to a container, you never have to worry about positioning it again. Nonetheless, it's very easy to shift the container that a window is in, maintaining its constraints so that it resizes as needed according to the dimensions of the new container.<br />
* Due to the container hierarchy, hiding a container window automatically hides all its contained windows too. The same for show. With clever construction and labels with callbacks, this lets one make complex GUI elements that are minimizable or maximizable or ...<br />
* However, there is always some overhead for automation systems and Geyser is no exception. Fortunately, most of the overhead is during window creation and resize events - not things that happen frequently.<br />
<br />
=== Getting pictures for your stuff ===<br />
You can find good, freely-available assets for your UI here:<br />
* [https://kenney.nl/assets?q=2d kenney.nl]<br />
* [https://opengameart.org/ opengameart.org]<br />
* [https://game-icons.net/ game-icons.net]<br />
<br />
=== Constraints format ===<br />
<br />
Geyser position constraints are a string composed of a number and a format type. For example, "10px" means 10 pixels, either pixels from the origin (e.g. x or y) or a value for the width or height. A negative number indicates distance from a container's right or bottom border depending on whether is a constraint for x/width or y/height, respectively. Percentages for width and height are in terms of the container's dimensions and negative values are converted to the equivalent positive value. A 100% width subwindow with an x-coordinate of 10 will have part of itself displayed outside the confines of its container. There is no hard limit on maximum window size, just as with regular Mudlet windows. If a number, n, is passed as a constraint instead of a string, it is assumed to be equivalent to "npx". Any Lua table that contains entries for x, y, width and height in the proper format can be used for Geyser constructors and setting constraints. Just like in Mudlet, 0,0 coordinates mean the top-left corner.<br />
<br />
The following is a valid example for coordinates of a Geyser object:<br />
<br />
<syntaxhighlight lang="lua"><br />
{x = "20px", y = "-10c", width = "40%", height = 30}<br />
</syntaxhighlight><br />
<br />
=== Math in Geyser ===<br />
You can also use math in your Geyser constraints just to line things up just right! Want to have a label occupy full height but not the first 30 pixels? You can:<br />
<br />
<syntaxhighlight lang="lua"><br />
footer = Geyser.Label:new({<br />
name = "footer",<br />
x = 0, y = 30,<br />
height = "100%-30px",<br />
}, main_window)<br />
</syntaxhighlight><br />
<br />
= Geyser elements =<br />
The purpose of this document is to go through every Geyser element and provide practical examples on how they are used. Read it from top to bottom, preferably doing all of the examples to understand how they work!<br />
<br />
== Technical manual ==<br />
<br />
See https://www.mudlet.org/geyser/files/index.html for a brief and technical overview of all Geyser elements and their functions.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html Geyser.Container]==<br />
An invisible, organizing object in Geyser - use it to divide your screen and position elements accordingly. '''[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html See here]''' for all of the functions that are available to you to use.<br />
<br />
A container is also the base class - which means that everything (labels, miniconsoles and gauges) can use its functions, since everything else is at heart a container.<br />
<br />
=== Creating a container ===<br />
To get started with a container, here's an example that'll create a 200px border on the left side of Mudlet for you, and make a container cover all of it - so you can place other visual elements inside it:<br />
<br />
<syntaxhighlight lang="lua"><br />
setBorderLeft(200)<br />
left_container = Geyser.Container:new({<br />
name = "left_container", -- give it a unique name here<br />
x=0, y=0, -- have it start at the top-left corner of mudlet<br />
width = 200, height="100%", -- with a width of 200, and a height of the full screen, hence 100%<br />
})<br />
</syntaxhighlight><br />
<br />
Right away, you'll see space appear on the left side. It'll be black, as the container is an invisible unit by itself. You can make sure it's there by making it flash by doing this from the input line:<br />
<br />
<syntaxhighlight lang="lua">lua left_container:flash()</syntaxhighlight><br />
<br />
The command will cause your container to flash for a moment for you, revealing itself.<br />
<br />
{{Note}} If you hide a container and create new Geyser elements within it, they'll be shown automatically for you.<br />
<br />
=== Container within a container ===<br />
You can place containers within other containers by specifying which "parent" the new container should have when you create one. Given our [[#Creating a container|previous example]], you can split the left side into two halves like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
left_container_top = Geyser.Container:new({<br />
name = "left_container_top",<br />
x=0, y=0, -- this container occupies the top, so it starts top-left as well<br />
width = "100%", height="50%", -- but only uses up half of the height<br />
}, left_container) -- this is the important bit - it says that left_container_top should be inside left_container<br />
<br />
left_container_bottom = Geyser.Container:new({<br />
name = "left_container_bottom",<br />
x=0, y="50%", -- this container starts halfway down the first one<br />
width = "100%", height="50%", -- and has the same half height of the original container<br />
}, left_container) <br />
</syntaxhighlight><br />
<br />
=== Aligning relative to bottom or right sides ===<br />
The aligning point within Mudlet is the top-left corner, and it's the same for the elements they are aligned - the position you specify is used by the top-left corner of the element.<br />
<br />
Using Geyser, you can align to the opposite side as well, using the coordinates in negatives, while keeping the dimensions of the object in mind. For example, if you want to align a box that's 20px wide on the usual left side, you'd give it a width of 20 and an x value of 0. If you'd like to align it on the right side, then you'd give it an x value of -20. The box will spawn 20px away from the right side and "grow" to the right by 20px.<br />
<br />
<syntaxhighlight lang="lua"><br />
right_container = Geyser.Container:new({<br />
name = "right_container",<br />
x="-20%", y=0, -- makes the container start 20% of the screen away from the right side<br />
width = "20%", height="50%", -- filling it up until the end<br />
}) <br />
</syntaxhighlight><br />
<br />
Do make sure to account for the scrollbar, as Mudlet UI elements can overlap it. You can also move the scrollbar with [[Manual:UI_Functions#setBorderRight|setBorderRight()]].<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html Geyser.Label]==<br />
Labels allow you to use pictures in your interface, as well as nicely-formatted text - see docs for label [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html functions].<br />
<br />
=== Basic label ===<br />
<br />
Here's an example to get you started with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
</syntaxhighlight><br />
<br />
This labels '''x''' coordinate is specified as 50% - and because it's not attached to any container, this implies that the window will start halfway at the main window. You can tell it's not attached to a container because there's nothing in between the last ''}'' and '')'', the place where the container goes.<br />
<br />
The '''y''' coordinate is 0 - which means that the label will start at the top of the screen. With the width being 50%, the label will occupy 50% of the screen - and since it starts at the halfway point, it means it'll occupy the entire right side. A height of 100% means that it'll stretch from the top to the full bottom.<br />
<br />
Here's what that'll look like:<br />
<br />
[[File:Simple-label.png|center|600px]]<br />
<br />
<br />
Playing around with the starting location and dimensions, we can also place it in the center of the screen with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
})<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
[[File:Simple_label_centered.png|center|600px]]<br />
<br />
To change the message on a label, you can use the ''mylabel:echo()'' function, where ''mylabel'' is the name of the label you gave it:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("hello!")<br />
</syntaxhighlight><br />
<br />
To get rid of the label, use the '':hide()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:hide()<br />
</syntaxhighlight><br />
<br />
=== Coloring text ===<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black", -- default text colour<br />
color = "SeaGreen" -- default label background<br />
})<br />
<br />
-- You can also change colour of text on demand with:<br />
testlabel:echo[[<p style="color:blue;">You can change the text color of a whole sentence or paragraph...</p><p>...or you can change the text color of one <span style="color:green;">word</span> or even a single l<span style="color:red;">e</span>tter.</p>]]<br />
</syntaxhighlight><br />
<br />
=== Setting the font size ===<br />
<br />
To set a different font size for your Label, use the ''setFontSize()'' method. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel:setFontSize(14)<br />
</syntaxhighlight><br />
<br />
The font size is set in Pt, so anything above 30 will likely be too large to be useful.<br />
<br />
=== Label inside a container ===<br />
<br />
Once you've got your containers and mastered the basic labels, you can drop labels into your nicely-organized containers. Doing so is similar to nesting containers:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
}, left_container_bottom) -- this is where we tell it what container to go into<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
That label is exactly the same as the one above that goes across the screen, except it's in our bottom-left container - so it looks appropriately different:<br />
<br />
[[File:Label in a container.png|center]]<br />
<br />
=== Image on a label ===<br />
One of the more amazing things labels allow you to do is put pictures anywhere on your Mudlet screen, that blend in very well. To do so, once the label is created, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setBackgroundImage setBackgroundImage()] function with the exact path to the image ([[File:Skullface.png]]):<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 0, y = "-14px",<br />
width = "16px", height = "14px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/skullface.png]]) -- update location to actual image location on your computer<br />
</syntaxhighlight><br />
<br />
This'll plop the picture to the bottom-left of your screen. To make the picture show, download the skullface picture above - save it to your desktop, and adjust the location of the image within [[]]'s to what it is on your computer. For example, if you saved this on your Windows 7 desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[C:/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
(yes, that's / and not \ - \ has been known not to work)<br />
<br />
If you saved this on your Mac desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
If you saved this on your Ubuntu desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/home/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
Using this basic building block, you can work up to making yourself a UI!<br />
<br />
=== Stretching an image on a label ===<br />
If you'd like your image not to keep its original size, but instead use up the available space of the label - you can use the [http://doc.qt.io/qt-5/stylesheet-reference.html#border-image border-image] stylesheet property to do so.<br />
<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- change the location to your picture<br />
-- on windows, use / to separate folders still, not \<br />
label:setStyleSheet[[<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);<br />
]]<br />
</syntaxhighlight><br />
<br />
{{note}} If you're on a Mudlet earlier than 3.15 and are having difficulty with the image coming up, it may be because of strange differences between Qt's CSS engine which does not affect mudlet's Lua. You may want to try appending :gsub("\\","/") to your string including getMudletHomeDir() (e.g. <code>getMudletHomeDir():gsub("\\","/")</code>). No longer necessary after Mudlet 3.15.<br />
<br />
=== Aligning an image within a label ===<br />
You can use background-image in combination with background-position to align an image within a label (if, say, the image is much smaller than the label).<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this will set and align an image top-right of the label<br />
if stunning then<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-ok.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
else<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-no.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
end<br />
</syntaxhighlight><br />
<br />
=== Showing / hiding a label ===<br />
You can show and hide labels, as you can any container, miniconsole or a gauge in Geyser with [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:show Geyser.Container:show()] and [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:hide Geyser.Container:hide()]. Remember that since labels are a type of a container, all container functions work on them.<br />
<br />
Hiding a label will allow you to click through on what is below the label, as well as free up the visual space for something else.<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- hide the label with:<br />
testlabel:hide()<br />
<br />
-- show the label with:<br />
testlabel:show()<br />
</syntaxhighlight><br />
<br />
=== Clickable images ===<br />
Tacking onto the fact that you can plop images anywhere on your Mudlet screen now, you can also make them react to your clicks. You can do so with the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setClickCallback setClickCallback()] function - by giving it a function to call when your label is clicked, you'll make it react.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "-215px", y = "0px",<br />
width = "200px", height = "200px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/qubodup-opengameart-cc0-200px-missile_icon.png]]) -- update location to actual image location on your computer<br />
picture_label:setClickCallback("on_bomb_press")<br />
<br />
function on_bomb_press()<br />
send("say BOOM!")<br />
end<br />
</syntaxhighlight><br />
<br />
That's it! Pressing on the image will make the ''on_bomb_press()'' function go off, which will do its code of ''send("say BOOM!")''. Download the picture for use [http://opengameart.org/content/missile-rts-icon here].<br />
<br />
[[File:Clickable_image.png|500px|center]]<br />
<br />
=== Styling labels ===<br />
Besides putting text or images on labels, you can also style them using Qt's stylesheets feature. Doing so allows you to create various graphics that make the label look more appealing:<br />
<br />
[[File:Label_styling_examples.png|center]]<br />
<br />
To set a stylesheet on a label, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setStyleSheet Geyser.Label:setStyleSheet()] function on your label, describing the stylesheet you'd like to give it. A stylesheet consists of properties you set - for example the background color, borders, padding, and so forth. You describe properties in the following format: ''property name''''':'''''values''''';'''. See here for a [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties list of all supported properties]. For example, to make your labels background be yellow, you'd use the background-color property:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "mylabel",<br />
x = "50%", y = "50%",<br />
width = 200, height = 100<br />
})<br />
<br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet.png|center]]<br />
<br />
Which is nice, but not particularly impressive.<br />
<br />
Scrolling down the list of properties, you'll come along a border one. Plopping it into our stylesheet nets the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
border: 5px solid white;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border.png|center]]<br />
<br />
Which gives a border!<br />
<br />
Fiddling with it some more and applying new properties we find on that page, we get a rounded border on our label:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: grey;<br />
border-width: 15px;<br />
border-style: solid;<br />
border-color: green;<br />
border-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border_radius.png|center]]<br />
<br />
Which'll conclude our exploration for now. Try out all of the other possible options available there - there's loads, from [http://doc.qt.io/qt-5/stylesheet-reference.html#border-style funky borders], to tiling images and fancy color combinations using gradients.<br />
<br />
You should also check out [[Manual:Geyser#Geyser.StyleSheet|Geyser.StyleSheet]] for a way to manage your stylesheets with adjustable properties and the ability to take defaults from another stylesheet.<br />
<br />
=== Adding a tooltip to a label ===<br />
<br />
Since Mudlet 4.6, you can now add a tooltip to labels and gauges. You can start by making a simple label and echoing some text to it:<br />
<br />
<syntaxhighlight lang="lua"><br />
testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = "50%",<br />
y = "50%",<br />
height = "25%",<br />
width = "25%",<br />
})<br />
testLabel:echo("This is on the label!")<br />
testLabel:setAlignment("center")<br />
-- sets the tooltip text<br />
testLabel:setToolTip("This is the tooltip", "10")<br />
<br />
<br />
-- optionally - you can customise the tooltip, too!<br />
testLabel:setStyleSheet("QToolTip{background: yellow; color: blue; border:none;}")<br />
</syntaxhighlight><br />
<br />
Without tooltip<br />
[[File:TestLabelForTooltips.png|thumb|center]]<br />
<br />
With tooltip<br />
<br />
[[File:LabelTooltip.png|thumb|center]]<br />
<br />
=== Avoid stylesheet inheritance by tooltip ===<br />
<br />
{{note}} If you set a new stylesheet for a label and with that a background image it is possible that through inheritance the tooltip also has this stylesheet image.<br />
<br />
To avoid this specify that the stylesheet is meant for the Label by using QLabel{...} in your Label stylesheet for exampleː<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- by using QLabel{...} the stylesheet won't be given to the tooltip as well<br />
label:setStyleSheet[[<br />
QLabel{<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);}<br />
]]<br />
</syntaxhighlight><br />
<br />
<br />
=== Aligning text/images inside a label ===<br />
By default, text is [http://qt-project.org/doc/qt-5/qlabel.html#alignment-prop centered vertically and left aligned] in a label. To align it to a specific side, use the stylesheets we learnt about earlier with the qproperty-alignment:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- specify one property this way:<br />
mylabel:setStyleSheet([[qproperty-alignment: 'AlignTop';]])<br />
<br />
-- or multiple ones separated with a |, for example this will align text to top-left:<br />
mylabel:setStyleSheet([[<br />
qproperty-alignment: 'AlignLeft | AlignTop';<br />
]])<br />
<br />
mylabel:echo("hi!")<br />
</syntaxhighlight><br />
<br />
[[File:Text_aligned.png|center]]<br />
<br />
=== Enabling wordwrap in a label ===<br />
If you need to enable word wrapping in a label (which by default is off), add the following line to the labels stylesheet:<br />
<br />
qproperty-wordWrap: true;<br />
<br />
As an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
If you'd like to set multiple properties, set them all at once - not via multiple :setStyleSheet() calls:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background: red;<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Adding a hover effect to a label ===<br />
The labels support adding stylesheets for specific cases, such as when a mouse is [http://doc.qt.io/qt-5/stylesheet-reference.html#hover-ps hovering] over them. To make this work, you provide CSS for when the label is in its usual state, and for when it is hovered over:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this example will add a border to the label when it is hovered over<br />
mylabell:setStyleSheet([[<br />
QLabel{ border-radius: 4px; }<br />
QLabel::hover{<br />
background-color: rgba(0,0,0,0%);<br />
border: 4px double green;<br />
border-radius: 4px;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Checkboxes ===<br />
Combining the fact that you can click on a label with an image to do something with the fact that you can change pictures on a label at will, you can make an image that changes itself when you click on it.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "50%", y = "50%",<br />
width = "21px", height = "19px"<br />
})<br />
-- a little trick we do to make the background of the label be transparent<br />
picture_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
picture_label:setClickCallback("on_checkbox_press")<br />
<br />
function on_checkbox_press()<br />
if checkbox_ticked then<br />
checkbox_ticked = false<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_unticked.png]])<br />
echo("Checkbox unticked.\n")<br />
else<br />
checkbox_ticked = true<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
echo("Checkbox TICKED!\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
The ''on_checkbox_press()'' function this time keeps the track of the checkbox with the ''checkbox_ticked'' variable and sets the image appropriately. You can download the ticked ([[File:Checkbox_ticked.png]]) and unticked images ([[File:Checkbox_unticked.png]]) or the [http://wiki.mudlet.org/images/6/6d/Checkbox.mpackage whole package] altogether.<br />
<br />
[[File:Checkbox_demo.png|500px|center]]<br />
<br />
=== Animated labels with sprites ===<br />
You can animate sprite packs using timers. Assuming you have the sprite pack downloaded, try this example:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 10, y = "-24px",<br />
width = "16px", height = "14px",<br />
})<br />
<br />
santa_counter = nil<br />
<br />
function animate_santa()<br />
santa_counter = (santa_counter or 0) + 1<br />
if santa_counter > 8 then santa_counter = 1 end<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/santa/santa]]..santa_counter..[[.png]]) -- update location to actual image location on your computer<br />
santa_timer = tempTimer(.16, animate_santa)<br />
end<br />
<br />
animate_santa()<br />
</syntaxhighlight><br />
<br />
The completed package is available [http://wiki.mudlet.org/images/6/6b/Dancing-santa.mpackage here], install it and do '''start/end animation''' to watch.<br />
<br />
=== Inserting extra spaces and newlines ===<br />
Echoing text into Mudlet and Geyser labels is different from miniconsoles and the main window, due to their nature. One of the differences is that extra spaces in a label, by default, get compressed down to one. '''To add extra spaces in a label''', replace extra spaces with '''&amp;nbsp;''' or by wrapping your text with them inside '''<nowiki><pre>my text here</pre></nowiki>'''.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this won't work, it'll show as one space:<br />
mylabel:echo("You -> point")<br />
<br />
-- but this would, because it replaces all spaces with &nbsp before echoing<br />
mylabel:echo(string.gsub("You -> point", " ", "&nbsp;"))<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- here is another way to go about this - and it additionally makes the font be monospaced:<br />
mylabel:echo("<pre>You -> point</pre>")<br />
</syntaxhighlight><br />
<br />
'''To add a new line in a label''' (aka linebreak), use '''<nowiki><br></nowiki>''' (instead of ''\n'' as you are used to in an echo).<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("These<br>words<br>are<br>split")<br />
</syntaxhighlight><br />
<br />
=== Transparent labels ===<br />
One of the possible ways of achieving transparency on a label is to add <code>background-color: rgba(0,0,0,0%);</code> to its stylesheet. Here's an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
my_transparent_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
</syntaxhighlight><br />
<br />
Want to get transparency in a miniconsole? You can [[Manual:Geyser#Change_your_miniconsole_background_image|do that as well]].<br />
<br />
=== Custom mouse cursor ===<br />
You can change the shape of the cursor when it's over your label with:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCursor("Forbidden") -- will change your mouse cursor to "forbidden" (as in "can't do this") cursor<br />
</syntaxhighlight><br />
Possible cursor shapes are [[CursorShapes| available here]], and you can import this [[Media:Cursor grid.zip|demo package]] to try them all out.<br />
<br />
It is also possible to change the mouse cursor to a custom made cursor by:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCustomCursor(getMudletHomeDir().."/custom_cursor.png")<br />
</syntaxhighlight><br />
It is recommended that the custom cursor is a png with size of 32x32 to be supported on all systems.<br />
<br />
[[File:Changecursoroverlabel.gif]]<br />
<br />
{{Note}} Available in Mudlet 4.8+<br />
<br />
=== Flyout Labels ===<br />
<br />
Flyout labels allow you to create 'dropdown' or 'flyout' menus - menus that reveal more items once you hover your mouse over them. To create flyout labels:<br />
# add <code>nestable=true</code> (left click to open menu) or <code>nestflyout=true</code> (mouse hover to open menu) to your main label.<br />
# use [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] on your main label to add flyout labels to it.<br />
## [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] uses the same arguments as when creating a new label but also takes the '''layoutDir''' option to specify in which direction and axis should the labels align, where 2 letters combine into the option: first letter R for right, L for left, T for top, B for bottom, followed by the orientation: V for vertical or H for horizontal. So options are: <code>layoutDir="RV"</code>, <code>layoutDir="RH"</code>, <code>layoutDir="LV"</code>, <code>layoutDir="LH"</code>, and so on.<br />
# optionally, add <code>flyOut=true</code> to your flyout labels to make the labels dissapear when the mouse isn't hovering over them anymore.<br />
<br />
Note that the main flyout label cannot go into a container and needs to be on its own.<br />
<br />
{{note}} Requires Mudlet 3.0.<br />
<br />
==== Demo ====<br />
Here's an example that follows the steps above:<br />
<br />
<syntaxhighlight lang="lua"><br />
label0 = Geyser.Label:new({name="label0", <br />
x="50%",y="50%",height=50,width=300,nestable=true, <br />
message="<center>Clicky clicky</center>"})<br />
<br />
-- and add 3 labels to it with RV layout - so Right of the label, aligned Vertically<br />
label1 = label0:addChild({name="label1",height=30,width=70, layoutDir="RV", flyOut=true, message="label one"})<br />
label1:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label2 = label0:addChild({name="label2",height=30,width=70, layoutDir="RV", flyOut=true, message="label two"}) <br />
label2:setStyleSheet([[background-color: green; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label3 = label0:addChild({name="label3",height=30,width=70, layoutDir="RV", flyOut=true, message="label three"})<br />
label3:setStyleSheet([[background-color: red; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
</syntaxhighlight><br />
<br />
A more thorough example. Try it out to see what you can create with flyout labels:<br />
<syntaxhighlight lang="lua"><br />
-- create a label with a nestable=true property to say that it can nest labels<br />
mainlabel = Geyser.Label:new({name="testa", x=400,y=50,height=50,width=300,nestflyout=true, message="<center>HOVER HERE TO SEE FLY-OUT LABELS!</center>"})<br />
<br />
-- create 15 labels and store them in a table <br />
table_for_flyout_labels = {}<br />
for i=1,15 do<br />
-- options to layoutDir are the direction the window should go (R for right, L for left, T for top, B for bottom), followed by how the nested labels should be oriented (V for vertical or H for horizontal). So "BH" here means it'll go on the bottom of the label, while expanding horizontally<br />
table_for_flyout_labels[i] = mainlabel:addChild({name="test"..tostring(i),height=30,width=70, layoutDir="BH", flyOut=true, message="test"..tostring(i)})<br />
<br />
table_for_flyout_labels[i]:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px;]])<br />
end<br />
<br />
-- make the test5 label look a bit special as it has got a surprise<br />
table_for_flyout_labels[5]:echo("Hover here")<br />
<br />
-- add even more nested labels to the 5th label!<br />
even_more_flyout_labels = {}<br />
for i=1,60 do<br />
-- here, the layout will be to the right of it, while expanding vertically<br />
even_more_flyout_labels[i]=table_for_flyout_labels[5]:addChild({name="hover label "..tostring(i),height=30,width=100, layoutDir="RV", flyOut=true, message="label "..tostring(i)})<br />
even_more_flyout_labels[i]:setClickCallback("testFunc", even_more_flyout_labels[i].name)<br />
even_more_flyout_labels[i]:setStyleSheet([[background-color: grey; border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]])<br />
end<br />
<br />
function testFunc(name)<br />
display(name)<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look something like this: <br />
<br />
[[File:Flyout_labels_demo.png|150px]]<br />
<br />
==== Demo of layouts ====<br />
Here's another demo that explains all of the layout styles quite well:<br />
<syntaxhighlight lang="lua"><br />
local directions = {"R", "L", "T", "B"}<br />
local orientations = {"V", "H"}<br />
local mappings = {R = "right", L = "left", T = "top", B = "bottom", V = "vertical", H = "horizontal"}<br />
<br />
local combinations, combination_labels = {}, {}<br />
for _, direction in pairs(directions) do<br />
for _, orientation in pairs(orientations) do<br />
combinations[#combinations+1] = direction..orientation<br />
end<br />
end<br />
<br />
local function get_foreground_text_colour(r,g,b)<br />
local luminosity = (0.2126 * ((r/255)^2.2)) + (0.7152 * ((g/255)^2.2)) + (0.0722 * ((b /255)^2.2))<br />
if luminosity > 0.5 then<br />
return "black"<br />
else<br />
return "white"<br />
end<br />
end<br />
<br />
local function get_random_colour_rgb()<br />
return math.random(1,255), math.random(1,255), math.random(1,255)<br />
end<br />
<br />
-- create a label with a nestable=true property to say that it can nest labels<br />
all_possible_combinations_label = Geyser.Label:new({name="all_possible_combinations_label", x=0,y="-400",height=50,width=500,<br />
nestable = true, message="<center>Click to see a listing of possible combinations</center>"})<br />
<br />
for i = 1, #combinations do<br />
local combination = combinations[i]<br />
combination_labels[i] = all_possible_combinations_label:addChild({name="combo_"..combination,height=30,width=150, nestable = true, flyOut=true, layoutDir="BH", message="<center>Combination "..combination.."</center>"})<br />
<br />
local r,g,b = get_random_colour_rgb()<br />
local text_colour = get_foreground_text_colour(r,g,b)<br />
<br />
local combination_labels_children = {}<br />
for ii = 1, 3 do<br />
combination_labels_children[ii] = combination_labels[i]:addChild({<br />
name="combo_"..combination.."_"..ii, height = 30, width = 150, layoutDir=combination, flyOut = true,<br />
message = string.format("<center><b>%s</b>%s+<b>%s</b>%s layout</center>", <br />
combination:sub(1,1), mappings[combination:sub(1,1)]:sub(2), combination:sub(2,2), mappings[combination:sub(2,2)]:sub(2)),<br />
fgColor = text_colour})<br />
<br />
combination_labels_children[ii]:setStyleSheet(string.format([[background-color:rgb(%d, %d, %d); border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]], r,g,b))<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look like this:<br />
<br />
[[File:Flyoutlabels-layout-demo.png]]<br />
<br />
=== Geyser.Label right click menu ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
You can create a right click menu for a label just by using the function (assuming your label name is 'myLabel'):<br />
<syntaxhighlight lang="lua"> myLabelːcreateRightClickMenu({MenuItems = menuTable}) -- scroll down for a fuller example with more details </syntaxhighlight><br />
<br />
The menu table comprises of all the items and their names. To create a parent menu just create a nested table of names.<br />
<br />
Example of a menuTable:<br />
<syntaxhighlight lang="lua"> menuTable = {"First Item", "Second Item (Parent)", {"First ChildItem", "Second ChildItem"}, "Third Item"} </syntaxhighlight><br />
<br />
The menu would look like thisː<br />
<br />
[[File:RCDemo1.gif|250px]]<br />
<br />
You can give more constraints to further style and enhance your right click menu.<br />
<br />
==== Style your right click menu ====<br />
Your right click menu has 2 default styles integratedː "light" and "dark" which are defined by the constraint "Style".<br />
<br />
To set a default style just give the constraint Style the preferred value, for exampleː<br />
<syntaxhighlight lang="lua"> Style = "dark" </syntaxhighlight><br />
<br />
To give different levels of your menu different style just add the number of the level to the constraint, for exampleː<br />
<syntaxhighlight lang="lua"> Style2 = "light" -- Gives the second level of your menu the "light" style</syntaxhighlight><br />
<br />
For adding your own stylesheet use the constraint MenuStyle (use the same method as above to define stylesheets for different levels)<br />
<syntaxhighlight lang="lua"> MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]] <br />
-- Gives the second level of your menu this stylesheet</syntaxhighlight><br />
<br />
The same methods are used for defining the format, width and height for the menu item.<br />
<syntaxhighlight lang="lua"> <br />
MenuWidth = 70 -- standard menu width if nothing else is given<br />
MenuWidth2 = 80 -- menu width for the second level <br />
MenuFormat1 = "c10" -- menu format for the first level (format works like any other label echo format, in this case c is center and 10 is the font-size)<br />
MenuHeight = 30<br />
</syntaxhighlight><br />
<br />
==== Set onClick action for your menu item ====<br />
To set an action if your menu item is clicked use the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<syntaxhighlight lang="lua"> <br />
myLabelːsetMenuAction("First Item", function() echo("Clicked on the first item\n") end<br />
myLabelːsetMenuAction("Second Item (Parent).First ChildItem", function() echo("Clicked on the first child item\n") end) -- To set an action to a child item find it by using "Parent.Child" as name (only one parent is needed to be given the parents parent is not needed)<br />
</syntaxhighlight><br />
<br />
==== Access an menu item directly ====<br />
The simplest way to access a menu item directly is by just using the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<br />
For example to change the menu item textː<br />
<syntaxhighlight lang="lua"> <br />
myLabelːfindMenuElement("First Item"):echo([[my first Item]])<br />
</syntaxhighlight><br />
<br />
==== Right click menu example ====<br />
Better then any further explanation is probably this practical example. <br />
<br />
<syntaxhighlight lang="lua"> <br />
-- create the label the right click menu will be in<br />
myRightClickLabel = myRightClickLabel or Geyser.Label:new({<br />
name = "myRightClickLabel", message = "Please right click!", <br />
format = "cb15", x=10, y=10, width ="30%", height = "15%", <br />
color = "purple"})<br />
<br />
-- right click menu creation with custom styleheet on level2 and default "Dark" style <br />
myRightClickLabel:createRightClickMenu({<br />
MenuItems = {"Emergency", "Drink",{"ManaPotion","HealthPotion"}, "Disappear", "Cast",{"Blindness", "Blink"}}, <br />
Style = "Dark", <br />
MenuWidth2 = 80, <br />
MenuFormat1 = "c10",<br />
MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]]<br />
})<br />
<br />
myRightClickLabel:setMenuAction("Emergency", function() <br />
cecho("<red:pink>[Emergency Mode] Run as fast as possible!\n") <br />
send("emergency") <br />
closeAllLevels(myRightClickLabel) -- this can be used to close the right click menu if clicked on this item<br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.ManaPotion", function()<br />
cecho("<blue>Drinking my mana potion.\n") <br />
send("drink mp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.HealthPotion", function() <br />
cecho("<red>Drinking my health potion.\n") <br />
send("drink hp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Disappear", function() <br />
cecho("<grey>Disappearing.. \n") <br />
send("disappear") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blindness", function() <br />
cecho("<light_blue>Casting blindness \n") <br />
send("cast blindness enemy") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blink", function() <br />
cecho("<light_blue>Casting blink \n") <br />
send("cast blink") <br />
end )<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
<br />
[[File:Right click example demo.gif]]<br />
<br />
==== Add right click menu to label with already existing left click action ====<br />
If your label has an already existing left click action you'll have to create the right click menu<br />
"before" creating the labels "setClickCallBack" action and then just put into your labels onClick function<br />
(assuming your label name is 'myLabel' and 'event' is the last parameter of your onClick function)<br />
<br />
<syntaxhighlight lang="lua"> <br />
myLabel:onRightClick(event)<br />
</syntaxhighlight><br />
<br />
=== Geyser name ===<br />
Make sure to give your Geyser Labels, miniconsoles, and userwindows a <code>name</code> - while it'll technically work without one, items will be duplicated when you re-save them if they're lacking a name.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserStyleSheet.html Geyser.StyleSheet]==<br />
<br />
Allows you to create a managed stylesheet to make it easier to set and change properties. Also allows you to inherit properties from another stylesheet, making it easier to manage multiple styles at once.<br />
<br />
=== Basic Usage ===<br />
<br />
Here's an example to get you started. This creates a basic stylesheet to set the background color black and the foreground/text color to green, then applies it to a Geyser Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
local testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = 100,<br />
y = 100,<br />
height = 100,<br />
width = 300,<br />
stylesheet = stylesheet:getCSS(),<br />
})<br />
<br />
-- Alternate method of creating a stylesheet using a table of properties<br />
local stylesheet = Geyser.StyleSheet:new({<br />
['background-color'] = "black",<br />
['color'] = "green",<br />
})<br />
</syntaxhighlight><br />
<br />
=== Getting the CSS string === <br />
<br />
As shown above, you can use getCSS to get the stylesheet as a string.<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getCSS())<br />
--[[<br />
"background-color: black;\ncolor: green;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Including a target ===<br />
<br />
You can include a 'target' for your stylesheet to be applied to, such as QLabel, QPlainTextEdit, etc.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- QPlainTextEdit is useful for styling command lines in particular, to keep the style from bleeding into any associated miniconsole or userwindow.<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
QPlainTextEdit {<br />
background-color: black;<br />
color: green;<br />
}]])<br />
<br />
-- or as an optional third argument. Passing nil for the parent explicitly <br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]], nil, "QPlainTextEdit")<br />
<br />
-- or using the setTarget function after the fact<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
stylesheet:setTarget("QPlainTextEdit")<br />
</syntaxhighlight><br />
<br />
=== Changing a property ===<br />
<br />
Assuming you started with the example above, if you wanted to change the background color to purple you would do the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("background-color", "purple")<br />
testLabel:setStyleSheet(stylesheet:getCSS())<br />
</syntaxhighlight><br />
<br />
Or if you wanted to set the font, you would do:<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", [["Ubuntu Mono"]])<br />
</syntaxhighlight><br />
<br />
Note the way we set the font with the double quotes included in the string, this is because the quotes have to be there in the final stylesheet. You could use single quotes instead of the bracket notation as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", '"Ubuntu Mono"')<br />
</syntaxhighlight><br />
<br />
=== Getting the value of a property ===<br />
<br />
Again assuming you started with the example code above it's as easy as<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:get("color") -- will return "green"<br />
</syntaxhighlight><br />
<br />
=== Getting a table of properties and their values ===<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Setting the properties via table ===<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setStyleTable({<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"',<br />
})<br />
</syntaxhighlight><br />
<br />
=== Resetting the style with a string ===<br />
<br />
Creating a new Geyser.StyleSheet would break any inheritance for stylesheets which had this one as a parent (see below), so if you wish to reset the style via CSS string you should use :setCSS<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setCSS([[<br />
background-color: black;<br />
color: green;<br />
font: "Ubuntu Mono";<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Inheriting properties ===<br />
<br />
As with most things Geyser, just pass the parent in when you create the new stylesheet<br />
<br />
<syntaxhighlight lang="lua"><br />
local childsheet = Geyser.StyleSheet:new("color: blue;", stylesheet)<br />
display(childsheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "blue",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
<br />
display(childsheet:get("background-color")<br />
--"purple"<br />
<br />
-- show only properties set in this stylesheet, without inheritance<br />
display(childsheet:getStyleTable(false))<br />
--[[<br />
{<br />
color = "blue"<br />
}<br />
--]]<br />
<br />
-- can do the same for the CSS string<br />
display(childsheet:getCSS(false))<br />
--[[<br />
"color: blue;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html Geyser.MiniConsole]==<br />
This allows you to spawn a Mudlet miniconsole - unlike labels, these aren't as styleable, but they do format text better. They make a good fit for text-based menus, chat and map capture, and other things.<br />
<br />
Spawning one is very similar to other Geyser elements - paste this into a new script:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x="70%", y="50%",<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="30%", height="50%",<br />
})<br />
</syntaxhighlight><br />
<br />
This'll make you one at the bottom-right of the screen. The miniconsole will have a grey background by default, but you can set it to any color you'd like with [http://www.mudlet.org/geyser/files/geyser/GeyserWindow.html#Geyser.Window:setColor miniconsole:setColor()]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setColor("black") -- give it a nice black background<br />
</syntaxhighlight><br />
<br />
A special dimension property that MiniConsoles have is a character - instead of specifying a miniconsole to be % of a container or a certain number of pixels, you can specify it as a certain number of characters. You do this by using "c" at the end of a number. This way, you can, for example, specify miniconsole to be 10 letters long and 2 lines high:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="70%", y="50%",<br />
wrapAt = 10,<br />
width="10c", height="2c",<br />
})<br />
flatbox:setColor("red")<br />
flatbox:echo("ABCDEFGHIJ") -- that is 10 letters<br />
</syntaxhighlight><br />
<br />
=== Adding text ===<br />
You can use [[Manual:Technical_Manual#echo|echo()]] the same way with a miniconsole to add text as to the usual window:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("hello!")<br />
</syntaxhighlight><br />
<br />
As well as [[Manual:Technical_Manual#cecho|cecho]], [[Manual:Technical_Manual#decho|decho]], or [[Manual:Technical_Manual#hecho|hecho]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:cecho("<green>hey, <blue>colored <red>text!\n")<br />
</syntaxhighlight><br />
<br />
=== Copying lines with color ===<br />
To copy a line over to the miniconsole, as it is from the game with all colors preserved, you can [[Manual:UI_Functions#selectCurrentLine|select]], [[Manual:UI_Functions#copy|copy]], and [[Manual:UI_Functions#appendBuffer|append]] it. For an example, try making a trigger with this as the ''perl regex'' pattern type:<br />
<br />
<syntaxhighlight lang="lua"><br />
^<br />
</syntaxhighlight><br />
<br />
That'll make the trigger go off on every line. Then give it the following script (assumed you have made the HelloWorld miniconsole from earlier):<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
... and you'll see all MUD output duplicated exactly as it is to the miniconsole. Amazing! It's very efficient as well, so you can have many miniconsoles, even in spam, not lag you down.<br />
<br />
=== Clearing the miniconsole ===<br />
Clearing the miniconsole just requires using the following script (assumes you have made the HelloWorld miniconsole from earlier):<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:clear()<br />
</syntaxhighlight><br />
<br />
=== Doing edits in copied lines ===<br />
Sometimes you'll want to edit the line before stuffing it into the miniconsole. For example, if you're making a chat capture, you'd want to condense a really long org name into something that's more space-friendly.<br />
<br />
To do so, you'd use the [[Manual:Technical_Manual#selectString|selectString()]] the text you'd like to modify, [[Manual:Technical_Manual#replace|replace()]] it with a different one:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Your", 1) -- select the word you'd like to replace - in this case, 'Your'<br />
setBgColor(getBgColor()) -- preserve the background color in the replacement<br />
setFgColor(getFgColor()) -- preserve the foreground color in the replacement<br />
replace("Mine") -- replace the selection with the wird 'Mine'<br />
<br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
=== Gagging from the main window ===<br />
If you'd like to gag the line from the main window so it only shows up in your miniconsole, [[Manual:Technical_Manual#deleteLine|delete]] it after moving it over:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=== Clickable menus ===<br />
Using the [[Manual:Technical_Manual#echoLink|echoLink]], [[Manual:Technical_Manual#insertLink|insertLink]] and [[Manual:Technical_Manual#setLink|setLink]] functions, you can turn text into one that reacts on a click. Combined with your power of placing text anywhere on the screen with a miniconsole, you can make menus with options. Here is one such example, where selecting an item causes an echo to happen:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="20%", y="80%",<br />
width="40c", height="4c",<br />
})<br />
flatbox:setColor("red")<br />
clearWindow("flatbox")<br />
<br />
flatbox:cecho("<white:red>Choose one of the following options:\n")<br />
<br />
flatbox:fg("white")<br />
flatbox:bg("red")<br />
<br />
for _, fruit in ipairs{"banana", "apple", "orange"} do<br />
echoLink("flatbox", "* "..fruit:title().."\n", [[echo("You picked ]]..fruit..[[\n")]], "The "..fruit.." option", true)<br />
end<br />
<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
This will produce something like the following:<br />
<br />
[[File:Fruit_menu.png|center]]<br />
<br />
=== Change your miniconsole background image ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
To set a custom background image for your miniconsole, use [https://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html#Geyser.MiniConsole:setBackgroundImage :setBackgroundImage()]:<br />
<syntaxhighlight lang="lua"><br />
miniconsole_withBgImg = Geyser.MiniConsole:new({name = "BackgroundonConsole", x="50%", y="50%", width = "20%", height = "40%"})<br />
miniconsole_withBgImg:setBackgroundImage(":/Mudlet_splashscreen_development.png", "center")<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:decho("<:0,0,0,130> This is a decho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:hecho("#,80000000 This is a hecho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:decho("<:0,0,0> This is a decho test with no transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:hecho("#,000000 This is a hecho test with no transparent background\n")<br />
end<br />
</syntaxhighlight><br />
<br />
=== Enable and use your miniconsole command line ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Every miniconsole has a hidden command line. Enable it with:<br />
<syntaxhighlight lang="lua"><br />
HelloWorldContainer = HelloWorldContainer or Adjustable.Container:new({name="HelloWorldContainer", titleText = "Container with a command line"})<br />
<br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "purple",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, HelloWorldContainer)<br />
<br />
HelloWorld:enableCommandLine()<br />
</syntaxhighlight><br />
<br />
=== Set an action to your miniconsole command line ===<br />
If no action is set to your miniconsole command line the commands are send to the game the same way as for the main command line. Aliases still work as usual, and if you have command echo enabled in preferences, it'll show in both miniconsole and the main window.<br />
<br />
It is also possible to set an action to your command line, this enables you to use the command line as custom text input.<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:enableCommandLine()<br />
local function channelChat(text)<br />
send("chat "..text)<br />
HelloWorld:echo("[chat] " ..text.."\n")<br />
end<br />
<br />
HelloWorld:setCmdAction(channelChat)<br />
</syntaxhighlight><br />
<br />
This will send your miniconsole command line input to the chat channel.<br />
<br />
More complicated/sophisticated actions are possible, setCmdAction works the same way as the Label clickCallback functions - that is, you can pass arguments to it.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html Geyser.Gauge]==<br />
<!--<br />
This is a composite window. Gauge duplicates the functionality of the built in Mudlet gauges, but in a clean and easily extended way. Internally, a Geyser Gauge is a container holding two Labels, front and back, which are initially scaled to fill the entire Gauge container. Hence, a gauge, g, can be given callbacks with the g.front:setClickCallback() method.<br />
<br />
The backgroundColor parameter initially sets the colors of the gauge, but of course the front and back components can be accessed individually as labels for high control over their looks. Gauges can be horizontal or vertical and decrease in value left to right, right to left, down up or up down depending on the value of the orientation parameter.<br />
--><br />
<br />
A Gauge allows you to represent numbers on a scale - and most typically, you've seen it be used as your standard hp/mana/whatever bar. A basic bar is made similarly to other Geyser elements. To set the value on the gauge that it should represent, use the [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] function:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="5%",<br />
})<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
That'll spawn you a pretty basic gauge with a horizontal orientation and a grey colour - and as a test, with a random value.<br />
<br />
[[File:Basic_gauge.png|center]]<br />
<br />
=== Updating a gauge ===<br />
You'd want your gauge to stay in sync with your actual values. To make that happen, you want to call [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] whenever the value that the gauge is tracking changes.<br />
<br />
So for example, if you make a health bar - wherever you get your new health at (be it prompt, gmcp, atcp or whatever), update the gauge as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- theoretical example<br />
current_health, max_health = tonumber(matches[2]), tonumber(matches[3])<br />
<br />
-- update the bar<br />
hp_bar:setValue(current_health, max_health)<br />
</syntaxhighlight><br />
<br />
You can also write down how much health have you got on the bar with:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local hp = math.random(1,100) <br />
hpbar:setValue(current_health, max_health, "<b>"..max_health.."hp</b>")<br />
<br />
-- example using GMCP in IRE games:<br />
hpbar:setValue((100/gmcp.Char.Vitals.maxhp)*gmcp.Char.Vitals.hp,100,gmcp.Char.Vitals.hp)<br />
</syntaxhighlight><br />
<br />
[[File:Hpbar_basic.png|center]]<br />
<br />
=== Styling a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. Combining this with Geyser:Label.setStyleSheet, you can improve the visuals of your gauges by using Qt-supported CSS. The syntax for specifying CSS is a bit different - it requires a semicolon after every property, and is done in the format of ''property name''''':'''''values''''';'''. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here] and you can use [https://build-system.fman.io/qt-designer-download Qt Designer] to create them. Practical example:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #98f041, stop: 0.1 #8cf029, stop: 0.49 #66cc00, stop: 0.5 #52a300, stop: 1 #66cc00);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #78bd33, stop: 0.1 #6ebd20, stop: 0.49 #4c9900, stop: 0.5 #387000, stop: 1 #4c9900);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge.png|center]]<br />
<br />
The same style can be adjusted by colors to red as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f04141, stop: 0.1 #ef2929, stop: 0.49 #cc0000, stop: 0.5 #a40000, stop: 1 #cc0000);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bd3333, stop: 0.1 #bd2020, stop: 0.49 #990000, stop: 0.5 #700000, stop: 1 #990000);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge_red.png|center]]<br />
<br />
=== Updating a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. To make a gauge clickable you can set a ClickCallBack on the top label which is ''mygauge.text'' example: <syntaxhighlight lang="lua">mygauge.text:setClickCallback("functionName", variableToSendToFunctionName)</syntaxhighlight><br><br />
If you would like to have different click events for the top or back of a gauge you can enable clickThrough for the top or ''mygauge.text'' label example<br />
<br />
<syntaxhighlight lang="lua"><br />
mygauge.text:enableClickthrough()<br />
mygauge.front:setClickCallback("functionOne", variableToSendToFunctionOne)<br />
mygauge.back:setClickCallback("functionTwo", variableToSendToFunctionTwo)<br />
</syntaxhighlight><br />
<br />
<br />
=== Tooltips on gauges ===<br />
Tooltips are available since Mudlet 4.6 as explained in above section [[#Adding_a_tooltip_to_a_label]], and as gauges are really only made up of labels as well, you could add a tooltip then by just using <syntaxhighlight lang="lua">mygauge.text:setToolTip("This is the gauge's tooltip", "10")</syntaxhighlight> the same as it's handled for clickback.<br />
<br />
== HBox/VBox ==<br />
<br />
These are special types of containers. Every window in these is horizontally or vertically aligned in the order they were added.<br />
<br />
{{MudletVersion|2.0}}<br />
<br />
== Geyser.UserWindow ==<br />
Allows you to use Mudlets UserWindows within Geyser, which allows you to use all the functionality of a MiniConsole in its basic form.<br />
The big advantage is the possibility to add other Geyser Elements like Labels, MiniConsole, Gauges, Mappers to the UserWindow.<br />
The UserWindow then can act as container for those elements with all the perks of dynamic resizing or any other Geyser functionality.<br />
<br />
{{note}} available in Mudlet 4.6.1+<br />
<br />
===Basic floating userwindow ===<br />
This will create a movable floating userwindow.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "TestUserWindow",<br />
titleText ="My Test UserWindow", -- only available since Mudlet 4.8+<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
</syntaxhighlight><br />
<br />
You can change the title of the userwindow by using the parameger titleText and the functions below (as of Mudlet 4.8+)ː<br />
<br />
To set a new title after creation useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setTitle("My new title Text")<br />
</syntaxhighlight><br />
<br />
To revert to the standard title useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:resetTitle()<br />
</syntaxhighlight><br />
<br />
To '''save the position''' of the userwindow - say in case you've dragged it onto another monitor and would like it to stay there when you restart Mudlet - use [[Manual:UI_Functions#saveWindowLayout|saveWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
saveWindowLayout()<br />
</syntaxhighlight><br />
<br />
To restore it afterwards, use [[Manual:UI_Functions#loadWindowLayout|loadWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create your userwindows first with Geyser.UserWindow:new<br />
-- then restore them to the positions they were at:<br />
loadWindowLayout()<br />
</syntaxhighlight><br />
<br />
=== Docked UserWindow ===<br />
To create the window docked at the right side,<br />
set the variable docked (at creation of the container) to true.<br />
Be aware that with this variable set to true the position and the size at creation of the userwindow will be ignored.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true<br />
<br />
})<br />
</syntaxhighlight><br />
<br />
Since Mudlet 4.8+ it is also possible to choose the docking Position of the UserWindow at creation and by function withː<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true,<br />
dockPosition = "top" -- Possible dockPositions are left "l", right "r", top "t", bottom "b" and floating "f" <br />
})<br />
</syntaxhighlight><br />
<br />
To change it for a already created UserWindow use the function setDockPosition(dockPosition) likeː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setDockPosition("left")<br />
</syntaxhighlight><br />
<br />
=== Disable/enable UserWindow autoDock ===<br />
{{note}} available in Mudlet 4.8+<br />
<br />
The auto docking feature can be really annoying at times. To disable it use the functionsː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:disableAutoDock() -- disables autoDock. Docking still possible with ːsetDockPosition<br />
testuserwindow:enableAutoDock() -- reenables autoDock<br />
</syntaxhighlight><br />
<br />
=== Styling the UserWindow border and title area ===<br />
{{note}} available in Mudlet 4.10+ and Linux only<br />
<br />
Geyser.UserWindows can accept a stylesheet to change the appearance of the border and title area and make<br />
the UserWindow look more appealing. This unfortunately only works in Linux, as in macOS and Windows, it is the OS theme that is used here. <br />
<br />
<syntaxhighlight lang="lua"><br />
myUserWindow = myUserWindow or Geyser.UserWindow:new({<br />
name = "myUserWindow", titleText = "myUserWindow", autoDock = false<br />
})<br />
<br />
myUserWindow:setStyleSheet( <br />
[[QDockWidget{<br />
border: 1px solid green; /* UserWindow border style */<br />
font: bold 15pt "Arial"; /* Font of the titleBar */<br />
color: rgb(0,0,150); /* Font color */<br />
}<br />
<br />
QDockWidget::title{ <br />
background-color: rgb(0,255,150); /* TitleBar color */<br />
border: 2px solid red; /* TitleBar border */<br />
border-radius: 2px; /* TitleBar border radius */<br />
text-align: center; /* alignment of the titleText */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
[[File:UserWindowStyleSheet.png]]<br />
<br />
=== UserWindow as Container ===<br />
This is the feature which shows the versatile nature of Geyser.UserWindows.<br />
The UserWindow act as container and is at that possible to dynamically resize the containing Geyser Elments.<br />
Put a label in the UserWindow resize it as rectangle.<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "ParentTestUserWindow",<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
<br />
testuserwindow:setColor("dark_green") -- give the userwindow a bit of color <br />
<br />
labelinuserw = Geyser.Label:new({<br />
name = "LabelinUserWindow",<br />
x=20, y=20,<br />
width = -20, height = -20,<br />
color="light_blue", fontSize=20,<br />
},testuserwindow)<br />
<br />
labelinuserw:echo("This is a label in an userwindow", "black", "c")<br />
</syntaxhighlight><br />
[[File:LabelInUserWindow.png]]<br />
<br />
The same way you are able to add your favorite Geyser Application (like tabbed chat, animated timers, gauges) to an UserWindow.<br />
<br />
Note that you don't need to add MiniConsoles to a UserWindow - as UserWindows already have them built-in.<br />
<br />
[[File:Tabbedchatinuserwindow.png]]<br />
<br />
== Geyser.CommandLine ==<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Allows you to create your custom command lines which can resize/move like any other Geyser object.<br />
<br />
If you just need a command line which is integrated in a miniconsole or userwindow, check out [[Manual:Geyser#Enable and use your miniconsole command line|:enableCommandLine()]].<br />
<br />
=== Creating a Geyser.CommandLine ===<br />
An example to get you startedː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine = myCommandLine or Geyser.CommandLine:new({<br />
name = "myCommandLine", <br />
x = "-20%", y = -40, <br />
width = "20%", height = 40,<br />
stylesheet = "border: 1px solid silver;"<br />
})<br />
</syntaxhighlight><br />
This creates a new command line in the right bottom of your screen.<br />
<br />
=== Bind action to your command line input ===<br />
If you use your previously created command line, any command will just be send to the game, after having been checked for aliases.<br />
<br />
To react to any input in a custom manner, we can set an action to the command line and use the input as parameter.<br />
<br />
Example of a command line changing the background color of your main console (assumes you have created "myCommandLine" from earlier): <br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setAction(<br />
function(commandLineInput)<br />
r, g, b = Geyser.Color.parse(commandLineInput) -- gets the r, g, b values of the color you input to the command line<br />
if b then -- checks if the color is valid<br />
setBackgroundColor(r, g, b)<br />
else<br />
echo("\n"..commandLineInput.." is not a valid color. Try again.")<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
=== Styling a command line ===<br />
You can style your Geyser command line by using Qt-supported CSS. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here].<br />
<br />
Practical example (assuming "myCommandLine" is created)ː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setStyleSheet([[<br />
QPlainTextEdit{ /* QPlainTextEdit is used to prevent the styleSheet bleeding to the right click menu*/<br />
border: 1px solid silver; /* Command line border style */<br />
background-color: rgb(0,255,150); /* Command line background color */<br />
font: bold 12pt "Arial"; /* Font and font-size of your command line */<br />
color: rgb(0,0,150); /* Command line text color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Create an extra command line in Mudlet ===<br />
If your goal is to just have an extra command/input line - say, for role-playing purposes: copy/paste the example below into a new script in Mudletː<br />
<br />
<syntaxhighlight lang="lua"><br />
inputContainer = inputContainer or Adjustable.Container:new({<br />
x = 0, y = "-4c", <br />
name = "InputContainer", padding = 2, <br />
width = "100%", height = "4c", <br />
autoLoad = false<br />
})<br />
<br />
extraCmdLine = extraCmdLine or Geyser.CommandLine:new({<br />
name = "extraCmdLine", <br />
x = 0, y = 0, width = "100%", height = "100%"<br />
}, inputContainer)<br />
<br />
inputContainer:attachToBorder("bottom")<br />
</syntaxhighlight><br />
<br />
This will look likeː <br />
<br />
[[File:AdditionalCommandLine.png|extra command line]]<br />
<br />
== Adjustable.Container ==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
Adjustable Containers are a new "GeyserClass" which act as containers for Geyser elements, but with more flexible and user configurable features. They are referred to as "adjustable" because they can be minimized, loaded, saved, moved, adjusted in size with the mouse pointer, and attached to borders. <br />
<br />
A brief video of [https://www.youtube.com/watch?v=GT2ScizuM48&feature=youtu.be Introduction to Adjustable Containers] is available.<br />
<br />
=== Creating an Adjustable.Container ===<br />
An Adjustable.Container is created just like any other Geyser Object. For example, we might experiment with creating a new Adjustable.Container by running the following line of lua code:<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
</syntaxhighlight><br />
This will create a new Adjustable.Container with the name ''testContainer''. Specifying the adjustable container's name is important for saving. Defining a variable, such as ''testCon'' in our above example, allows functions to be used with the Adjustable.Container.<br />
<br />
Our newly created Adjustable.Container may be used the same way as any other Geyser.Container might. For example, let's put a Geyser.Label in our new testContainer:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
testLabel = Geyser.Label:new({name="myTestLabel", x=0, y=0, height="100%", width="100%", color="green"},testCon)<br />
</syntaxhighlight><br />
<br />
The above code creates a new, green-colored Geyser.Label in the ''testCon'' adjustable.container as shown below:<br />
<br />
[[File:GreenLabelinAdjustableContainer.png]]<br />
<br />
You can also create one for miniconsole:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer = miniconsoleContainer or Adjustable.Container:new({name="miniconsoleContainer"})<br />
myMiniconsole = Geyser.MiniConsole:new({<br />
name="myMiniconsole",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, miniconsoleContainer)<br />
<br />
myMiniconsole:echo("Hello!\n")<br />
</syntaxhighlight><br />
<br />
That will give you:<br />
<br />
[[File:Adjustable container miniconsole.png]]<br />
<br />
=== Key Functions ===<br />
A listing of key functions for the Adjustable.Container module can be found hereː https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html<br />
<br />
To make the Adjustable Container show on screen use the following:<syntaxhighlight lang="lua"><br />
testCon:show() --will cause the Adjustable Container to show if not showing<br />
</syntaxhighlight><br />
<br />
===<div id="valid constraints"> Valid Constraints</div>===<br />
Adjustable Container constraints and their default values can be found at [https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html#Adjustable.Container:new].<br />
<br />
These are in addition to the standard Geyser.Container constraints.<br />
<br />
=== Change Title Text ===<br />
To specify the title text of a new container, use the constraint <code>titleText</code> in the constructor (see [[Manual:Geyser#valid constraints|valid constraints]]).<br />
<br />
To change the title text after a container has already been created, use <code>setTitle</code>. Continuing from the previous example, the title for an existing container named "testCon" might be adjusted in a number of ways: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Title") -- changes the container's title to "Title"<br />
</syntaxhighlight><br />
<br />
A container's title text defaults to the color green, but this can also be adjusted by using <code>setTitle</code>: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Red Title Test","red") -- changes the container's title text to "Red Title Test" and displays the text in the specified color "red".<br />
</syntaxhighlight><br />
<br />
To restore a container's default title text, <code>setTitle</code> is issued without any specified title or color: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle() -- resets the container's title text<br />
</syntaxhighlight><br />
<br />
=== AutoSave and AutoLoad ===<br />
The following Adjustable.Container settings can be saved and loadedː<br />
<br />
<code>x</code>, <code>y</code>, <code>height</code>, <code>width</code>, <code>minimized</code>, <code>locked</code>, <code>lock Style</code>, <code>padding</code>, and <code>hidden</code>.<br />
<br />
These settings will be automatically saved when the Mudlet profile is closed, and automatically loaded when a previous Adjustable.Container is created within the corresponding profile.<br />
<br />
To prevent automatic saving and/or loading of these settings, the <code>autoLoad</code> and <code>autoSave</code> constraints can be included in the constructor. For example, the following code will prevent the settings of the ''testCon2'' Adjustable.Container from being loaded upon creation:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", autoLoad=false})<br />
</syntaxhighlight><br />
<br />
To also prevent the ''testCon2'' Adjustable.Container from automatically saving its settings when the Mudlet profile is closed, the <code>autoSave=false</code> constraint would be added at creation as follows:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCont2 = testCont2 or Adjustable.Container:new({name="testCont2", autoLoad=false, autoSave=false})<br />
</syntaxhighlight><br />
<br />
Automatic saving can also be deactivated after an Adjustable.Container has been created, by invoking <code>testCont:disableAutoSave()</code><br />
<br />
Note that even with autoSave and autoLoad disabled, it is still possible to save and load manually through the right-click menu and/or by using <code>testCont:save()</code> or <code>testCont:load()</code> in a script.<br />
<br />
To save/load all your containers manually at the same time, we use <code>Adjustable.Container:saveAll()</code> and/or <code>Adjustable.Container:loadAll()</code><br />
<br />
=== "All" Functions ===<br />
The following functions affect all Adjustable Containers at the same time.<br />
<br />
{{note}} You must create the Adjustable Containers before these functions will have an effect.<br />
<br />
<code>Adjustable.Container.loadAll()</code> loads all the settings from your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container.saveAll()</code> saves all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:showAll()</code> shows all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:doAll(myfunc)</code> creates a function that will affect all your Adjustable Containers. For example:<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:hide() end) -- hides all your adjustable containers<br />
</syntaxhighlight><br />
<br />
=== Custom Save/Load Directories and Slots ===<br />
{{note}} available in Mudlet 4.10+<br />
==== Custom Directory ====<br />
If no option set your Adjustable.Container saves/loads its settings in your profile directory.<br />
<br />
It is possible to change the default save/load directory by using for example a different defaultDir as constraint when creating your Adjustable.Container.<br />
<br />
{{note}} This can be especially useful for authors of packages which want to ship their own save files.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = "/home/edru/MyAdjustableContainerSettings/"}) -- noteː the directory will be created if it doesn't exist<br />
</syntaxhighlight><br />
<br />
Example for save files in a package (assuming the packagename is "AdjustableContainerTest" and the settings are saved in "myPersonalAdjSettings"<br />
<syntaxhighlight lang="lua"><br />
local packageName = "AdjustableContainerTest"<br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = string.format("%s/%s/myPersonalAdjSettings/", getMudletHomeDir(), packageName)})<br />
</syntaxhighlight><br />
<br />
==== Custom Slot ====<br />
Another useful addition is to choose a save slot depending on the situation or to reset to a default save state.<br />
<br />
To save to a different slot just add it as parameter when saving.<br />
<br />
For exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːsave("combatSlot")<br />
</syntaxhighlight><br />
<br />
To then load from that slot just useː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːload("combatSlot")<br />
</syntaxhighlight><br />
<br />
{{note}} This also allows package/module authors to choose a "default" save setting to reset to.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
Adjustable.ContainerːsaveAll("default") -- saves the default settings<br />
<br />
-- to reset to default settings then just use<br />
Adjustable.ContainerːloadAll("default") -- loads the default settings<br />
</syntaxhighlight><br />
<br />
This can also be used to change the whole GUI on the fly.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
-- in combat situation use combat settings<br />
Adjustable.ContainerːloadAll("combat") -- loads special combat settings<br />
-- combat is over <br />
Adjustable.ContainerːloadAll("default") --reverts to the default settings<br />
</syntaxhighlight><br />
<br />
==== Delete Save File ====<br />
To delete the save file just useː<br />
<syntaxhighlight lang="lua"><br />
testCont2:deleteSaveFile()<br />
</syntaxhighlight><br />
<br />
===Right-click menu===<br />
Your Adjustable Container has also integrated a right-click menu with the main key functions for easier usability:<br />
<br />
[[File:AdjustableContainerRightClickMenu.png]]<br />
<br />
The right-click menu automatically shows you the possible positions to attach to (top, right, bottom, or left) when it's near one of them. For example, to attach a window to the right of the screen, drag it over to the right - and then the 'Attach to - right' will appear as an option:<br />
<br />
[[File:Adjustable Container - attach to right.png]]<br />
<br />
It also shows the lockstyle selection, which allows you to choose what happens when you press <code>Lock</code>, with 4 lockstyles available by default:<br />
<br />
* standard: this is the default lockstyle, with a small margin on top to keep the right click menu usable.<br />
* light: only hides the min/restore and close labels. Borders and margin are not affected.<br />
* full: the container gets fully locked without any margin left for the right click menu.<br />
* border: keeps the borders of the container visible while locked.<br />
<br />
From Mudlet 4.10+ on it is also possible to change your right-click menu style to dark mode by<br />
<br />
<syntaxhighlight lang="lua"><br />
myAdjustableContainer:changeMenuStyle("dark") -- possible menu styles are "dark" or "light"<br />
</syntaxhighlight><br />
<br />
=== Create a Custom Menu with Custom Items ===<br />
To create a new menu element in your right click menu called "Custom" and add an item to it use:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newCustomItem(name, func)<br />
-- for example<br />
testcontainer:newCustomItem("Hello world", function(self) echo("Hello world\n") self:flash() end)<br />
-- this will write "Hello world" to the main console and flashes your container.<br />
</syntaxhighlight><br />
<br />
=== Add new LockStyles ===<br />
For more advanced users it's possible to add a new Lockstyles by:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newLockStyle(name, func)<br />
-- for example<br />
testcontainer:newLockStyle("NewLockStyle", function(self) self.Inside:move(40, 40) self.Inside:resize(-40,-40) self:setTitle("") end)<br />
</syntaxhighlight><br />
<br />
=== Change Adjustable Container Style ===<br />
Additionally to the standard container constraints Adjustable Containers allow you to change at creation: the internal Label style, the menu style, min/close buttons, the menu text, title text... <br />
<br />
( see [[Manual:Geyser#valid constraints|valid constraints]])<br />
An example of a Adjustable Container with different style.<br />
<syntaxhighlight lang="lua"><br />
testCont =<br />
testCont or<br />
Adjustable.Container:new(<br />
{<br />
name = "TestNewStyleContainer",<br />
adjLabelstyle = "background-color:rgba(220,220,220,100%); border: 5px groove grey;",<br />
buttonstyle=[[<br />
QLabel{ border-radius: 7px; background-color: rgba(140,140,140,100%);}<br />
QLabel::hover{ background-color: rgba(160,160,160,50%);}<br />
]],<br />
buttonFontSize = 10,<br />
buttonsize = 20,<br />
titleText = "My new Style",<br />
titleTxtColor = "black",<br />
padding = 15,<br />
}<br />
)<br />
</syntaxhighlight><br />
This code creates a container which looks like this:<br />
<br />
[[File:NewStyleAdjustableContainer.png|Adjustable Container with different style]]<br />
<br />
<br />
=== Attach your Adjustable Container to a Border ===<br />
The simplest way to attach your container to a border is to move your container near the border you want it to attach and use the <br />
right click menu <code> Attach to:</code><br />
<br />
There is also the function <code> TestCont:attachToBorder("right") -- attach TestCont to the right border </code><br />
<br />
To change the margin between container and border use the constraint <code> attachedMargin </code > or the function <code> TestContːsetBorderMargin(10) -- 10 is the margin in px </code><br />
<br />
{{note}} The border is set in percentages and adjusts with screen-size<br />
<br />
=== Create a moveable border frame ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Adjustable Container can be connected to a border and therefore act like a frame.<br />
<br />
This only works if your container is attached to a specific border and the border to connect to has also at least one container attached to it.<br />
Use the function <code>connectToBorder</code><br />
<br />
<syntaxhighlight lang="lua"><br />
TestCont:connectToBorder("left") -- possible borders are "top", "bottom", "right", "left"<br />
</syntaxhighlight><br />
<br />
Minimizing automatically disconnects from a border. Another way is to use the function <code>disconnect</code>.<br />
<br />
{{note}}Connected container are still resizable even if locked.<br />
<br />
If you like to do everything with your right click menu there is the function<br />
<br />
<syntaxhighlight lang="lua"><br />
TestContːaddConnectMenu()<br />
</syntaxhighlight><br />
If you want to add the connect menu items to all Adjustable Containers just<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:addConnectMenu() end)<br />
</syntaxhighlight><br />
<br />
There is also a brief video of how to [https://www.youtube.com/watch?v=Ex-q5zAEfpc connect your Adjustable Container] available.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
GUI = GUI or {}<br />
<br />
GUI.top = Adjustable.Container:new({name = "top", y="0%", height = "10%", autoLoad = false})<br />
GUI.bottom = Adjustable.Container:new({name = "bottom", height = "20%", y = "-20%", autoLoad = false})<br />
GUI.right = Adjustable.Container:new({name = "right", y = "0%", height = "100%", x = "-20%", width = "20%", autoLoad = false})<br />
GUI.left = Adjustable.Container:new({name = "left", x = "0%", y = "0%", height = "100%", width = "20%", autoLoad = false})<br />
<br />
<br />
GUI.top:attachToBorder("top")<br />
GUI.bottom:attachToBorder("bottom")<br />
GUI.left:attachToBorder("left")<br />
GUI.right:attachToBorder("right")<br />
<br />
GUI.top:connectToBorder("left")<br />
GUI.top:connectToBorder("right")<br />
GUI.bottom:connectToBorder("left")<br />
GUI.bottom:connectToBorder("right")<br />
</syntaxhighlight><br />
Here's what the frame will look like:<br />
<br />
[[File:Adjustable_frame.gif]]<br />
<br />
=== Add a scrollable box ===<br />
{{note}} available in Mudlet 4.15+<br />
<br />
To add a scrollable box to an adjustable label, try the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
ScrollContainer = ScrollContainer or Adjustable.Container:new({name = "ScrollContainer"})<br />
ContainerBox = ContainerBox or Geyser.ScrollBox:new({name = "ContainerBox", x = 0, y = 0, height = "100%", width = "100%"}, ScrollContainer)</syntaxhighlight><br />
<br />
[[File:Scrollbox-in-container.png|thumb|center]]<br />
<br />
==Change Container==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
With this command it is possible to change an elements or even a containers location to that from another container.<br />
For example:<br />
<syntaxhighlight lang="lua"><br />
mycontainerone:changeContainer(mycontainertwo)<br />
--puts container one into container two which means container two will be the parent of container one<br />
</syntaxhighlight><br />
It is also possible to change to a container which is not located on the main window:<br />
<syntaxhighlight lang="lua"><br />
myEmco:changeContainer(emco_userwindow)<br />
--puts my tabbed chat Emco into my userwindow<br />
--to put it back to the main window change to a container located on the main window<br />
myEmco:changeContainer(mymainwindow_container)<br />
--or if it the element wasn't in a container use the main Geyser Root container called Geyser<br />
myEmco:changeContainer(Geyser)<br />
</syntaxhighlight><br />
<br />
==Geyser.Mapper==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
It‘s possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation use: (this will create a map window docked at the left corner)<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are "left", "right", "top", "bottom", and "floating".<br><br />
To change the dockPosition after creation use:<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget:setDockPosition("floating")<br />
-- this will change myMapWidget dockPosition to floating <br />
</syntaxhighlight><br />
<br />
= Tutorial =<br />
Note: This tutorial assumes you know how scripts in Mudlet work. If not then you should look at the manual first. Also it only shows how Geyser basically works and explains Geysers special windows. It wont go into detail about the windows that where already in Mudlet.<br />
<br />
=== Hello World ===<br />
Let's start with something simple. A Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_1.png]]<br />
<br />
This code creates a blank Label with a size of 200x50 at a position of 50 points horizontal and vertical from its parent window - which is the main window since we didn't specify any.<br />
<br />
You can manipulate the Label through the normal functions but Geyser.Label:new() returns an object which can be used to manipulate the label directly. So you should store it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local HelloWorld = Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
Then you can, for example print a text on it:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_2.png]]<br />
<br />
You can put a format parameter so that the text is, for example, centered.<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_3.png]]<br />
<br />
The second parameter is the color. We set it to nil which means the labels foreground color will be used.<br />
<br />
The color parameter either accepts a string ("red"), a hex value("#FF0000" or "0xFF0000" or "|cFF0000"), or a decimal value "&lt;255,0,0&gt;"<br />
<br />
Example:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", "red", "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
{{note}} This will automatically set the foreground color, so any echo, without the color parameter set, after that will use the same color.<br />
<br />
You can also set the foreground color with the setFgColor method:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setFgColor("red")<br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
=== Containers ===<br />
<br />
Containers are windows that can contain other windows. Actually, since all other Geyser windows subclass container, every window can do that. But containers do not have any visible content by themselves. <br />
<br />
Let's show that by an example:<br />
<syntaxhighlight lang="lua"><br />
local container = Geyser.Container:new({<br />
name="container",<br />
x=50, y=50,<br />
width=250, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
This will create a container, but if you look at the screen you will see nothing at the positon.<br />
There is a way to make containers visible though:<br />
<syntaxhighlight lang="lua"><br />
container:flash()<br />
</syntaxhighlight><br />
<br />
This will flash the container for a short period of time.<br />
<br />
[[Image:Geyser_Container_1.png]]<br />
<br />
flash() accepts a number as paremeter which defines the time, in seconds, the flash is shown.<br />
<br />
Now, that the container is created, you can add other windows to it. There are 2 ways:<br />
<br />
Directly when creating the window:<br />
<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
},<br />
container)<br />
container_label:echo("This is a label in a container", nil, "c")<br />
</syntaxhighlight><br />
<br />
Later, after the window was created<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
})<br />
container_label:echo("This is a label in a container", nil, "c")<br />
container:add(container_label)<br />
</syntaxhighlight><br />
<br />
Both will lead to the same outcome.<br />
<br />
[[Image:Geyser_Container_2.png]]<br />
<br />
Note that we gave a width and height of "100%" to the constructor of the label. This means that the label will take 100% of the containers width and height. If values are given in percent they will even resize with its parent:<br />
<br />
<syntaxhighlight lang="lua"><br />
container:resize(325, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_3.png]]<br />
<br />
The first parameter is the width, the second the height. If the value is nil the current value is used.<br />
<br />
As said in the "Hello World" tutorial the position is relative to its parent window. That's why we could set both x and y to 0 and it is at the position we wanted - the position of the container.<br />
<br />
When we now move the container the label moves with it:<br />
<syntaxhighlight lang="lua"><br />
container:move(400, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_4.png]]<br />
<br />
The first parameter is the x-, the second the y-position. If the value is nil the current value is used.<br />
<br />
=== VBox and HBox ===<br />
<br />
The VBox and HBox classes are special Containers.<br />
They will automatically align its containing windows vertically or horizontally, respectively, in the order they where added to them.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local HBox = Geyser.HBox:new({<br />
name="HBox",<br />
x=0, y=0,<br />
width=400, height=30,<br />
})<br />
<br />
</syntaxhighlight><br />
<br />
Like containers you won't see them by themselves.<br />
<br />
Adding children works like with containers<br />
<syntaxhighlight lang="lua"><br />
<br />
local label1 = Geyser.Label:new({<br />
name="Label1",<br />
},<br />
HBox)<br />
label1:echo("Label 1", "black", "c")<br />
label1:setColor(255, 0, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_1.png]]<br />
<br />
We didn't set any position or size, but the label gets the same size as the HBox.<br />
<br />
If we add another window:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label2 = Geyser.Label:new({<br />
name="Label2",<br />
},<br />
HBox)<br />
label2:echo("Label 2", "black", "c")<br />
label2:setColor(0, 255, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_2.png]]<br />
<br />
the size will be divided equally between them!<br />
<br />
What if you want a child that takes more or less space than the others?<br />
That's possible too:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label3 = Geyser.Label:new({<br />
name="Label3",<br />
h_stretch_factor=2.0,<br />
},<br />
HBox)<br />
label3:echo("Label 3", nil, "c")<br />
label3:setColor(0, 0, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_3.png]]<br />
<br />
As you can see, Label 3 takes the same space as Label 1 and 2 Together. <br />
That's because we supplied a horizontal stretch factor with "h_stretch_factor=2.0"<br />
<br />
This works also with a vertical stretch factor, just replace "h_stretch_factor" with "v_stretch_factor"<br />
<br />
Now you may have windows that should not be stretched at all.<br />
To accomplish this you have to set the horizontal and/or vertical policy:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local label4 = Geyser.Label:new({<br />
name="Label4",<br />
width="13%",<br />
h_policy=Geyser.Fixed,<br />
},<br />
HBox)<br />
label4:echo("Label 4", "black", "c")<br />
label4:setColor(0, 255, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_4.png]]<br />
<br />
Possible values for the policies are Geyser.Fixed and Geyser.Dynamic (which is the default). They can also be applied to VBox and HBox in exactly the same way.<br />
<br />
Note that, like in the example above, the label will retain relative values (like percent) if used.<br />
<br />
The VBox works like the HBox, only that the child windows are aligned vertically.<br />
<br />
= Walkthroughs =<br />
Here are a few walkthroughs that will show you how to combine Geyser elements to create some simple GUI widgets.<br />
<br />
===Create a Clickable Compass===<br />
[[File: compass.png]]<br />
The following will walk you through the process of creating your own clickable compass using the Geyser framework.<br />
====Setup the image files====<br />
The compass requires a handful of images to work properly. You can find them here: https://www.dropbox.com/sh/53l7xrn4ds35wnq/WpWOziVKmH <br><br />
Download each image and place it in your profile folder. You can find your profile folder with getMudletHomeDir()<br><br />
If you're using Mudlet 2.1+ you can enter '''lua getMudletHomeDir()''' from the command line to return the profile folder path on your computer.<br />
<br />
====Create a new script====<br />
Script Name: '''''compass.resize'''''<br><br />
Registered Event Handlers: '''''sysWindowResizeEvent'''''<p><br />
Every snippet of code will be placed within this script.<br />
====Store the screen size====<br />
We'll want to store the screen size in some local variables so they can be easily referenced to later on.<br />
<syntaxhighlight lang="lua">local mw, mh = getMainWindowSize()</syntaxhighlight><br />
<br />
====Create a global table or namespace====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''compass''''' and everything we make from here on out will be stored within the compass table. We'll also add a few values to it: dirs and ratio. '''''compass.dirs''''' will store each direction while '''''compass.ratio''''' will store the ratio of our screen size so you can 'square up' your compass.<br />
<syntaxhighlight lang="lua">compass = compass or {<br />
dirs = {"nw","n","ne","w","center","e","sw","s","se"},<br />
ratio = mw / mh<br />
}</syntaxhighlight><br />
<br />
====Create the parent label====<br />
[[File: grey.png|thumbnail]]<br />
The 'parent label' refers to the label on the bottom layer. The entire compass will be created within this label. It's container is '''main''' for it's parent is the main window.<br />
<syntaxhighlight lang="lua">compass.back = Geyser.Label:new({<br />
name = "compass.back",<br />
x = "25%",<br />
y = "25%",<br />
width = "10%",<br />
height = "10%",<br />
},main)</syntaxhighlight><br />
<br />
====Set the parent label stylesheet====<br />
[[File: blue.png|thumbnail]]<br />
This will create the blue sphere that makes up most of the compass. The background color is a radial gradient that goes from a deep blue to a brighter shade. The border radius rounds the edges. When the radius is exactly half of the label width it forms a circle. The arrows of the compass actually protrude from the sphere so we give it a margin to suck it in a bit for this effect.<br />
<syntaxhighlight lang="lua">compass.back:setStyleSheet([[<br />
background-color: QRadialGradient(cx:.3,cy:1,radius:1,stop:0 rgb(0,0,50),stop:.5 rgb(0,0,100),stop:1 rgb(0,0,255));<br />
border-radius: ]]..tostring(compass.back:get_width()/2-14)..[[px;<br />
margin: 10px;<br />
]])</syntaxhighlight><br />
<br />
====Create a 3x3 grid====<br />
The compass is split into 9 sections. One for each cardinal direction plus an extra space that sits in the center. This 3x3 grid is created by 3 VBoxes that sit within a single HBox (or vice versa but I flipped a coin and this is what it gave me).<br><br />
So first off, we create the HBox. It will be the same size as its parent, ''compass.back''.<br />
<syntaxhighlight lang="lua"> compass.box = Geyser.HBox:new({<br />
name = "compass.box",<br />
x = 0,<br />
y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},compass.back)</syntaxhighlight><br />
Next, we create our 3 VBoxes. You don't need to specify position or size because these are placed within ''compass.box'', an HBox.<br />
<syntaxhighlight lang="lua"> compass.row1 = Geyser.VBox:new({<br />
name = "compass.row1",<br />
},compass.box)<br />
compass.row2 = Geyser.VBox:new({<br />
name = "compass.row2",<br />
},compass.box)<br />
compass.row3 = Geyser.VBox:new({<br />
name = "compass.row3",<br />
},compass.box)</syntaxhighlight><br />
Finally, we add our 9 labels. Take note that they are split up into even groups of 3. Each group is placed into a different ''compass.row#''<br />
<syntaxhighlight lang="lua"> compass.nw = Geyser.Label:new({<br />
name = "compass.nw",<br />
},compass.row1)<br />
<br />
compass.w = Geyser.Label:new({<br />
name = "compass.w",<br />
},compass.row1)<br />
<br />
compass.sw = Geyser.Label:new({<br />
name = "compass.sw",<br />
},compass.row1)<br />
<br />
compass.n = Geyser.Label:new({<br />
name = "compass.n",<br />
},compass.row2)<br />
<br />
compass.center = Geyser.Label:new({<br />
name = "compass.center",<br />
},compass.row2)<br />
<br />
compass.s = Geyser.Label:new({<br />
name = "compass.s",<br />
},compass.row2)<br />
<br />
compass.ne = Geyser.Label:new({<br />
name = "compass.ne",<br />
},compass.row3)<br />
<br />
compass.e = Geyser.Label:new({<br />
name = "compass.e",<br />
},compass.row3)<br />
<br />
compass.se = Geyser.Label:new({<br />
name = "compass.se",<br />
},compass.row3)</syntaxhighlight><br />
====Create a callback function====<br />
We'll want our compass to head in the direction of the arrow we're clicking. This is where we specify so. When the arrow is clicked, this function will be ran with the arrow direction as the argument.<br />
<syntaxhighlight lang="lua">function compass.click(name)<br />
send(name)<br />
end</syntaxhighlight><br />
====Create the hover functions====<br />
We want our arrows to turn yellow when we hover over them. We do so by simply resetting the label's stylesheet and changing the border image. Don't forget to include the margin as we still want that.<br />
<syntaxhighlight lang="lua">function compass.onEnter(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[hover.png");<br />
margin: 5px;<br />
]])<br />
end<br />
<br />
function compass.onLeave(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[.png");<br />
margin: 5px;<br />
]])<br />
end</syntaxhighlight><br />
====Set the stylesheets in the grid====<br />
[[File: Sample.png|thumb]]<br />
Each of the 9 labels need an image of an arrow. Rather than setting each individually, we'll iterate over the ''compass.dirs'' table we made awhile back and add the respective image to each. The names of images are a reflection of the ''compass.dirs'' table. This keeps it consistent and easy to refer to. During the iteration, the callback, setLabelOnEnter and setLabelOnLeave are also set for each label.<br />
<syntaxhighlight lang="lua">for k,v in pairs(compass.dirs) do<br />
compass[v]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..v..[[.png");<br />
margin: 5px;<br />
]])<br />
compass[v]:setClickCallback("compass.click",v)<br />
setLabelOnEnter("compass."..v,"compass.onEnter",v)<br />
setLabelOnLeave("compass."..v,"compass.onLeave",v)<br />
end</syntaxhighlight><br />
<br />
====Resize the compass into a square====<br />
[[File: final.png|thumb]]<br />
Most screen size ratios aren't a perfect 1:1. This will cause a 10% x 10% label to be far from square. By setting our height (the smaller of the two numbers) to our width, we can resize our compass to a near perfect square. This function is also the name of our script because we want it to run each time sysWindowResizeEvent is raised.<br />
<syntaxhighlight lang="lua">function compass.resize()<br />
compass.back:resize(compass.back.width, compass.back:get_width())<br />
end<br />
<br />
compass.resize()</syntaxhighlight><br />
<br />
===Create a Tabbed Window===<br />
[[File: tabwindow.png]]<br />
The following will walk you through the process of creating your own tabbed window using the Geyser framework.<br />
<br />
====Create a new script====<br />
Script Name: '''''Tabbed Window'''''<br><br />
Every snippet of code will be placed within this script.<br />
====Create a global table====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''menu''''' and everything we make from here on out will be stored within the menu table. We'll also add a few values to it: tabs, color1, color2, width, height and current. <br><br />
''''tabs'''' will be a table that stores all our tab names. If we want our tabs to have different names, we alter this table.<br><br />
''''color1'''' and ''''color2'''' will store the colors of our tabbed window. If we want to change the color of our tabbed window, we alter these values.<br><br />
''''width'''' and ''''height'''' will store the size of our tabbed window. If we want to change the size of the tabbed window, we alter these values.<br><br />
''''current'''' keeps track of which tab is selected. We will set this to the first tab in the table by default. We do this outside the initial table creation so we can easily access menu.tabs<br><br />
<syntaxhighlight lang="lua">menu = menu or {<br />
tabs = {"Tab1","Tab2","Tab3","Tab4"},<br />
color1 = "rgb(0,0,70)",<br />
color2 = "rgb(0,0,50)",<br />
width = "20%",<br />
height = "40%",<br />
}<br />
menu.current = menu.current or menu.tabs[1]</syntaxhighlight><br />
<br />
====Create the main container====<br />
Our tabbed window will need a container. This will be the bottom layer. Containers are invisible so no need to set a stylesheet.<br />
<syntaxhighlight lang="lua">menu.container = Geyser.Container:new({<br />
name = "menu.back",<br />
x = "50%", y = "25%",<br />
width = menu.width,<br />
height = menu.height,<br />
},main)</syntaxhighlight><br />
====Create an HBox====<br />
All of our tabs will be evenly spaced. So we'll create an HBox to sit at the top of our container.<br />
<syntaxhighlight lang="lua">menu.header = Geyser.HBox:new({<br />
name = "menu.header",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "10%",<br />
},menu.container)</syntaxhighlight><br />
====Create a label====<br />
This label will serve as a container for each window. It sits right underneath the HBox we just created for the tabs.<br />
<syntaxhighlight lang="lua">menu.footer = Geyser.Label:new({<br />
name = "menu.footer",<br />
x = 0, y = "10%",<br />
width = "100%",<br />
height = "90%",<br />
},menu.container)</syntaxhighlight><br />
We don't want this to be a big grey box at startup, so we'll set the stylesheet to appear like the rest of the windows.<br />
<syntaxhighlight lang="lua"><br />
menu.footer:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])</syntaxhighlight><br />
Each window actually has two labels. One for the light blue background, and another for the dark blue center. This will create that dark blue center.<br />
<syntaxhighlight lang="lua">menu.center = Geyser.Label:new({<br />
name = "menu.center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
menu.center:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])</syntaxhighlight><br />
====Add your tabs and their windows====<br />
Now we'll want to add our tabs and windows. We do this in a single for loop of the ''''menu.tabs'''' table since it holds all our tab names.<br />
<syntaxhighlight lang="lua">for k,v in pairs(menu.tabs) do<br />
</syntaxhighlight><br />
This will create the tabs. Each tab will be named: menu.<tabname>tab<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"] = Geyser.Label:new({<br />
name = "menu."..v.."tab",<br />
},menu.header)<br />
</syntaxhighlight><br />
Here is where we set the tab stylesheet. Each tab has a rounded top, so we set the border-radius of the top-left and top-right to 10px. Each tab has a small space for separation so we give the right and left sides a tiny margin of 1px.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-top-left-radius: 10px;<br />
border-top-right-radius: 10px;<br />
margin-right: 1px;<br />
margin-left: 1px;<br />
]])<br />
</syntaxhighlight><br />
This will display the name of each tab on the tab.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:echo("<center>"..v)<br />
</syntaxhighlight><br />
We need our tabs to do stuff when clicked, so we'll assign it a callback function, '''''menu.click''''', which we'll create later on. Our tab name is the argument.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setClickCallback("menu.click",v)<br />
</syntaxhighlight><br />
Now we create the windows that appear when each tab is clicked. Each window has two labels, one atop the other. The first, which we'll create here, has rounded edges on its bottom.<br />
<syntaxhighlight lang="lua"><br />
menu[v] = Geyser.Label:new({<br />
name = "menu."..v,<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
<br />
menu[v]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
The second label serves as the window's center and has rounded edges on all sides. And a margin of 5px from it's parent, the label we just created. When adding stuff to your windows, this is the label you'll want to use. '''''menu.<tabname>center'''''<br />
<syntaxhighlight lang="lua"><br />
menu[v.."center"] = Geyser.Label:new({<br />
name = "menu."..v.."center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu[v])<br />
</syntaxhighlight><syntaxhighlight lang="lua"><br />
menu[v.."center"]:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])<br />
</syntaxhighlight><br />
Finally, we hide all the windows and end the for loop.<br />
<syntaxhighlight lang="lua"><br />
menu[v]:hide()<br />
end</syntaxhighlight><br />
====Create a callback function====<br />
The last step is to create our callback function for when a tab is clicked. This will hide that tab that is stored in '''''menu.current''''', set menu.current to the clicked tab, and then show the menu.current tab.<br />
<syntaxhighlight lang="lua">function menu.click(tab)<br />
menu[menu.current]:hide()<br />
menu.current = tab<br />
menu[menu.current]:show()<br />
end</syntaxhighlight><br />
====Adding content to your windows====<br />
Add content to '''menu.<tab name>center'''<br />
So if we wanted to display our gold in a window we could:<syntaxhighlight lang="lua">menu.Tab1center:echo(myGold)</syntaxhighlight><br />
If we wanted to add a map to a window we could:<br />
<syntaxhighlight lang="lua">myMap = Geyser.Mapper:new({<br />
name = "myMap",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.Tab2center)</syntaxhighlight><br />
<br />
===Create a Window with a resize label===<br />
<br />
Previous tutorial is now done much simpler [[Manual:Geyser#Adjustable.Container|Adjustable containers]], have a look at those instead.<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Geyser&diff=20315Manual:Geyser2023-02-17T20:56:53Z<p>Kebap: /* Math in Geyser */ Typo</p>
<hr />
<div>{{TOC right}}<br />
<br />
= Introduction =<br />
<br />
The Geyser Layout Manager is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
=== Motivation ===<br />
<br />
Mudlet makes the creation of label, miniconsoles and gauges a quick and easy thing. Mudlet provides a nice signal when window resize events happen. To help with complex window management, Geyser steps in.<br />
<br />
=== Main Geyser Features ===<br />
<br />
Geyser is based on traditional GUI concepts and should feel similar to using Java's Swing. The biggest difference is in how positions are specified.<br />
<br />
* All window positions are specified relative to their container - nothing new there. However, window positions can also take on percentages and negative pixel and character values. For instance, a window could be constrained to have a height of 50% of its container and a width such that the window's right edge is always 20 characters from its container's right edge. See examples below and the demos/tests that come with Geyser.<br />
* All windows under Geyser control are automatically resized as necessary when the main Mudlet window is resized. Once you create a window and assign it to a container, you never have to worry about positioning it again. Nonetheless, it's very easy to shift the container that a window is in, maintaining its constraints so that it resizes as needed according to the dimensions of the new container.<br />
* Due to the container hierarchy, hiding a container window automatically hides all its contained windows too. The same for show. With clever construction and labels with callbacks, this lets one make complex GUI elements that are minimizable or maximizable or ...<br />
* However, there is always some overhead for automation systems and Geyser is no exception. Fortunately, most of the overhead is during window creation and resize events - not things that happen frequently.<br />
<br />
=== Getting pictures for your stuff ===<br />
You can find good, freely-available assets for your UI here:<br />
* [https://kenney.nl/assets?q=2d kenney.nl]<br />
* [https://opengameart.org/ opengameart.org]<br />
* [https://game-icons.net/ game-icons.net]<br />
<br />
=== Constraints format ===<br />
<br />
Geyser position constraints are a string composed of a number and a format type. For example, "10px" means 10 pixels, either pixels from the origin (e.g. x or y) or a value for the width or height. A negative number indicates distance from a container's right or bottom border depending on whether is a constraint for x/width or y/height, respectively. Percentages for width and height are in terms of the container's dimensions and negative values are converted to the equivalent positive value. A 100% width subwindow with an x-coordinate of 10 will have part of itself displayed outside the confines of its container. There is no hard limit on maximum window size, just as with regular Mudlet windows. If a number, n, is passed as a constraint instead of a string, it is assumed to be equivalent to "npx". Any Lua table that contains entries for x, y, width and height in the proper format can be used for Geyser constructors and setting constraints. Just like in Mudlet, 0,0 coordinates mean the top-left corner.<br />
<br />
The following is a valid example for coordinates of a Geyser object:<br />
<br />
<syntaxhighlight lang="lua"><br />
{x = "20px", y = "-10c", width = "40%", height = 30}<br />
</syntaxhighlight><br />
<br />
=== Math in Geyser ===<br />
You can also use math in your Geyser constraints just to line things up just right! Want to have a label occupy full height but not the first 30 pixels? You can:<br />
<br />
<syntaxhighlight lang="lua"><br />
footer = Geyser.Label:new({<br />
name = "footer",<br />
x = 0, y = 30,<br />
height = "100%-30px",<br />
}, main_window)<br />
</syntaxhighlight><br />
<br />
= Geyser elements =<br />
The purpose of this document is to go through every Geyser element and provide practical examples on how they are used. Read it from top to bottom, preferably doing all of the examples to understand how they work!<br />
<br />
== Technical manual ==<br />
<br />
See https://www.mudlet.org/geyser/files/index.html for a brief and technical overview of all Geyser elements and their functions.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html Geyser.Container]==<br />
An invisible, organizing object in Geyser - use it to divide your screen and position elements accordingly. '''[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html See here]''' for all of the functions that are available to you to use.<br />
<br />
A container is also the base class - which means that everything (labels, miniconsoles and gauges) can use its functions, since everything else is at heart a container.<br />
<br />
=== Creating a container ===<br />
To get started with a container, here's an example that'll create a 200px border on the left side of Mudlet for you, and make a container cover all of it - so you can place other visual elements inside it:<br />
<br />
<syntaxhighlight lang="lua"><br />
setBorderLeft(200)<br />
left_container = Geyser.Container:new({<br />
name = "left_container", -- give it a unique name here<br />
x=0, y=0, -- have it start at the top-left corner of mudlet<br />
width = 200, height="100%", -- with a width of 200, and a height of the full screen, hence 100%<br />
})<br />
</syntaxhighlight><br />
<br />
Right away, you'll see space appear on the left side. It'll be black, as the container is an invisible unit by itself. You can make sure it's there by making it flash by doing this from the input line:<br />
<br />
<syntaxhighlight lang="lua">lua left_container:flash()</syntaxhighlight><br />
<br />
The command will cause your container to flash for a moment for you, revealing itself.<br />
<br />
{{Note}} If you hide a container and create new Geyser elements within it, they'll be shown automatically for you.<br />
<br />
=== Container within a container ===<br />
You can place containers within other containers by specifying which "parent" the new container should have when you create one. Given our [[#Creating a container|previous example]], you can split the left side into two halves like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
left_container_top = Geyser.Container:new({<br />
name = "left_container_top",<br />
x=0, y=0, -- this container occupies the top, so it starts top-left as well<br />
width = "100%", height="50%", -- but only uses up half of the height<br />
}, left_container) -- this is the important bit - it says that left_container_top should be inside left_container<br />
<br />
left_container_bottom = Geyser.Container:new({<br />
name = "left_container_bottom",<br />
x=0, y="50%", -- this container starts halfway down the first one<br />
width = "100%", height="50%", -- and has the same half height of the original container<br />
}, left_container) <br />
</syntaxhighlight><br />
<br />
=== Aligning relative to bottom or right sides ===<br />
The aligning point within Mudlet is the top-left corner, and it's the same for the elements they are aligned - the position you specify is used by the top-left corner of the element.<br />
<br />
Using Geyser, you can align to the opposite side as well, using the coordinates in negatives, while keeping the dimensions of the object in mind. For example, if you want to align a box that's 20px wide on the usual left side, you'd give it a width of 20 and an x value of 0. If you'd like to align it on the right side, then you'd give it an x value of -20. The box will spawn 20px away from the right side and "grow" to the right by 20px.<br />
<br />
<syntaxhighlight lang="lua"><br />
right_container = Geyser.Container:new({<br />
name = "right_container",<br />
x="-20%", y=0, -- makes the container start 20% of the screen away from the right side<br />
width = "20%", height="50%", -- filling it up until the end<br />
}) <br />
</syntaxhighlight><br />
<br />
Do make sure to account for the scrollbar, as Mudlet UI elements can overlap it. You can also move the scrollbar with [[Manual:UI_Functions#setBorderRight|setBorderRight()]].<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html Geyser.Label]==<br />
Labels allow you to use pictures in your interface, as well as nicely-formatted text - see docs for label [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html functions].<br />
<br />
=== Basic label ===<br />
<br />
Here's an example to get you started with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
</syntaxhighlight><br />
<br />
This labels '''x''' coordinate is specified as 50% - and because it's not attached to any container, this implies that the window will start halfway at the main window. You can tell it's not attached to a container because there's nothing in between the last ''}'' and '')'', the place where the container goes.<br />
<br />
The '''y''' coordinate is 0 - which means that the label will start at the top of the screen. With the width being 50%, the label will occupy 50% of the screen - and since it starts at the halfway point, it means it'll occupy the entire right side. A height of 100% means that it'll stretch from the top to the full bottom.<br />
<br />
Here's what that'll look like:<br />
<br />
[[File:Simple-label.png|center|600px]]<br />
<br />
<br />
Playing around with the starting location and dimensions, we can also place it in the center of the screen with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
})<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
[[File:Simple_label_centered.png|center|600px]]<br />
<br />
To change the message on a label, you can use the ''mylabel:echo()'' function, where ''mylabel'' is the name of the label you gave it:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("hello!")<br />
</syntaxhighlight><br />
<br />
To get rid of the label, use the '':hide()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:hide()<br />
</syntaxhighlight><br />
<br />
=== Coloring text ===<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black", -- default text colour<br />
color = "SeaGreen" -- default label background<br />
})<br />
<br />
-- You can also change colour of text on demand with:<br />
testlabel:echo[[<p style="color:blue;">You can change the text color of a whole sentence or paragraph...</p><p>...or you can change the text color of one <span style="color:green;">word</span> or even a single l<span style="color:red;">e</span>tter.</p>]]<br />
</syntaxhighlight><br />
<br />
=== Setting the font size ===<br />
<br />
To set a different font size for your Label, use the ''setFontSize()'' method. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel:setFontSize(14)<br />
</syntaxhighlight><br />
<br />
The font size is set in Pt, so anything above 30 will likely be too large to be useful.<br />
<br />
=== Label inside a container ===<br />
<br />
Once you've got your containers and mastered the basic labels, you can drop labels into your nicely-organized containers. Doing so is similar to nesting containers:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
}, left_container_bottom) -- this is where we tell it what container to go into<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
That label is exactly the same as the one above that goes across the screen, except it's in our bottom-left container - so it looks appropriately different:<br />
<br />
[[File:Label in a container.png|center]]<br />
<br />
=== Image on a label ===<br />
One of the more amazing things labels allow you to do is put pictures anywhere on your Mudlet screen, that blend in very well. To do so, once the label is created, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setBackgroundImage setBackgroundImage()] function with the exact path to the image ([[File:Skullface.png]]):<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 0, y = "-14px",<br />
width = "16px", height = "14px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/skullface.png]]) -- update location to actual image location on your computer<br />
</syntaxhighlight><br />
<br />
This'll plop the picture to the bottom-left of your screen. To make the picture show, download the skullface picture above - save it to your desktop, and adjust the location of the image within [[]]'s to what it is on your computer. For example, if you saved this on your Windows 7 desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[C:/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
(yes, that's / and not \ - \ has been known not to work)<br />
<br />
If you saved this on your Mac desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
If you saved this on your Ubuntu desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/home/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
Using this basic building block, you can work up to making yourself a UI!<br />
<br />
=== Stretching an image on a label ===<br />
If you'd like your image not to keep its original size, but instead use up the available space of the label - you can use the [http://doc.qt.io/qt-5/stylesheet-reference.html#border-image border-image] stylesheet property to do so.<br />
<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- change the location to your picture<br />
-- on windows, use / to separate folders still, not \<br />
label:setStyleSheet[[<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);<br />
]]<br />
</syntaxhighlight><br />
<br />
{{note}} If you're on a Mudlet earlier than 3.15 and are having difficulty with the image coming up, it may be because of strange differences between Qt's CSS engine which does not affect mudlet's Lua. You may want to try appending :gsub("\\","/") to your string including getMudletHomeDir() (e.g. <code>getMudletHomeDir():gsub("\\","/")</code>). No longer necessary after Mudlet 3.15.<br />
<br />
=== Aligning an image within a label ===<br />
You can use background-image in combination with background-position to align an image within a label (if, say, the image is much smaller than the label).<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this will set and align an image top-right of the label<br />
if stunning then<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-ok.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
else<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-no.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
end<br />
</syntaxhighlight><br />
<br />
=== Showing / hiding a label ===<br />
You can show and hide labels, as you can any container, miniconsole or a gauge in Geyser with [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:show Geyser.Container:show()] and [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:hide Geyser.Container:hide()]. Remember that since labels are a type of a container, all container functions work on them.<br />
<br />
Hiding a label will allow you to click through on what is below the label, as well as free up the visual space for something else.<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- hide the label with:<br />
testlabel:hide()<br />
<br />
-- show the label with:<br />
testlabel:show()<br />
</syntaxhighlight><br />
<br />
=== Clickable images ===<br />
Tacking onto the fact that you can plop images anywhere on your Mudlet screen now, you can also make them react to your clicks. You can do so with the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setClickCallback setClickCallback()] function - by giving it a function to call when your label is clicked, you'll make it react.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "-215px", y = "0px",<br />
width = "200px", height = "200px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/qubodup-opengameart-cc0-200px-missile_icon.png]]) -- update location to actual image location on your computer<br />
picture_label:setClickCallback("on_bomb_press")<br />
<br />
function on_bomb_press()<br />
send("say BOOM!")<br />
end<br />
</syntaxhighlight><br />
<br />
That's it! Pressing on the image will make the ''on_bomb_press()'' function go off, which will do its code of ''send("say BOOM!")''. Download the picture for use [http://opengameart.org/content/missile-rts-icon here].<br />
<br />
[[File:Clickable_image.png|500px|center]]<br />
<br />
=== Styling labels ===<br />
Besides putting text or images on labels, you can also style them using Qt's stylesheets feature. Doing so allows you to create various graphics that make the label look more appealing:<br />
<br />
[[File:Label_styling_examples.png|center]]<br />
<br />
To set a stylesheet on a label, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setStyleSheet Geyser.Label:setStyleSheet()] function on your label, describing the stylesheet you'd like to give it. A stylesheet consists of properties you set - for example the background color, borders, padding, and so forth. You describe properties in the following format: ''property name''''':'''''values''''';'''. See here for a [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties list of all supported properties]. For example, to make your labels background be yellow, you'd use the background-color property:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "mylabel",<br />
x = "50%", y = "50%",<br />
width = 200, height = 100<br />
})<br />
<br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet.png|center]]<br />
<br />
Which is nice, but not particularly impressive.<br />
<br />
Scrolling down the list of properties, you'll come along a border one. Plopping it into our stylesheet nets the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
border: 5px solid white;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border.png|center]]<br />
<br />
Which gives a border!<br />
<br />
Fiddling with it some more and applying new properties we find on that page, we get a rounded border on our label:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: grey;<br />
border-width: 15px;<br />
border-style: solid;<br />
border-color: green;<br />
border-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border_radius.png|center]]<br />
<br />
Which'll conclude our exploration for now. Try out all of the other possible options available there - there's loads, from [http://doc.qt.io/qt-5/stylesheet-reference.html#border-style funky borders], to tiling images and fancy color combinations using gradients.<br />
<br />
You should also check out [[Manual:Geyser#Geyser.StyleSheet|Geyser.StyleSheet]] for a way to manage your stylesheets with adjustable properties and the ability to take defaults from another stylesheet.<br />
<br />
=== Adding a tooltip to a label ===<br />
<br />
Since Mudlet 4.6, you can now add a tooltip to labels and gauges. You can start by making a simple label and echoing some text to it:<br />
<br />
<syntaxhighlight lang="lua"><br />
testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = "50%",<br />
y = "50%",<br />
height = "25%",<br />
width = "25%",<br />
})<br />
testLabel:echo("This is on the label!")<br />
testLabel:setAlignment("center")<br />
-- sets the tooltip text<br />
testLabel:setToolTip("This is the tooltip", "10")<br />
<br />
<br />
-- optionally - you can customise the tooltip, too!<br />
testLabel:setStyleSheet("QToolTip{background: yellow; color: blue; border:none;}")<br />
</syntaxhighlight><br />
<br />
Without tooltip<br />
[[File:TestLabelForTooltips.png|thumb|center]]<br />
<br />
With tooltip<br />
<br />
[[File:LabelTooltip.png|thumb|center]]<br />
<br />
=== Avoid stylesheet inheritance by tooltip ===<br />
<br />
{{note}} If you set a new stylesheet for a label and with that a background image it is possible that through inheritance the tooltip also has this stylesheet image.<br />
<br />
To avoid this specify that the stylesheet is meant for the Label by using QLabel{...} in your Label stylesheet for exampleː<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- by using QLabel{...} the stylesheet won't be given to the tooltip as well<br />
label:setStyleSheet[[<br />
QLabel{<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);}<br />
]]<br />
</syntaxhighlight><br />
<br />
<br />
=== Aligning text/images inside a label ===<br />
By default, text is [http://qt-project.org/doc/qt-5/qlabel.html#alignment-prop centered vertically and left aligned] in a label. To align it to a specific side, use the stylesheets we learnt about earlier with the qproperty-alignment:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- specify one property this way:<br />
mylabel:setStyleSheet([[qproperty-alignment: 'AlignTop';]])<br />
<br />
-- or multiple ones separated with a |, for example this will align text to top-left:<br />
mylabel:setStyleSheet([[<br />
qproperty-alignment: 'AlignLeft | AlignTop';<br />
]])<br />
<br />
mylabel:echo("hi!")<br />
</syntaxhighlight><br />
<br />
[[File:Text_aligned.png|center]]<br />
<br />
=== Enabling wordwrap in a label ===<br />
If you need to enable word wrapping in a label (which by default is off), add the following line to the labels stylesheet:<br />
<br />
qproperty-wordWrap: true;<br />
<br />
As an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
If you'd like to set multiple properties, set them all at once - not via multiple :setStyleSheet() calls:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background: red;<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Adding a hover effect to a label ===<br />
The labels support adding stylesheets for specific cases, such as when a mouse is [http://doc.qt.io/qt-5/stylesheet-reference.html#hover-ps hovering] over them. To make this work, you provide CSS for when the label is in its usual state, and for when it is hovered over:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this example will add a border to the label when it is hovered over<br />
mylabell:setStyleSheet([[<br />
QLabel{ border-radius: 4px; }<br />
QLabel::hover{<br />
background-color: rgba(0,0,0,0%);<br />
border: 4px double green;<br />
border-radius: 4px;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Checkboxes ===<br />
Combining the fact that you can click on a label with an image to do something with the fact that you can change pictures on a label at will, you can make an image that changes itself when you click on it.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "50%", y = "50%",<br />
width = "21px", height = "19px"<br />
})<br />
-- a little trick we do to make the background of the label be transparent<br />
picture_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
picture_label:setClickCallback("on_checkbox_press")<br />
<br />
function on_checkbox_press()<br />
if checkbox_ticked then<br />
checkbox_ticked = false<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_unticked.png]])<br />
echo("Checkbox unticked.\n")<br />
else<br />
checkbox_ticked = true<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
echo("Checkbox TICKED!\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
The ''on_checkbox_press()'' function this time keeps the track of the checkbox with the ''checkbox_ticked'' variable and sets the image appropriately. You can download the ticked ([[File:Checkbox_ticked.png]]) and unticked images ([[File:Checkbox_unticked.png]]) or the [http://wiki.mudlet.org/images/6/6d/Checkbox.mpackage whole package] altogether.<br />
<br />
[[File:Checkbox_demo.png|500px|center]]<br />
<br />
=== Animated labels with sprites ===<br />
You can animate sprite packs using timers. Assuming you have the sprite pack downloaded, try this example:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 10, y = "-24px",<br />
width = "16px", height = "14px",<br />
})<br />
<br />
santa_counter = nil<br />
<br />
function animate_santa()<br />
santa_counter = (santa_counter or 0) + 1<br />
if santa_counter > 8 then santa_counter = 1 end<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/santa/santa]]..santa_counter..[[.png]]) -- update location to actual image location on your computer<br />
santa_timer = tempTimer(.16, animate_santa)<br />
end<br />
<br />
animate_santa()<br />
</syntaxhighlight><br />
<br />
The completed package is available [http://wiki.mudlet.org/images/6/6b/Dancing-santa.mpackage here], install it and do '''start/end animation''' to watch.<br />
<br />
=== Inserting extra spaces and newlines ===<br />
Echoing text into Mudlet and Geyser labels is different from miniconsoles and the main window, due to their nature. One of the differences is that extra spaces in a label, by default, get compressed down to one. '''To add extra spaces in a label''', replace extra spaces with '''&amp;nbsp;''' or by wrapping your text with them inside '''<nowiki><pre>my text here</pre></nowiki>'''.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this won't work, it'll show as one space:<br />
mylabel:echo("You -> point")<br />
<br />
-- but this would, because it replaces all spaces with &nbsp before echoing<br />
mylabel:echo(string.gsub("You -> point", " ", "&nbsp;"))<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- here is another way to go about this - and it additionally makes the font be monospaced:<br />
mylabel:echo("<pre>You -> point</pre>")<br />
</syntaxhighlight><br />
<br />
'''To add a new line in a label''' (aka linebreak), use '''<nowiki><br></nowiki>''' (instead of ''\n'' as you are used to in an echo).<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("These<br>words<br>are<br>split")<br />
</syntaxhighlight><br />
<br />
=== Transparent labels ===<br />
One of the possible ways of achieving transparency on a label is to add <code>background-color: rgba(0,0,0,0%);</code> to its stylesheet. Here's an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
my_transparent_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
</syntaxhighlight><br />
<br />
Want to get transparency in a miniconsole? You can [[Manual:Geyser#Change_your_miniconsole_background_image|do that as well]].<br />
<br />
=== Custom mouse cursor ===<br />
You can change the shape of the cursor when it's over your label with:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCursor("Forbidden") -- will change your mouse cursor to "forbidden" (as in "can't do this") cursor<br />
</syntaxhighlight><br />
Possible cursor shapes are [[CursorShapes| available here]], and you can import this [[Media:Cursor grid.zip|demo package]] to try them all out.<br />
<br />
It is also possible to change the mouse cursor to a custom made cursor by:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCustomCursor(getMudletHomeDir().."/custom_cursor.png")<br />
</syntaxhighlight><br />
It is recommended that the custom cursor is a png with size of 32x32 to be supported on all systems.<br />
<br />
[[File:Changecursoroverlabel.gif]]<br />
<br />
{{Note}} Available in Mudlet 4.8+<br />
<br />
=== Flyout Labels ===<br />
<br />
Flyout labels allow you to create 'dropdown' or 'flyout' menus - menus that reveal more items once you hover your mouse over them. To create flyout labels:<br />
# add <code>nestable=true</code> (left click to open menu) or <code>nestflyout=true</code> (mouse hover to open menu) to your main label.<br />
# use [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] on your main label to add flyout labels to it.<br />
## [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] uses the same arguments as when creating a new label but also takes the '''layoutDir''' option to specify in which direction and axis should the labels align, where 2 letters combine into the option: first letter R for right, L for left, T for top, B for bottom, followed by the orientation: V for vertical or H for horizontal. So options are: <code>layoutDir="RV"</code>, <code>layoutDir="RH"</code>, <code>layoutDir="LV"</code>, <code>layoutDir="LH"</code>, and so on.<br />
# optionally, add <code>flyOut=true</code> to your flyout labels to make the labels dissapear when the mouse isn't hovering over them anymore.<br />
<br />
Note that the main flyout label cannot go into a container and needs to be on its own.<br />
<br />
{{note}} Requires Mudlet 3.0.<br />
<br />
==== Demo ====<br />
Here's an example that follows the steps above:<br />
<br />
<syntaxhighlight lang="lua"><br />
label0 = Geyser.Label:new({name="label0", <br />
x="50%",y="50%",height=50,width=300,nestable=true, <br />
message="<center>Clicky clicky</center>"})<br />
<br />
-- and add 3 labels to it with RV layout - so Right of the label, aligned Vertically<br />
label1 = label0:addChild({name="label1",height=30,width=70, layoutDir="RV", flyOut=true, message="label one"})<br />
label1:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label2 = label0:addChild({name="label2",height=30,width=70, layoutDir="RV", flyOut=true, message="label two"}) <br />
label2:setStyleSheet([[background-color: green; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label3 = label0:addChild({name="label3",height=30,width=70, layoutDir="RV", flyOut=true, message="label three"})<br />
label3:setStyleSheet([[background-color: red; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
</syntaxhighlight><br />
<br />
A more thorough example. Try it out to see what you can create with flyout labels:<br />
<syntaxhighlight lang="lua"><br />
-- create a label with a nestable=true property to say that it can nest labels<br />
mainlabel = Geyser.Label:new({name="testa", x=400,y=50,height=50,width=300,nestflyout=true, message="<center>HOVER HERE TO SEE FLY-OUT LABELS!</center>"})<br />
<br />
-- create 15 labels and store them in a table <br />
table_for_flyout_labels = {}<br />
for i=1,15 do<br />
-- options to layoutDir are the direction the window should go (R for right, L for left, T for top, B for bottom), followed by how the nested labels should be oriented (V for vertical or H for horizontal). So "BH" here means it'll go on the bottom of the label, while expanding horizontally<br />
table_for_flyout_labels[i] = mainlabel:addChild({name="test"..tostring(i),height=30,width=70, layoutDir="BH", flyOut=true, message="test"..tostring(i)})<br />
<br />
table_for_flyout_labels[i]:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px;]])<br />
end<br />
<br />
-- make the test5 label look a bit special as it has got a surprise<br />
table_for_flyout_labels[5]:echo("Hover here")<br />
<br />
-- add even more nested labels to the 5th label!<br />
even_more_flyout_labels = {}<br />
for i=1,60 do<br />
-- here, the layout will be to the right of it, while expanding vertically<br />
even_more_flyout_labels[i]=table_for_flyout_labels[5]:addChild({name="hover label "..tostring(i),height=30,width=100, layoutDir="RV", flyOut=true, message="label "..tostring(i)})<br />
even_more_flyout_labels[i]:setClickCallback("testFunc", even_more_flyout_labels[i].name)<br />
even_more_flyout_labels[i]:setStyleSheet([[background-color: grey; border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]])<br />
end<br />
<br />
function testFunc(name)<br />
display(name)<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look something like this: <br />
<br />
[[File:Flyout_labels_demo.png|150px]]<br />
<br />
==== Demo of layouts ====<br />
Here's another demo that explains all of the layout styles quite well:<br />
<syntaxhighlight lang="lua"><br />
local directions = {"R", "L", "T", "B"}<br />
local orientations = {"V", "H"}<br />
local mappings = {R = "right", L = "left", T = "top", B = "bottom", V = "vertical", H = "horizontal"}<br />
<br />
local combinations, combination_labels = {}, {}<br />
for _, direction in pairs(directions) do<br />
for _, orientation in pairs(orientations) do<br />
combinations[#combinations+1] = direction..orientation<br />
end<br />
end<br />
<br />
local function get_foreground_text_colour(r,g,b)<br />
local luminosity = (0.2126 * ((r/255)^2.2)) + (0.7152 * ((g/255)^2.2)) + (0.0722 * ((b /255)^2.2))<br />
if luminosity > 0.5 then<br />
return "black"<br />
else<br />
return "white"<br />
end<br />
end<br />
<br />
local function get_random_colour_rgb()<br />
return math.random(1,255), math.random(1,255), math.random(1,255)<br />
end<br />
<br />
-- create a label with a nestable=true property to say that it can nest labels<br />
all_possible_combinations_label = Geyser.Label:new({name="all_possible_combinations_label", x=0,y="-400",height=50,width=500,<br />
nestable = true, message="<center>Click to see a listing of possible combinations</center>"})<br />
<br />
for i = 1, #combinations do<br />
local combination = combinations[i]<br />
combination_labels[i] = all_possible_combinations_label:addChild({name="combo_"..combination,height=30,width=150, nestable = true, flyOut=true, layoutDir="BH", message="<center>Combination "..combination.."</center>"})<br />
<br />
local r,g,b = get_random_colour_rgb()<br />
local text_colour = get_foreground_text_colour(r,g,b)<br />
<br />
local combination_labels_children = {}<br />
for ii = 1, 3 do<br />
combination_labels_children[ii] = combination_labels[i]:addChild({<br />
name="combo_"..combination.."_"..ii, height = 30, width = 150, layoutDir=combination, flyOut = true,<br />
message = string.format("<center><b>%s</b>%s+<b>%s</b>%s layout</center>", <br />
combination:sub(1,1), mappings[combination:sub(1,1)]:sub(2), combination:sub(2,2), mappings[combination:sub(2,2)]:sub(2)),<br />
fgColor = text_colour})<br />
<br />
combination_labels_children[ii]:setStyleSheet(string.format([[background-color:rgb(%d, %d, %d); border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]], r,g,b))<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look like this:<br />
<br />
[[File:Flyoutlabels-layout-demo.png]]<br />
<br />
=== Geyser.Label right click menu ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
You can create a right click menu for a label just by using the function (assuming your label name is 'myLabel'):<br />
<syntaxhighlight lang="lua"> myLabelːcreateRightClickMenu({MenuItems = menuTable}) -- scroll down for a fuller example with more details </syntaxhighlight><br />
<br />
The menu table comprises of all the items and their names. To create a parent menu just create a nested table of names.<br />
<br />
Example of a menuTable:<br />
<syntaxhighlight lang="lua"> menuTable = {"First Item", "Second Item (Parent)", {"First ChildItem", "Second ChildItem"}, "Third Item"} </syntaxhighlight><br />
<br />
The menu would look like thisː<br />
<br />
[[File:RCDemo1.gif|250px]]<br />
<br />
You can give more constraints to further style and enhance your right click menu.<br />
<br />
==== Style your right click menu ====<br />
Your right click menu has 2 default styles integratedː "light" and "dark" which are defined by the constraint "Style".<br />
<br />
To set a default style just give the constraint Style the preferred value, for exampleː<br />
<syntaxhighlight lang="lua"> Style = "dark" </syntaxhighlight><br />
<br />
To give different levels of your menu different style just add the number of the level to the constraint, for exampleː<br />
<syntaxhighlight lang="lua"> Style2 = "light" -- Gives the second level of your menu the "light" style</syntaxhighlight><br />
<br />
For adding your own stylesheet use the constraint MenuStyle (use the same method as above to define stylesheets for different levels)<br />
<syntaxhighlight lang="lua"> MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]] <br />
-- Gives the second level of your menu this stylesheet</syntaxhighlight><br />
<br />
The same methods are used for defining the format, width and height for the menu item.<br />
<syntaxhighlight lang="lua"> <br />
MenuWidth = 70 -- standard menu width if nothing else is given<br />
MenuWidth2 = 80 -- menu width for the second level <br />
MenuFormat1 = "c10" -- menu format for the first level (format works like any other label echo format, in this case c is center and 10 is the font-size)<br />
MenuHeight = 30<br />
</syntaxhighlight><br />
<br />
==== Set onClick action for your menu item ====<br />
To set an action if your menu item is clicked use the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<syntaxhighlight lang="lua"> <br />
myLabelːsetMenuAction("First Item", function() echo("Clicked on the first item\n") end<br />
myLabelːsetMenuAction("Second Item (Parent).First ChildItem", function() echo("Clicked on the first child item\n") end) -- To set an action to a child item find it by using "Parent.Child" as name (only one parent is needed to be given the parents parent is not needed)<br />
</syntaxhighlight><br />
<br />
==== Access an menu item directly ====<br />
The simplest way to access a menu item directly is by just using the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<br />
For example to change the menu item textː<br />
<syntaxhighlight lang="lua"> <br />
myLabelːfindMenuElement("First Item"):echo([[my first Item]])<br />
</syntaxhighlight><br />
<br />
==== Right click menu example ====<br />
Better then any further explanation is probably this practical example. <br />
<br />
<syntaxhighlight lang="lua"> <br />
-- create the label the right click menu will be in<br />
myRightClickLabel = myRightClickLabel or Geyser.Label:new({<br />
name = "myRightClickLabel", message = "Please right click!", <br />
format = "cb15", x=10, y=10, width ="30%", height = "15%", <br />
color = "purple"})<br />
<br />
-- right click menu creation with custom styleheet on level2 and default "Dark" style <br />
myRightClickLabel:createRightClickMenu({<br />
MenuItems = {"Emergency", "Drink",{"ManaPotion","HealthPotion"}, "Disappear", "Cast",{"Blindness", "Blink"}}, <br />
Style = "Dark", <br />
MenuWidth2 = 80, <br />
MenuFormat1 = "c10",<br />
MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]]<br />
})<br />
<br />
myRightClickLabel:setMenuAction("Emergency", function() <br />
cecho("<red:pink>[Emergency Mode] Run as fast as possible!\n") <br />
send("emergency") <br />
closeAllLevels(myRightClickLabel) -- this can be used to close the right click menu if clicked on this item<br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.ManaPotion", function()<br />
cecho("<blue>Drinking my mana potion.\n") <br />
send("drink mp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.HealthPotion", function() <br />
cecho("<red>Drinking my health potion.\n") <br />
send("drink hp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Disappear", function() <br />
cecho("<grey>Disappearing.. \n") <br />
send("disappear") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blindness", function() <br />
cecho("<light_blue>Casting blindness \n") <br />
send("cast blindness enemy") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blink", function() <br />
cecho("<light_blue>Casting blink \n") <br />
send("cast blink") <br />
end )<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
<br />
[[File:Right click example demo.gif]]<br />
<br />
==== Add right click menu to label with already existing left click action ====<br />
If your label has an already existing left click action you'll have to create the right click menu<br />
"before" creating the labels "setClickCallBack" action and then just put into your labels onClick function<br />
(assuming your label name is 'myLabel' and 'event' is the last parameter of your onClick function)<br />
<br />
<syntaxhighlight lang="lua"> <br />
myLabel:onRightClick(event)<br />
</syntaxhighlight><br />
<br />
=== Geyser name ===<br />
Make sure to give your Geyser Labels, miniconsoles, and userwindows a <code>name</code> - while it'll technically work without one, items will be duplicated when you re-save them if they're lacking a name.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserStyleSheet.html Geyser.StyleSheet]==<br />
<br />
Allows you to create a managed stylesheet to make it easier to set and change properties. Also allows you to inherit properties from another stylesheet, making it easier to manage multiple styles at once.<br />
<br />
=== Basic Usage ===<br />
<br />
Here's an example to get you started. This creates a basic stylesheet to set the background color black and the foreground/text color to green, then applies it to a Geyser Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
local testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = 100,<br />
y = 100,<br />
height = 100,<br />
width = 300,<br />
stylesheet = stylesheet:getCSS(),<br />
})<br />
<br />
-- Alternate method of creating a stylesheet using a table of properties<br />
local stylesheet = Geyser.StyleSheet:new({<br />
['background-color'] = "black",<br />
['color'] = "green",<br />
})<br />
</syntaxhighlight><br />
<br />
=== Getting the CSS string === <br />
<br />
As shown above, you can use getCSS to get the stylesheet as a string.<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getCSS())<br />
--[[<br />
"background-color: black;\ncolor: green;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Including a target ===<br />
<br />
You can include a 'target' for your stylesheet to be applied to, such as QLabel, QPlainTextEdit, etc.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- QPlainTextEdit is useful for styling command lines in particular, to keep the style from bleeding into any associated miniconsole or userwindow.<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
QPlainTextEdit {<br />
background-color: black;<br />
color: green;<br />
}]])<br />
<br />
-- or as an optional third argument. Passing nil for the parent explicitly <br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]], nil, "QPlainTextEdit")<br />
<br />
-- or using the setTarget function after the fact<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
stylesheet:setTarget("QPlainTextEdit")<br />
</syntaxhighlight><br />
<br />
=== Changing a property ===<br />
<br />
Assuming you started with the example above, if you wanted to change the background color to purple you would do the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("background-color", "purple")<br />
testLabel:setStyleSheet(stylesheet:getCSS())<br />
</syntaxhighlight><br />
<br />
Or if you wanted to set the font, you would do:<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", [["Ubuntu Mono"]])<br />
</syntaxhighlight><br />
<br />
Note the way we set the font with the double quotes included in the string, this is because the quotes have to be there in the final stylesheet. You could use single quotes instead of the bracket notation as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", '"Ubuntu Mono"')<br />
</syntaxhighlight><br />
<br />
=== Getting the value of a property ===<br />
<br />
Again assuming you started with the example code above it's as easy as<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:get("color") -- will return "green"<br />
</syntaxhighlight><br />
<br />
=== Getting a table of properties and their values ===<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Setting the properties via table ===<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setStyleTable({<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"',<br />
})<br />
</syntaxhighlight><br />
<br />
=== Resetting the style with a string ===<br />
<br />
Creating a new Geyser.StyleSheet would break any inheritance for stylesheets which had this one as a parent (see below), so if you wish to reset the style via CSS string you should use :setCSS<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setCSS([[<br />
background-color: black;<br />
color: green;<br />
font: "Ubuntu Mono";<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Inheriting properties ===<br />
<br />
As with most things Geyser, just pass the parent in when you create the new stylesheet<br />
<br />
<syntaxhighlight lang="lua"><br />
local childsheet = Geyser.StyleSheet:new("color: blue;", stylesheet)<br />
display(childsheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "blue",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
<br />
display(childsheet:get("background-color")<br />
--"purple"<br />
<br />
-- show only properties set in this stylesheet, without inheritance<br />
display(childsheet:getStyleTable(false))<br />
--[[<br />
{<br />
color = "blue"<br />
}<br />
--]]<br />
<br />
-- can do the same for the CSS string<br />
display(childsheet:getCSS(false))<br />
--[[<br />
"color: blue;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html Geyser.MiniConsole]==<br />
This allows you to spawn a Mudlet miniconsole - unlike labels, these aren't as styleable, but they do format text better. They make a good fit for text-based menus, chat and map capture, and other things.<br />
<br />
Spawning one is very similar to other Geyser elements - paste this into a new script:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x="70%", y="50%",<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="30%", height="50%",<br />
})<br />
</syntaxhighlight><br />
<br />
This'll make you one at the bottom-right of the screen. The miniconsole will have a grey background by default, but you can set it to any color you'd like with [http://www.mudlet.org/geyser/files/geyser/GeyserWindow.html#Geyser.Window:setColor miniconsole:setColor()]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setColor("black") -- give it a nice black background<br />
</syntaxhighlight><br />
<br />
A special dimension property that MiniConsoles have is a character - instead of specifying a miniconsole to be % of a container or a certain number of pixels, you can specify it as a certain number of characters. You do this by using "c" at the end of a number. This way, you can, for example, specify miniconsole to be 10 letters long and 2 lines high:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="70%", y="50%",<br />
wrapAt = 10,<br />
width="10c", height="2c",<br />
})<br />
flatbox:setColor("red")<br />
flatbox:echo("ABCDEFGHIJ") -- that is 10 letters<br />
</syntaxhighlight><br />
<br />
=== Adding text ===<br />
You can use [[Manual:Technical_Manual#echo|echo()]] the same way with a miniconsole to add text as to the usual window:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("hello!")<br />
</syntaxhighlight><br />
<br />
As well as [[Manual:Technical_Manual#cecho|cecho]], [[Manual:Technical_Manual#decho|decho]], or [[Manual:Technical_Manual#hecho|hecho]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:cecho("<green>hey, <blue>colored <red>text!\n")<br />
</syntaxhighlight><br />
<br />
=== Copying lines with color ===<br />
To copy a line over to the miniconsole, as it is from the game with all colors preserved, you can [[Manual:UI_Functions#selectCurrentLine|select]], [[Manual:UI_Functions#copy|copy]], and [[Manual:UI_Functions#appendBuffer|append]] it. For an example, try making a trigger with this as the ''perl regex'' pattern type:<br />
<br />
<syntaxhighlight lang="lua"><br />
^<br />
</syntaxhighlight><br />
<br />
That'll make the trigger go off on every line. Then give it the following script (assumed you have made the HelloWorld miniconsole from earlier):<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
... and you'll see all MUD output duplicated exactly as it is to the miniconsole. Amazing! It's very efficient as well, so you can have many miniconsoles, even in spam, not lag you down.<br />
<br />
=== Clearing the miniconsole ===<br />
Clearing the miniconsole just requires using the following script (assumes you have made the HelloWorld miniconsole from earlier):<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:clear()<br />
</syntaxhighlight><br />
<br />
=== Doing edits in copied lines ===<br />
Sometimes you'll want to edit the line before stuffing it into the miniconsole. For example, if you're making a chat capture, you'd want to condense a really long org name into something that's more space-friendly.<br />
<br />
To do so, you'd use the [[Manual:Technical_Manual#selectString|selectString()]] the text you'd like to modify, [[Manual:Technical_Manual#replace|replace()]] it with a different one:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Your", 1) -- select the word you'd like to replace - in this case, 'Your'<br />
setBgColor(getBgColor()) -- preserve the background color in the replacement<br />
setFgColor(getFgColor()) -- preserve the foreground color in the replacement<br />
replace("Mine") -- replace the selection with the wird 'Mine'<br />
<br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
=== Gagging from the main window ===<br />
If you'd like to gag the line from the main window so it only shows up in your miniconsole, [[Manual:Technical_Manual#deleteLine|delete]] it after moving it over:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=== Clickable menus ===<br />
Using the [[Manual:Technical_Manual#echoLink|echoLink]], [[Manual:Technical_Manual#insertLink|insertLink]] and [[Manual:Technical_Manual#setLink|setLink]] functions, you can turn text into one that reacts on a click. Combined with your power of placing text anywhere on the screen with a miniconsole, you can make menus with options. Here is one such example, where selecting an item causes an echo to happen:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="20%", y="80%",<br />
width="40c", height="4c",<br />
})<br />
flatbox:setColor("red")<br />
clearWindow("flatbox")<br />
<br />
flatbox:cecho("<white:red>Choose one of the following options:\n")<br />
<br />
flatbox:fg("white")<br />
flatbox:bg("red")<br />
<br />
for _, fruit in ipairs{"banana", "apple", "orange"} do<br />
echoLink("flatbox", "* "..fruit:title().."\n", [[echo("You picked ]]..fruit..[[\n")]], "The "..fruit.." option", true)<br />
end<br />
<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
This will produce something like the following:<br />
<br />
[[File:Fruit_menu.png|center]]<br />
<br />
=== Change your miniconsole background image ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
To set a custom background image for your miniconsole, use [https://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html#Geyser.MiniConsole:setBackgroundImage :setBackgroundImage()]:<br />
<syntaxhighlight lang="lua"><br />
miniconsole_withBgImg = Geyser.MiniConsole:new({name = "BackgroundonConsole", x="50%", y="50%", width = "20%", height = "40%"})<br />
miniconsole_withBgImg:setBackgroundImage(":/Mudlet_splashscreen_development.png", "center")<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:decho("<:0,0,0,130> This is a decho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:hecho("#,80000000 This is a hecho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:decho("<:0,0,0> This is a decho test with no transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:hecho("#,000000 This is a hecho test with no transparent background\n")<br />
end<br />
</syntaxhighlight><br />
<br />
=== Enable and use your miniconsole command line ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Every miniconsole has a hidden command line. Enable it with:<br />
<syntaxhighlight lang="lua"><br />
HelloWorldContainer = HelloWorldContainer or Adjustable.Container:new({name="HelloWorldContainer", titleText = "Container with a command line"})<br />
<br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "purple",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, HelloWorldContainer)<br />
<br />
HelloWorld:enableCommandLine()<br />
</syntaxhighlight><br />
<br />
=== Set an action to your miniconsole command line ===<br />
If no action is set to your miniconsole command line the commands are send to the game the same way as for the main command line. Aliases still work as usual, and if you have command echo enabled in preferences, it'll show in both miniconsole and the main window.<br />
<br />
It is also possible to set an action to your command line, this enables you to use the command line as custom text input.<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:enableCommandLine()<br />
local function channelChat(text)<br />
send("chat "..text)<br />
HelloWorld:echo("[chat] " ..text.."\n")<br />
end<br />
<br />
HelloWorld:setCmdAction(channelChat)<br />
</syntaxhighlight><br />
<br />
This will send your miniconsole command line input to the chat channel.<br />
<br />
More complicated/sophisticated actions are possible, setCmdAction works the same way as the Label clickCallback functions - that is, you can pass arguments to it.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html Geyser.Gauge]==<br />
<!--<br />
This is a composite window. Gauge duplicates the functionality of the built in Mudlet gauges, but in a clean and easily extended way. Internally, a Geyser Gauge is a container holding two Labels, front and back, which are initially scaled to fill the entire Gauge container. Hence, a gauge, g, can be given callbacks with the g.front:setClickCallback() method.<br />
<br />
The backgroundColor parameter initially sets the colors of the gauge, but of course the front and back components can be accessed individually as labels for high control over their looks. Gauges can be horizontal or vertical and decrease in value left to right, right to left, down up or up down depending on the value of the orientation parameter.<br />
--><br />
<br />
A Gauge allows you to represent numbers on a scale - and most typically, you've seen it be used as your standard hp/mana/whatever bar. A basic bar is made similarly to other Geyser elements. To set the value on the gauge that it should represent, use the [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] function:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="5%",<br />
})<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
That'll spawn you a pretty basic gauge with a horizontal orientation and a grey colour - and as a test, with a random value.<br />
<br />
[[File:Basic_gauge.png|center]]<br />
<br />
=== Updating a gauge ===<br />
You'd want your gauge to stay in sync with your actual values. To make that happen, you want to call [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] whenever the value that the gauge is tracking changes.<br />
<br />
So for example, if you make a health bar - wherever you get your new health at (be it prompt, gmcp, atcp or whatever), update the gauge as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- theoretical example<br />
current_health, max_health = tonumber(matches[2]), tonumber(matches[3])<br />
<br />
-- update the bar<br />
hp_bar:setValue(current_health, max_health)<br />
</syntaxhighlight><br />
<br />
You can also write down how much health have you got on the bar with:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local hp = math.random(1,100) <br />
hpbar:setValue(current_health, max_health, "<b>"..max_health.."hp</b>")<br />
<br />
-- example using GMCP in IRE games:<br />
hpbar:setValue((100/gmcp.Char.Vitals.maxhp)*gmcp.Char.Vitals.hp,100,gmcp.Char.Vitals.hp)<br />
</syntaxhighlight><br />
<br />
[[File:Hpbar_basic.png|center]]<br />
<br />
=== Styling a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. Combining this with Geyser:Label.setStyleSheet, you can improve the visuals of your gauges by using Qt-supported CSS. The syntax for specifying CSS is a bit different - it requires a semicolon after every property, and is done in the format of ''property name''''':'''''values''''';'''. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here] and you can use [https://build-system.fman.io/qt-designer-download Qt Designer] to create them. Practical example:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #98f041, stop: 0.1 #8cf029, stop: 0.49 #66cc00, stop: 0.5 #52a300, stop: 1 #66cc00);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #78bd33, stop: 0.1 #6ebd20, stop: 0.49 #4c9900, stop: 0.5 #387000, stop: 1 #4c9900);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge.png|center]]<br />
<br />
The same style can be adjusted by colors to red as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f04141, stop: 0.1 #ef2929, stop: 0.49 #cc0000, stop: 0.5 #a40000, stop: 1 #cc0000);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bd3333, stop: 0.1 #bd2020, stop: 0.49 #990000, stop: 0.5 #700000, stop: 1 #990000);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge_red.png|center]]<br />
<br />
=== Updating a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. To make a gauge clickable you can set a ClickCallBack on the top label which is ''mygauge.text'' example: <syntaxhighlight lang="lua">mygauge.text:setClickCallback("functionName", variableToSendToFunctionName)</syntaxhighlight><br><br />
If you would like to have different click events for the top or back of a gauge you can enable clickThrough for the top or ''mygauge.text'' label example<br />
<br />
<syntaxhighlight lang="lua"><br />
mygauge.text:enableClickthrough()<br />
mygauge.front:setClickCallback("functionOne", variableToSendToFunctionOne)<br />
mygauge.back:setClickCallback("functionTwo", variableToSendToFunctionTwo)<br />
</syntaxhighlight><br />
<br />
<br />
=== Tooltips on gauges ===<br />
Tooltips are available since Mudlet 4.6 as explained in above section [[#Adding_a_tooltip_to_a_label]], and as gauges are really only made up of labels as well, you could add a tooltip then by just using <syntaxhighlight lang="lua">mygauge.text:setToolTip("This is the gauge's tooltip", "10")</syntaxhighlight> the same as it's handled for clickback.<br />
<br />
== HBox/VBox ==<br />
<br />
These are special types of containers. Every window in these is horizontally or vertically aligned in the order they were added.<br />
<br />
<sub>Added to Mudlet in 2.0-rc4</sub><br />
<br />
== Geyser.UserWindow ==<br />
Allows you to use Mudlets UserWindows within Geyser, which allows you to use all the functionality of a MiniConsole in its basic form.<br />
The big advantage is the possibility to add other Geyser Elements like Labels, MiniConsole, Gauges, Mappers to the UserWindow.<br />
The UserWindow then can act as container for those elements with all the perks of dynamic resizing or any other Geyser functionality.<br />
<br />
{{note}} available in Mudlet 4.6.1+<br />
<br />
===Basic floating userwindow ===<br />
This will create a movable floating userwindow.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "TestUserWindow",<br />
titleText ="My Test UserWindow", -- only available since Mudlet 4.8+<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
</syntaxhighlight><br />
<br />
You can change the title of the userwindow by using the parameger titleText and the functions below (as of Mudlet 4.8+)ː<br />
<br />
To set a new title after creation useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setTitle("My new title Text")<br />
</syntaxhighlight><br />
<br />
To revert to the standard title useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:resetTitle()<br />
</syntaxhighlight><br />
<br />
To '''save the position''' of the userwindow - say in case you've dragged it onto another monitor and would like it to stay there when you restart Mudlet - use [[Manual:UI_Functions#saveWindowLayout|saveWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
saveWindowLayout()<br />
</syntaxhighlight><br />
<br />
To restore it afterwards, use [[Manual:UI_Functions#loadWindowLayout|loadWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create your userwindows first with Geyser.UserWindow:new<br />
-- then restore them to the positions they were at:<br />
loadWindowLayout()<br />
</syntaxhighlight><br />
<br />
=== Docked UserWindow ===<br />
To create the window docked at the right side,<br />
set the variable docked (at creation of the container) to true.<br />
Be aware that with this variable set to true the position and the size at creation of the userwindow will be ignored.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true<br />
<br />
})<br />
</syntaxhighlight><br />
<br />
Since Mudlet 4.8+ it is also possible to choose the docking Position of the UserWindow at creation and by function withː<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true,<br />
dockPosition = "top" -- Possible dockPositions are left "l", right "r", top "t", bottom "b" and floating "f" <br />
})<br />
</syntaxhighlight><br />
<br />
To change it for a already created UserWindow use the function setDockPosition(dockPosition) likeː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setDockPosition("left")<br />
</syntaxhighlight><br />
<br />
=== Disable/enable UserWindow autoDock ===<br />
{{note}} available in Mudlet 4.8+<br />
<br />
The auto docking feature can be really annoying at times. To disable it use the functionsː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:disableAutoDock() -- disables autoDock. Docking still possible with ːsetDockPosition<br />
testuserwindow:enableAutoDock() -- reenables autoDock<br />
</syntaxhighlight><br />
<br />
=== Styling the UserWindow border and title area ===<br />
{{note}} available in Mudlet 4.10+ and Linux only<br />
<br />
Geyser.UserWindows can accept a stylesheet to change the appearance of the border and title area and make<br />
the UserWindow look more appealing. This unfortunately only works in Linux, as in macOS and Windows, it is the OS theme that is used here. <br />
<br />
<syntaxhighlight lang="lua"><br />
myUserWindow = myUserWindow or Geyser.UserWindow:new({<br />
name = "myUserWindow", titleText = "myUserWindow", autoDock = false<br />
})<br />
<br />
myUserWindow:setStyleSheet( <br />
[[QDockWidget{<br />
border: 1px solid green; /* UserWindow border style */<br />
font: bold 15pt "Arial"; /* Font of the titleBar */<br />
color: rgb(0,0,150); /* Font color */<br />
}<br />
<br />
QDockWidget::title{ <br />
background-color: rgb(0,255,150); /* TitleBar color */<br />
border: 2px solid red; /* TitleBar border */<br />
border-radius: 2px; /* TitleBar border radius */<br />
text-align: center; /* alignment of the titleText */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
[[File:UserWindowStyleSheet.png]]<br />
<br />
=== UserWindow as Container ===<br />
This is the feature which shows the versatile nature of Geyser.UserWindows.<br />
The UserWindow act as container and is at that possible to dynamically resize the containing Geyser Elments.<br />
Put a label in the UserWindow resize it as rectangle.<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "ParentTestUserWindow",<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
<br />
testuserwindow:setColor("dark_green") -- give the userwindow a bit of color <br />
<br />
labelinuserw = Geyser.Label:new({<br />
name = "LabelinUserWindow",<br />
x=20, y=20,<br />
width = -20, height = -20,<br />
color="light_blue", fontSize=20,<br />
},testuserwindow)<br />
<br />
labelinuserw:echo("This is a label in an userwindow", "black", "c")<br />
</syntaxhighlight><br />
[[File:LabelInUserWindow.png]]<br />
<br />
The same way you are able to add your favorite Geyser Application (like tabbed chat, animated timers, gauges) to an UserWindow.<br />
<br />
Note that you don't need to add MiniConsoles to a UserWindow - as UserWindows already have them built-in.<br />
<br />
[[File:Tabbedchatinuserwindow.png]]<br />
<br />
== Geyser.CommandLine ==<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Allows you to create your custom command lines which can resize/move like any other Geyser object.<br />
<br />
If you just need a command line which is integrated in a miniconsole or userwindow, check out [[Manual:Geyser#Enable and use your miniconsole command line|:enableCommandLine()]].<br />
<br />
=== Creating a Geyser.CommandLine ===<br />
An example to get you startedː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine = myCommandLine or Geyser.CommandLine:new({<br />
name = "myCommandLine", <br />
x = "-20%", y = -40, <br />
width = "20%", height = 40,<br />
stylesheet = "border: 1px solid silver;"<br />
})<br />
</syntaxhighlight><br />
This creates a new command line in the right bottom of your screen.<br />
<br />
=== Bind action to your command line input ===<br />
If you use your previously created command line, any command will just be send to the game, after having been checked for aliases.<br />
<br />
To react to any input in a custom manner, we can set an action to the command line and use the input as parameter.<br />
<br />
Example of a command line changing the background color of your main console (assumes you have created "myCommandLine" from earlier): <br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setAction(<br />
function(commandLineInput)<br />
r, g, b = Geyser.Color.parse(commandLineInput) -- gets the r, g, b values of the color you input to the command line<br />
if b then -- checks if the color is valid<br />
setBackgroundColor(r, g, b)<br />
else<br />
echo("\n"..commandLineInput.." is not a valid color. Try again.")<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
=== Styling a command line ===<br />
You can style your Geyser command line by using Qt-supported CSS. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here].<br />
<br />
Practical example (assuming "myCommandLine" is created)ː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setStyleSheet([[<br />
QPlainTextEdit{ /* QPlainTextEdit is used to prevent the styleSheet bleeding to the right click menu*/<br />
border: 1px solid silver; /* Command line border style */<br />
background-color: rgb(0,255,150); /* Command line background color */<br />
font: bold 12pt "Arial"; /* Font and font-size of your command line */<br />
color: rgb(0,0,150); /* Command line text color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Create an extra command line in Mudlet ===<br />
If your goal is to just have an extra command/input line - say, for role-playing purposes: copy/paste the example below into a new script in Mudletː<br />
<br />
<syntaxhighlight lang="lua"><br />
inputContainer = inputContainer or Adjustable.Container:new({<br />
x = 0, y = "-4c", <br />
name = "InputContainer", padding = 2, <br />
width = "100%", height = "4c", <br />
autoLoad = false<br />
})<br />
<br />
extraCmdLine = extraCmdLine or Geyser.CommandLine:new({<br />
name = "extraCmdLine", <br />
x = 0, y = 0, width = "100%", height = "100%"<br />
}, inputContainer)<br />
<br />
inputContainer:attachToBorder("bottom")<br />
</syntaxhighlight><br />
<br />
This will look likeː <br />
<br />
[[File:AdditionalCommandLine.png|extra command line]]<br />
<br />
== Adjustable.Container ==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
Adjustable Containers are a new "GeyserClass" which act as containers for Geyser elements, but with more flexible and user configurable features. They are referred to as "adjustable" because they can be minimized, loaded, saved, moved, adjusted in size with the mouse pointer, and attached to borders. <br />
<br />
A brief video of [https://www.youtube.com/watch?v=GT2ScizuM48&feature=youtu.be Introduction to Adjustable Containers] is available.<br />
<br />
=== Creating an Adjustable.Container ===<br />
An Adjustable.Container is created just like any other Geyser Object. For example, we might experiment with creating a new Adjustable.Container by running the following line of lua code:<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
</syntaxhighlight><br />
This will create a new Adjustable.Container with the name ''testContainer''. Specifying the adjustable container's name is important for saving. Defining a variable, such as ''testCon'' in our above example, allows functions to be used with the Adjustable.Container.<br />
<br />
Our newly created Adjustable.Container may be used the same way as any other Geyser.Container might. For example, let's put a Geyser.Label in our new testContainer:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
testLabel = Geyser.Label:new({name="myTestLabel", x=0, y=0, height="100%", width="100%", color="green"},testCon)<br />
</syntaxhighlight><br />
<br />
The above code creates a new, green-colored Geyser.Label in the ''testCon'' adjustable.container as shown below:<br />
<br />
[[File:GreenLabelinAdjustableContainer.png]]<br />
<br />
You can also create one for miniconsole:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer = miniconsoleContainer or Adjustable.Container:new({name="miniconsoleContainer"})<br />
myMiniconsole = Geyser.MiniConsole:new({<br />
name="myMiniconsole",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, miniconsoleContainer)<br />
<br />
myMiniconsole:echo("Hello!\n")<br />
</syntaxhighlight><br />
<br />
That will give you:<br />
<br />
[[File:Adjustable container miniconsole.png]]<br />
<br />
=== Key Functions ===<br />
A listing of key functions for the Adjustable.Container module can be found hereː https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html<br />
<br />
To make the Adjustable Container show on screen use the following:<syntaxhighlight lang="lua"><br />
testCon:show() --will cause the Adjustable Container to show if not showing<br />
</syntaxhighlight><br />
<br />
===<div id="valid constraints"> Valid Constraints</div>===<br />
Adjustable Container constraints and their default values can be found at [https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html#Adjustable.Container:new].<br />
<br />
These are in addition to the standard Geyser.Container constraints.<br />
<br />
=== Change Title Text ===<br />
To specify the title text of a new container, use the constraint <code>titleText</code> in the constructor (see [[Manual:Geyser#valid constraints|valid constraints]]).<br />
<br />
To change the title text after a container has already been created, use <code>setTitle</code>. Continuing from the previous example, the title for an existing container named "testCon" might be adjusted in a number of ways: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Title") -- changes the container's title to "Title"<br />
</syntaxhighlight><br />
<br />
A container's title text defaults to the color green, but this can also be adjusted by using <code>setTitle</code>: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Red Title Test","red") -- changes the container's title text to "Red Title Test" and displays the text in the specified color "red".<br />
</syntaxhighlight><br />
<br />
To restore a container's default title text, <code>setTitle</code> is issued without any specified title or color: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle() -- resets the container's title text<br />
</syntaxhighlight><br />
<br />
=== AutoSave and AutoLoad ===<br />
The following Adjustable.Container settings can be saved and loadedː<br />
<br />
<code>x</code>, <code>y</code>, <code>height</code>, <code>width</code>, <code>minimized</code>, <code>locked</code>, <code>lock Style</code>, <code>padding</code>, and <code>hidden</code>.<br />
<br />
These settings will be automatically saved when the Mudlet profile is closed, and automatically loaded when a previous Adjustable.Container is created within the corresponding profile.<br />
<br />
To prevent automatic saving and/or loading of these settings, the <code>autoLoad</code> and <code>autoSave</code> constraints can be included in the constructor. For example, the following code will prevent the settings of the ''testCon2'' Adjustable.Container from being loaded upon creation:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", autoLoad=false})<br />
</syntaxhighlight><br />
<br />
To also prevent the ''testCon2'' Adjustable.Container from automatically saving its settings when the Mudlet profile is closed, the <code>autoSave=false</code> constraint would be added at creation as follows:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCont2 = testCont2 or Adjustable.Container:new({name="testCont2", autoLoad=false, autoSave=false})<br />
</syntaxhighlight><br />
<br />
Automatic saving can also be deactivated after an Adjustable.Container has been created, by invoking <code>testCont:disableAutoSave()</code><br />
<br />
Note that even with autoSave and autoLoad disabled, it is still possible to save and load manually through the right-click menu and/or by using <code>testCont:save()</code> or <code>testCont:load()</code> in a script.<br />
<br />
To save/load all your containers manually at the same time, we use <code>Adjustable.Container:saveAll()</code> and/or <code>Adjustable.Container:loadAll()</code><br />
<br />
=== "All" Functions ===<br />
The following functions affect all Adjustable Containers at the same time.<br />
<br />
{{note}} You must create the Adjustable Containers before these functions will have an effect.<br />
<br />
<code>Adjustable.Container.loadAll()</code> loads all the settings from your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container.saveAll()</code> saves all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container.loadAll()</code> loads all the settings from your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:showAll()</code> shows all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:doAll(myfunc)</code> creates a function that will affect all your Adjustable Containers. For example:<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:hide() end) -- hides all your adjustable containers<br />
</syntaxhighlight><br />
<br />
=== Custom Save/Load Directories and Slots ===<br />
{{note}} available in Mudlet 4.10+<br />
==== Custom Directory ====<br />
If no option set your Adjustable.Container saves/loads its settings in your profile directory.<br />
<br />
It is possible to change the default save/load directory by using for example a different defaultDir as constraint when creating your Adjustable.Container.<br />
<br />
{{note}} This can be especially useful for authors of packages which want to ship their own save files.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = "/home/edru/MyAdjustableContainerSettings/"}) -- noteː the directory will be created if it doesn't exist<br />
</syntaxhighlight><br />
<br />
Example for save files in a package (assuming the packagename is "AdjustableContainerTest" and the settings are saved in "myPersonalAdjSettings"<br />
<syntaxhighlight lang="lua"><br />
local packageName = "AdjustableContainerTest"<br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = string.format("%s/%s/myPersonalAdjSettings/", getMudletHomeDir(), packageName)})<br />
</syntaxhighlight><br />
<br />
==== Custom Slot ====<br />
Another useful addition is to choose a save slot depending on the situation or to reset to a default save state.<br />
<br />
To save to a different slot just add it as parameter when saving.<br />
<br />
For exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːsave("combatSlot")<br />
</syntaxhighlight><br />
<br />
To then load from that slot just useː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːload("combatSlot")<br />
</syntaxhighlight><br />
<br />
{{note}} This also allows package/module authors to choose a "default" save setting to reset to.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
Adjustable.ContainerːsaveAll("default") -- saves the default settings<br />
<br />
-- to reset to default settings then just use<br />
Adjustable.ContainerːloadAll("default") -- loads the default settings<br />
</syntaxhighlight><br />
<br />
This can also be used to change the whole GUI on the fly.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
-- in combat situation use combat settings<br />
Adjustable.ContainerːloadAll("combat") -- loads special combat settings<br />
-- combat is over <br />
Adjustable.ContainerːloadAll("default") --reverts to the default settings<br />
</syntaxhighlight><br />
<br />
==== Delete Save File ====<br />
To delete the save file just useː<br />
<syntaxhighlight lang="lua"><br />
testCont2:deleteSaveFile()<br />
</syntaxhighlight><br />
<br />
===Right-click menu===<br />
Your Adjustable Container has also integrated a right-click menu with the main key functions for easier usability:<br />
<br />
[[File:AdjustableContainerRightClickMenu.png]]<br />
<br />
The right-click menu automatically shows you the possible positions to attach to (top, right, bottom, or left) when it's near one of them. For example, to attach a window to the right of the screen, drag it over to the right - and then the 'Attach to - right' will appear as an option:<br />
<br />
[[File:Adjustable Container - attach to right.png]]<br />
<br />
It also shows the lockstyle selection, which allows you to choose what happens when you press <code>Lock</code>, with 4 lockstyles available by default:<br />
<br />
* standard: this is the default lockstyle, with a small margin on top to keep the right click menu usable.<br />
* light: only hides the min/restore and close labels. Borders and margin are not affected.<br />
* full: the container gets fully locked without any margin left for the right click menu.<br />
* border: keeps the borders of the container visible while locked.<br />
<br />
From Mudlet 4.10+ on it is also possible to change your right-click menu style to dark mode by<br />
<br />
<syntaxhighlight lang="lua"><br />
myAdjustableContainer:changeMenuStyle("dark") -- possible menu styles are "dark" or "light"<br />
</syntaxhighlight><br />
<br />
=== Create a Custom Menu with Custom Items ===<br />
To create a new menu element in your right click menu called "Custom" and add an item to it use:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newCustomItem(name, func)<br />
-- for example<br />
testcontainer:newCustomItem("Hello world", function(self) echo("Hello world\n") self:flash() end)<br />
-- this will write "Hello world" to the main console and flashes your container.<br />
</syntaxhighlight><br />
<br />
=== Add new LockStyles ===<br />
For more advanced users it's possible to add a new Lockstyles by:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newLockStyle(name, func)<br />
-- for example<br />
testcontainer:newLockStyle("NewLockStyle", function(self) self.Inside:move(40, 40) self.Inside:resize(-40,-40) self:setTitle("") end)<br />
</syntaxhighlight><br />
<br />
=== Change Adjustable Container Style ===<br />
Additionally to the standard container constraints Adjustable Containers allow you to change at creation: the internal Label style, the menu style, min/close buttons, the menu text, title text... <br />
<br />
( see [[Manual:Geyser#valid constraints|valid constraints]])<br />
An example of a Adjustable Container with different style.<br />
<syntaxhighlight lang="lua"><br />
testCont =<br />
testCont or<br />
Adjustable.Container:new(<br />
{<br />
name = "TestNewStyleContainer",<br />
adjLabelstyle = "background-color:rgba(220,220,220,100%); border: 5px groove grey;",<br />
buttonstyle=[[<br />
QLabel{ border-radius: 7px; background-color: rgba(140,140,140,100%);}<br />
QLabel::hover{ background-color: rgba(160,160,160,50%);}<br />
]],<br />
buttonFontSize = 10,<br />
buttonsize = 20,<br />
titleText = "My new Style",<br />
titleTxtColor = "black",<br />
padding = 15,<br />
}<br />
)<br />
</syntaxhighlight><br />
This code creates a container which looks like this:<br />
<br />
[[File:NewStyleAdjustableContainer.png|Adjustable Container with different style]]<br />
<br />
<br />
=== Attach your Adjustable Container to a Border ===<br />
The simplest way to attach your container to a border is to move your container near the border you want it to attach and use the <br />
right click menu <code> Attach to:</code><br />
<br />
There is also the function <code> TestCont:attachToBorder("right") -- attach TestCont to the right border </code><br />
<br />
To change the margin between container and border use the constraint <code> attachedMargin </code > or the function <code> TestContːsetBorderMargin(10) -- 10 is the margin in px </code><br />
<br />
{{note}} The border is set in percentages and adjusts with screen-size<br />
<br />
=== Create a moveable border frame ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Adjustable Container can be connected to a border and therefore act like a frame.<br />
<br />
This only works if your container is attached to a specific border and the border to connect to has also at least one container attached to it.<br />
Use the function <code>connectToBorder</code><br />
<br />
<syntaxhighlight lang="lua"><br />
TestCont:connectToBorder("left") -- possible borders are "top", "bottom", "right", "left"<br />
</syntaxhighlight><br />
<br />
Minimizing automatically disconnects from a border. Another way is to use the function <code>disconnect</code>.<br />
<br />
{{note}}Connected container are still resizable even if locked.<br />
<br />
If you like to do everything with your right click menu there is the function<br />
<br />
<syntaxhighlight lang="lua"><br />
TestContːaddConnectMenu()<br />
</syntaxhighlight><br />
If you want to add the connect menu items to all Adjustable Containers just<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:addConnectMenu() end)<br />
</syntaxhighlight><br />
<br />
There is also a brief video of how to [https://www.youtube.com/watch?v=Ex-q5zAEfpc connect your Adjustable Container] available.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
GUI = GUI or {}<br />
<br />
GUI.top = Adjustable.Container:new({name = "top", y="0%", height = "10%", autoLoad = false})<br />
GUI.bottom = Adjustable.Container:new({name = "bottom", height = "20%", y = "-20%", autoLoad = false})<br />
GUI.right = Adjustable.Container:new({name = "right", y = "0%", height = "100%", x = "-20%", width = "20%", autoLoad = false})<br />
GUI.left = Adjustable.Container:new({name = "left", x = "0%", y = "0%", height = "100%", width = "20%", autoLoad = false})<br />
<br />
<br />
GUI.top:attachToBorder("top")<br />
GUI.bottom:attachToBorder("bottom")<br />
GUI.left:attachToBorder("left")<br />
GUI.right:attachToBorder("right")<br />
<br />
GUI.top:connectToBorder("left")<br />
GUI.top:connectToBorder("right")<br />
GUI.bottom:connectToBorder("left")<br />
GUI.bottom:connectToBorder("right")<br />
</syntaxhighlight><br />
Here's what the frame will look like:<br />
<br />
[[File:Adjustable_frame.gif]]<br />
<br />
=== Add a scrollable box ===<br />
{{note}} available in Mudlet 4.15+<br />
<br />
To add a scrollable box to an adjustable label, try the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
ScrollContainer = ScrollContainer or Adjustable.Container:new({name = "ScrollContainer"})<br />
ContainerBox = ContainerBox or Geyser.ScrollBox:new({name = "ContainerBox", x = 0, y = 0, height = "100%", width = "100%"}, ScrollContainer)</syntaxhighlight><br />
<br />
[[File:Scrollbox-in-container.png|thumb|center]]<br />
<br />
==Change Container==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
With this command it is possible to change an elements or even a containers location to that from another container.<br />
For example:<br />
<syntaxhighlight lang="lua"><br />
mycontainerone:changeContainer(mycontainertwo)<br />
--puts container one into container two which means container two will be the parent of container one<br />
</syntaxhighlight><br />
It is also possible to change to a container which is not located on the main window:<br />
<syntaxhighlight lang="lua"><br />
myEmco:changeContainer(emco_userwindow)<br />
--puts my tabbed chat Emco into my userwindow<br />
--to put it back to the main window change to a container located on the main window<br />
myEmco:changeContainer(mymainwindow_container)<br />
--or if it the element wasn't in a container use the main Geyser Root container called Geyser<br />
myEmco:changeContainer(Geyser)<br />
</syntaxhighlight><br />
<br />
==Geyser.Mapper==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
It‘s possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation use: (this will create a map window docked at the left corner)<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are "left", "right", "top", "bottom", and "floating".<br><br />
To change the dockPosition after creation use:<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget:setDockPosition("floating")<br />
-- this will change myMapWidget dockPosition to floating <br />
</syntaxhighlight><br />
<br />
= Tutorial =<br />
Note: This tutorial assumes you know how scripts in Mudlet work. If not then you should look at the manual first. Also it only shows how Geyser basically works and explains Geysers special windows. It wont go into detail about the windows that where already in Mudlet.<br />
<br />
=== Hello World ===<br />
Let's start with something simple. A Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_1.png]]<br />
<br />
This code creates a blank Label with a size of 200x50 at a position of 50 points horizontal and vertical from its parent window - which is the main window since we didn't specify any.<br />
<br />
You can manipulate the Label through the normal functions but Geyser.Label:new() returns an object which can be used to manipulate the label directly. So you should store it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local HelloWorld = Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
Then you can, for example print a text on it:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_2.png]]<br />
<br />
You can put a format parameter so that the text is, for example, centered.<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_3.png]]<br />
<br />
The second parameter is the color. We set it to nil which means the labels foreground color will be used.<br />
<br />
The color parameter either accepts a string ("red"), a hex value("#FF0000" or "0xFF0000" or "|cFF0000"), or a decimal value "&lt;255,0,0&gt;"<br />
<br />
Example:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", "red", "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
{{note}} This will automatically set the foreground color, so any echo, without the color parameter set, after that will use the same color.<br />
<br />
You can also set the foreground color with the setFgColor method:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setFgColor("red")<br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
=== Containers ===<br />
<br />
Containers are windows that can contain other windows. Actually, since all other Geyser windows subclass container, every window can do that. But containers do not have any visible content by themselves. <br />
<br />
Let's show that by an example:<br />
<syntaxhighlight lang="lua"><br />
local container = Geyser.Container:new({<br />
name="container",<br />
x=50, y=50,<br />
width=250, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
This will create a container, but if you look at the screen you will see nothing at the positon.<br />
There is a way to make containers visible though:<br />
<syntaxhighlight lang="lua"><br />
container:flash()<br />
</syntaxhighlight><br />
<br />
This will flash the container for a short period of time.<br />
<br />
[[Image:Geyser_Container_1.png]]<br />
<br />
flash() accepts a number as paremeter which defines the time, in seconds, the flash is shown.<br />
<br />
Now, that the container is created, you can add other windows to it. There are 2 ways:<br />
<br />
Directly when creating the window:<br />
<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
},<br />
container)<br />
container_label:echo("This is a label in a container", nil, "c")<br />
</syntaxhighlight><br />
<br />
Later, after the window was created<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
})<br />
container_label:echo("This is a label in a container", nil, "c")<br />
container:add(container_label)<br />
</syntaxhighlight><br />
<br />
Both will lead to the same outcome.<br />
<br />
[[Image:Geyser_Container_2.png]]<br />
<br />
Note that we gave a width and height of "100%" to the constructor of the label. This means that the label will take 100% of the containers width and height. If values are given in percent they will even resize with its parent:<br />
<br />
<syntaxhighlight lang="lua"><br />
container:resize(325, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_3.png]]<br />
<br />
The first parameter is the width, the second the height. If the value is nil the current value is used.<br />
<br />
As said in the "Hello World" tutorial the position is relative to its parent window. That's why we could set both x and y to 0 and it is at the position we wanted - the position of the container.<br />
<br />
When we now move the container the label moves with it:<br />
<syntaxhighlight lang="lua"><br />
container:move(400, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_4.png]]<br />
<br />
The first parameter is the x-, the second the y-position. If the value is nil the current value is used.<br />
<br />
=== VBox and HBox ===<br />
<br />
The VBox and HBox classes are special Containers.<br />
They will automatically align its containing windows vertically or horizontally, respectively, in the order they where added to them.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local HBox = Geyser.HBox:new({<br />
name="HBox",<br />
x=0, y=0,<br />
width=400, height=30,<br />
})<br />
<br />
</syntaxhighlight><br />
<br />
Like containers you won't see them by themselves.<br />
<br />
Adding children works like with containers<br />
<syntaxhighlight lang="lua"><br />
<br />
local label1 = Geyser.Label:new({<br />
name="Label1",<br />
},<br />
HBox)<br />
label1:echo("Label 1", "black", "c")<br />
label1:setColor(255, 0, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_1.png]]<br />
<br />
We didn't set any position or size, but the label gets the same size as the HBox.<br />
<br />
If we add another window:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label2 = Geyser.Label:new({<br />
name="Label2",<br />
},<br />
HBox)<br />
label2:echo("Label 2", "black", "c")<br />
label2:setColor(0, 255, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_2.png]]<br />
<br />
the size will be divided equally between them!<br />
<br />
What if you want a child that takes more or less space than the others?<br />
That's possible too:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label3 = Geyser.Label:new({<br />
name="Label3",<br />
h_stretch_factor=2.0,<br />
},<br />
HBox)<br />
label3:echo("Label 3", nil, "c")<br />
label3:setColor(0, 0, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_3.png]]<br />
<br />
As you can see, Label 3 takes the same space as Label 1 and 2 Together. <br />
That's because we supplied a horizontal stretch factor with "h_stretch_factor=2.0"<br />
<br />
This works also with a vertical stretch factor, just replace "h_stretch_factor" with "v_stretch_factor"<br />
<br />
Now you may have windows that should not be stretched at all.<br />
To accomplish this you have to set the horizontal and/or vertical policy:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local label4 = Geyser.Label:new({<br />
name="Label4",<br />
width="13%",<br />
h_policy=Geyser.Fixed,<br />
},<br />
HBox)<br />
label4:echo("Label 4", "black", "c")<br />
label4:setColor(0, 255, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_4.png]]<br />
<br />
Possible values for the policies are Geyser.Fixed and Geyser.Dynamic (which is the default). They can also be applied to VBox and HBox in exactly the same way.<br />
<br />
Note that, like in the example above, the label will retain relative values (like percent) if used.<br />
<br />
The VBox works like the HBox, only that the child windows are aligned vertically.<br />
<br />
= Walkthroughs =<br />
Here are a few walkthroughs that will show you how to combine Geyser elements to create some simple GUI widgets.<br />
<br />
===Create a Clickable Compass===<br />
[[File: compass.png]]<br />
The following will walk you through the process of creating your own clickable compass using the Geyser framework.<br />
====Setup the image files====<br />
The compass requires a handful of images to work properly. You can find them here: https://www.dropbox.com/sh/53l7xrn4ds35wnq/WpWOziVKmH <br><br />
Download each image and place it in your profile folder. You can find your profile folder with getMudletHomeDir()<br><br />
If you're using Mudlet 2.1+ you can enter '''lua getMudletHomeDir()''' from the command line to return the profile folder path on your computer.<br />
<br />
====Create a new script====<br />
Script Name: '''''compass.resize'''''<br><br />
Registered Event Handlers: '''''sysWindowResizeEvent'''''<p><br />
Every snippet of code will be placed within this script.<br />
====Store the screen size====<br />
We'll want to store the screen size in some local variables so they can be easily referenced to later on.<br />
<syntaxhighlight lang="lua">local mw, mh = getMainWindowSize()</syntaxhighlight><br />
<br />
====Create a global table or namespace====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''compass''''' and everything we make from here on out will be stored within the compass table. We'll also add a few values to it: dirs and ratio. '''''compass.dirs''''' will store each direction while '''''compass.ratio''''' will store the ratio of our screen size so you can 'square up' your compass.<br />
<syntaxhighlight lang="lua">compass = compass or {<br />
dirs = {"nw","n","ne","w","center","e","sw","s","se"},<br />
ratio = mw / mh<br />
}</syntaxhighlight><br />
<br />
====Create the parent label====<br />
[[File: grey.png|thumbnail]]<br />
The 'parent label' refers to the label on the bottom layer. The entire compass will be created within this label. It's container is '''main''' for it's parent is the main window.<br />
<syntaxhighlight lang="lua">compass.back = Geyser.Label:new({<br />
name = "compass.back",<br />
x = "25%",<br />
y = "25%",<br />
width = "10%",<br />
height = "10%",<br />
},main)</syntaxhighlight><br />
<br />
====Set the parent label stylesheet====<br />
[[File: blue.png|thumbnail]]<br />
This will create the blue sphere that makes up most of the compass. The background color is a radial gradient that goes from a deep blue to a brighter shade. The border radius rounds the edges. When the radius is exactly half of the label width it forms a circle. The arrows of the compass actually protrude from the sphere so we give it a margin to suck it in a bit for this effect.<br />
<syntaxhighlight lang="lua">compass.back:setStyleSheet([[<br />
background-color: QRadialGradient(cx:.3,cy:1,radius:1,stop:0 rgb(0,0,50),stop:.5 rgb(0,0,100),stop:1 rgb(0,0,255));<br />
border-radius: ]]..tostring(compass.back:get_width()/2-14)..[[px;<br />
margin: 10px;<br />
]])</syntaxhighlight><br />
<br />
====Create a 3x3 grid====<br />
The compass is split into 9 sections. One for each cardinal direction plus an extra space that sits in the center. This 3x3 grid is created by 3 VBoxes that sit within a single HBox (or vice versa but I flipped a coin and this is what it gave me).<br><br />
So first off, we create the HBox. It will be the same size as its parent, ''compass.back''.<br />
<syntaxhighlight lang="lua"> compass.box = Geyser.HBox:new({<br />
name = "compass.box",<br />
x = 0,<br />
y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},compass.back)</syntaxhighlight><br />
Next, we create our 3 VBoxes. You don't need to specify position or size because these are placed within ''compass.box'', an HBox.<br />
<syntaxhighlight lang="lua"> compass.row1 = Geyser.VBox:new({<br />
name = "compass.row1",<br />
},compass.box)<br />
compass.row2 = Geyser.VBox:new({<br />
name = "compass.row2",<br />
},compass.box)<br />
compass.row3 = Geyser.VBox:new({<br />
name = "compass.row3",<br />
},compass.box)</syntaxhighlight><br />
Finally, we add our 9 labels. Take note that they are split up into even groups of 3. Each group is placed into a different ''compass.row#''<br />
<syntaxhighlight lang="lua"> compass.nw = Geyser.Label:new({<br />
name = "compass.nw",<br />
},compass.row1)<br />
<br />
compass.w = Geyser.Label:new({<br />
name = "compass.w",<br />
},compass.row1)<br />
<br />
compass.sw = Geyser.Label:new({<br />
name = "compass.sw",<br />
},compass.row1)<br />
<br />
compass.n = Geyser.Label:new({<br />
name = "compass.n",<br />
},compass.row2)<br />
<br />
compass.center = Geyser.Label:new({<br />
name = "compass.center",<br />
},compass.row2)<br />
<br />
compass.s = Geyser.Label:new({<br />
name = "compass.s",<br />
},compass.row2)<br />
<br />
compass.ne = Geyser.Label:new({<br />
name = "compass.ne",<br />
},compass.row3)<br />
<br />
compass.e = Geyser.Label:new({<br />
name = "compass.e",<br />
},compass.row3)<br />
<br />
compass.se = Geyser.Label:new({<br />
name = "compass.se",<br />
},compass.row3)</syntaxhighlight><br />
====Create a callback function====<br />
We'll want our compass to head in the direction of the arrow we're clicking. This is where we specify so. When the arrow is clicked, this function will be ran with the arrow direction as the argument.<br />
<syntaxhighlight lang="lua">function compass.click(name)<br />
send(name)<br />
end</syntaxhighlight><br />
====Create the hover functions====<br />
We want our arrows to turn yellow when we hover over them. We do so by simply resetting the label's stylesheet and changing the border image. Don't forget to include the margin as we still want that.<br />
<syntaxhighlight lang="lua">function compass.onEnter(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[hover.png");<br />
margin: 5px;<br />
]])<br />
end<br />
<br />
function compass.onLeave(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[.png");<br />
margin: 5px;<br />
]])<br />
end</syntaxhighlight><br />
====Set the stylesheets in the grid====<br />
[[File: Sample.png|thumb]]<br />
Each of the 9 labels need an image of an arrow. Rather than setting each individually, we'll iterate over the ''compass.dirs'' table we made awhile back and add the respective image to each. The names of images are a reflection of the ''compass.dirs'' table. This keeps it consistent and easy to refer to. During the iteration, the callback, setLabelOnEnter and setLabelOnLeave are also set for each label.<br />
<syntaxhighlight lang="lua">for k,v in pairs(compass.dirs) do<br />
compass[v]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..v..[[.png");<br />
margin: 5px;<br />
]])<br />
compass[v]:setClickCallback("compass.click",v)<br />
setLabelOnEnter("compass."..v,"compass.onEnter",v)<br />
setLabelOnLeave("compass."..v,"compass.onLeave",v)<br />
end</syntaxhighlight><br />
<br />
====Resize the compass into a square====<br />
[[File: final.png|thumb]]<br />
Most screen size ratios aren't a perfect 1:1. This will cause a 10% x 10% label to be far from square. By setting our height (the smaller of the two numbers) to our width, we can resize our compass to a near perfect square. This function is also the name of our script because we want it to run each time sysWindowResizeEvent is raised.<br />
<syntaxhighlight lang="lua">function compass.resize()<br />
compass.back:resize(compass.back.width, compass.back:get_width())<br />
end<br />
<br />
compass.resize()</syntaxhighlight><br />
<br />
===Create a Tabbed Window===<br />
[[File: tabwindow.png]]<br />
The following will walk you through the process of creating your own tabbed window using the Geyser framework.<br />
<br />
====Create a new script====<br />
Script Name: '''''Tabbed Window'''''<br><br />
Every snippet of code will be placed within this script.<br />
====Create a global table====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''menu''''' and everything we make from here on out will be stored within the menu table. We'll also add a few values to it: tabs, color1, color2, width, height and current. <br><br />
''''tabs'''' will be a table that stores all our tab names. If we want our tabs to have different names, we alter this table.<br><br />
''''color1'''' and ''''color2'''' will store the colors of our tabbed window. If we want to change the color of our tabbed window, we alter these values.<br><br />
''''width'''' and ''''height'''' will store the size of our tabbed window. If we want to change the size of the tabbed window, we alter these values.<br><br />
''''current'''' keeps track of which tab is selected. We will set this to the first tab in the table by default. We do this outside the initial table creation so we can easily access menu.tabs<br><br />
<syntaxhighlight lang="lua">menu = menu or {<br />
tabs = {"Tab1","Tab2","Tab3","Tab4"},<br />
color1 = "rgb(0,0,70)",<br />
color2 = "rgb(0,0,50)",<br />
width = "20%",<br />
height = "40%",<br />
}<br />
menu.current = menu.current or menu.tabs[1]</syntaxhighlight><br />
<br />
====Create the main container====<br />
Our tabbed window will need a container. This will be the bottom layer. Containers are invisible so no need to set a stylesheet.<br />
<syntaxhighlight lang="lua">menu.container = Geyser.Container:new({<br />
name = "menu.back",<br />
x = "50%", y = "25%",<br />
width = menu.width,<br />
height = menu.height,<br />
},main)</syntaxhighlight><br />
====Create an HBox====<br />
All of our tabs will be evenly spaced. So we'll create an HBox to sit at the top of our container.<br />
<syntaxhighlight lang="lua">menu.header = Geyser.HBox:new({<br />
name = "menu.header",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "10%",<br />
},menu.container)</syntaxhighlight><br />
====Create a label====<br />
This label will serve as a container for each window. It sits right underneath the HBox we just created for the tabs.<br />
<syntaxhighlight lang="lua">menu.footer = Geyser.Label:new({<br />
name = "menu.footer",<br />
x = 0, y = "10%",<br />
width = "100%",<br />
height = "90%",<br />
},menu.container)</syntaxhighlight><br />
We don't want this to be a big grey box at startup, so we'll set the stylesheet to appear like the rest of the windows.<br />
<syntaxhighlight lang="lua"><br />
menu.footer:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])</syntaxhighlight><br />
Each window actually has two labels. One for the light blue background, and another for the dark blue center. This will create that dark blue center.<br />
<syntaxhighlight lang="lua">menu.center = Geyser.Label:new({<br />
name = "menu.center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
menu.center:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])</syntaxhighlight><br />
====Add your tabs and their windows====<br />
Now we'll want to add our tabs and windows. We do this in a single for loop of the ''''menu.tabs'''' table since it holds all our tab names.<br />
<syntaxhighlight lang="lua">for k,v in pairs(menu.tabs) do<br />
</syntaxhighlight><br />
This will create the tabs. Each tab will be named: menu.<tabname>tab<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"] = Geyser.Label:new({<br />
name = "menu."..v.."tab",<br />
},menu.header)<br />
</syntaxhighlight><br />
Here is where we set the tab stylesheet. Each tab has a rounded top, so we set the border-radius of the top-left and top-right to 10px. Each tab has a small space for separation so we give the right and left sides a tiny margin of 1px.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-top-left-radius: 10px;<br />
border-top-right-radius: 10px;<br />
margin-right: 1px;<br />
margin-left: 1px;<br />
]])<br />
</syntaxhighlight><br />
This will display the name of each tab on the tab.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:echo("<center>"..v)<br />
</syntaxhighlight><br />
We need our tabs to do stuff when clicked, so we'll assign it a callback function, '''''menu.click''''', which we'll create later on. Our tab name is the argument.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setClickCallback("menu.click",v)<br />
</syntaxhighlight><br />
Now we create the windows that appear when each tab is clicked. Each window has two labels, one atop the other. The first, which we'll create here, has rounded edges on its bottom.<br />
<syntaxhighlight lang="lua"><br />
menu[v] = Geyser.Label:new({<br />
name = "menu."..v,<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
<br />
menu[v]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
The second label serves as the window's center and has rounded edges on all sides. And a margin of 5px from it's parent, the label we just created. When adding stuff to your windows, this is the label you'll want to use. '''''menu.<tabname>center'''''<br />
<syntaxhighlight lang="lua"><br />
menu[v.."center"] = Geyser.Label:new({<br />
name = "menu."..v.."center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu[v])<br />
</syntaxhighlight><syntaxhighlight lang="lua"><br />
menu[v.."center"]:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])<br />
</syntaxhighlight><br />
Finally, we hide all the windows and end the for loop.<br />
<syntaxhighlight lang="lua"><br />
menu[v]:hide()<br />
end</syntaxhighlight><br />
====Create a callback function====<br />
The last step is to create our callback function for when a tab is clicked. This will hide that tab that is stored in '''''menu.current''''', set menu.current to the clicked tab, and then show the menu.current tab.<br />
<syntaxhighlight lang="lua">function menu.click(tab)<br />
menu[menu.current]:hide()<br />
menu.current = tab<br />
menu[menu.current]:show()<br />
end</syntaxhighlight><br />
====Adding content to your windows====<br />
Add content to '''menu.<tab name>center'''<br />
So if we wanted to display our gold in a window we could:<syntaxhighlight lang="lua">menu.Tab1center:echo(myGold)</syntaxhighlight><br />
If we wanted to add a map to a window we could:<br />
<syntaxhighlight lang="lua">myMap = Geyser.Mapper:new({<br />
name = "myMap",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.Tab2center)</syntaxhighlight><br />
<br />
===Create a Window with a resize label===<br />
<br />
Previous tutorial is now done much simpler [[Manual:Geyser#Adjustable.Container|Adjustable containers]], have a look at those instead.<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Miscellaneous_Functions&diff=20313Manual:Miscellaneous Functions2023-02-16T23:37:07Z<p>Kebap: /* getModuleInfo */ Typo</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Mudlet API documentation for miscellaneous functions.}}<br />
= Miscellaneous Functions =<br />
<br />
==addFileWatch==<br />
;addFileWatch(path)<br />
:Adds file watch on directory or file. Every change in that file (or directory) will raise [[Manual:Event_Engine#sysPathChanged|sysPathChanged]] event.<br />
<br />
:See also: [[#removeFileWatch|removeFileWatch()]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", "herbsChangedHandler")<br />
</syntaxhighlight><br />
<br />
==addSupportedTelnetOption==<br />
;addSupportedTelnetOption(option)<br />
:Adds a telnet option, which when queried by a game server, Mudlet will return DO (253) on. Use this to register the telnet option that you will be adding support for with Mudlet - see [[Manual:Supported_Protocols#Adding_support_for_a_telnet_protocol|additional protocols]] section for more.<br />
<br />
;Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
<event handlers that add support for MSDP... see http://www.mudbytes.net/forum/comment/63920/#c63920 for an example><br />
<br />
-- register with Mudlet that it should not decline the request of MSDP support<br />
local TN_MSDP = 69<br />
addSupportedTelnetOption(TN_MSDP)<br />
</syntaxhighlight><br />
<br />
==alert==<br />
;alert([seconds])<br />
:alerts the user to something happening - makes Mudlet flash in the Windows window bar, bounce in the macOS dock, or flash on Linux.<br />
<br />
{{MudletVersion|3.2}}<br />
<br />
;Parameters<br />
* ''seconds:''<br />
:(optional) number of seconds to have the alert for. If not provided, Mudlet will flash until the user opens Mudlet again.<br />
<br />
;Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- flash indefinitely until Mudlet is open<br />
alert()<br />
<br />
-- flash for just 3 seconds<br />
alert(3)<br />
</syntaxhighlight><br />
<br />
==cfeedTriggers==<br />
;cfeedTriggers(text)<br />
:Like feedTriggers, but you can add color information using color names, similar to cecho.<br />
<br />
;Parameters<br />
* ''text'': The string to feed to the trigger engine. Include colors by name as black,red,green,yellow,blue,magenta,cyan,white and light_* versions of same. You can also use a number to get the ansi color corresponding to that number.<br />
:See also: [[#feedTriggers|feedTriggers]]<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
cfeedTriggers("<green:red>green on red<r> reset <124:100> foreground of ANSI124 and background of ANSI100<r>\n")<br />
</syntaxhighlight><br />
<br />
==closeMudlet==<br />
;closeMudlet()<br />
<br />
:Closes Mudlet and all profiles immediately.<br />
:See also: [[Manual:Lua_Functions#saveProfile|saveProfile()]]<br />
<br />
{{note}} Use with care. This potentially lead to data loss, if "save on close" is not activated and the user didn't save the profile manually as this will NOT ask for confirmation nor will the profile be saved. Also it does not consider if there are ''other'' profiles open if multi-playing: they '''all''' will be closed!<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
closeMudlet()<br />
</syntaxhighlight><br />
<br />
==deleteAllNamedEventHandlers==<br />
; deleteAllNamedEventHandlers(userName)<br />
<br />
:Deletes all named event handlers for userName and prevents them from firing any more. Information is deleted and cannot be retrieved.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteAllNamedEventHandlers("Demonnic") -- emergency stop or debugging situation, most likely.<br />
</syntaxhighlight><br />
<br />
==deleteNamedEventHandler==<br />
; success = deleteNamedEventHandler(userName, handlerName)<br />
<br />
:Deletes a named event handler with name handlerName and prevents it from firing any more. Information is deleted and cannot be retrieved.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to stop. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local deleted = deleteNamedEventHandler("Demonnic", "Vitals")<br />
if deleted then<br />
cecho("Vitals deleted forever!!")<br />
else<br />
cecho("Vitals doesn't exist and so could not be deleted.")<br />
end<br />
</syntaxhighlight><br />
<br />
==denyCurrentSend==<br />
;denyCurrentSend()<br />
<br />
:Cancels a [[Manual:Lua_Functions#send|send()]] or user-entered command, but only if used within a [[Manual:Event_Engine#sysDataSendRequest|sysDataSendRequest]] event.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- cancels all "eat hambuger" commands<br />
function cancelEatHamburger(event, command)<br />
if command == "eat hamburger" then<br />
denyCurrentSend()<br />
cecho("<red>Denied! Didn't let the command through.\n")<br />
end<br />
end<br />
<br />
registerAnonymousEventHandler("sysDataSendRequest", "cancelEatHamburger")<br />
</syntaxhighlight><br />
<br />
==dfeedTriggers==<br />
;dfeedTriggers(str)<br />
:Like feedTriggers, but you can add color information using <r,g,b>, similar to decho.<br />
<br />
;Parameters<br />
* ''str'': The string to feed to the trigger engine. Include color information inside tags like decho.<br />
;See also: [[Manual:Lua_Functions#cfeedTriggers|cfeedTriggers]], [[Manual:Lua_Functions#decho|decho]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
dfeedTriggers("<0,128,0:128,0,0>green on red<r> reset\n")<br />
</syntaxhighlight><br />
<br />
==disableModuleSync==<br />
;disableModuleSync(name)<br />
: Stops syncing the given module.<br />
<br />
;Parameter<br />
* ''name'': name of the module.<br />
<br />
:See also: [[Manual:Lua_Functions#enableModuleSync|enableModuleSync()]], [[Manual:Lua_Functions#getModuleSync|getModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==enableModuleSync==<br />
;enableModuleSync(name)<br />
: Enables the sync for the given module name - any changes done to it will be saved to disk and if the module is installed in any other profile(s), it'll be updated in them as well on profile save.<br />
<br />
;Parameter<br />
* ''name'': name of the module to enable sync on.<br />
<br />
:See also: [[Manual:Lua_Functions#disableModuleSync|disableModuleSync()]], [[Manual:Lua_Functions#getModuleSync|getModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==expandAlias==<br />
;expandAlias(command, [echoBackToBuffer])<br />
:Runs the command as if it was from the command line - so aliases are checked and if none match, it's sent to the game unchanged. <br />
<br />
;Parameters<br />
* ''command''<br />
: Text of the command you want to send to the game. Will be checked for aliases.<br />
* ''echoBackToBuffer''<br />
: (optional) If ''false'', the command will not be echoed back in your buffer. Defaults to ''true'' if omitted.<br />
<br />
{{note}} Using expandAlias is not recommended anymore as it is not very robust and may lead to problems down the road. The recommendation is to use lua functions instead. See [[Manual:Functions_vs_expandAlias]] for details and examples.<br />
<br />
{{note}} If you want to be using the ''matches'' table after calling ''expandAlias'', you should save it first, as, e.g. ''local oldmatches = matches'' before calling ''expandAlias'', since ''expandAlias'' will overwrite it after using it again.<br />
<br />
{{note}} Since '''Mudlet 3.17.1''' the optional second argument to echo the command on screen will be ineffective whilst the game server has negotiated the telnet ECHO option to provide the echoing of text we ''send'' to him.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
expandAlias("t rat")<br />
<br />
-- don't echo the command<br />
expandAlias("t rat", false)<br />
</syntaxhighlight><br />
<br />
==feedTriggers==<br />
;feedTriggers(text[, dataIsUtf8Encoded = true])<br />
:This function will have Mudlet parse the given text as if it came from the game - one great application is trigger testing. The built-in '''`echo''' alias provides this functionality as well.<br />
<br />
;Parameters<br />
* ''text:''<br />
:string which is sent to the trigger processing system almost as if it came from the game server. This string must be byte encoded in a manner to match the currently selected ''Server Encoding''. <br />
* ''dataIsUtf8Encoded'' (available in Mudlet 4.2+):<br />
:Set this to false, if you need pre-Mudlet 4.0 behavior. Most players won't need this.<br />
:(Before Mudlet 4.0 the text had to be encoded directly in whatever encoding the setting in the preferences was set to. <br />
:(Encoding could involve using the Lua string character escaping mechanism of \ and a base 10 number for character codes from \1 up to \255 at maximum)<br />
:Since Mudlet 4.0 it is assumed that the text is UTF-8 encoded. It will then be automatically converted to the currently selected game server encoding.<br />
:Preventing the automatic conversion can be useful to Mudlet developers testing things, or possibly to those who are creating handlers for Telnet protocols within the Lua subsystem, who need to avoid the transcoding of individual protocol bytes, when they might otherwise be seen as extended ASCII characters.)<br />
<br />
;Returns (available in Mudlet 4.2+):<br />
* ''true'' on success, ''nil'' and an error message if the text contains characters that cannot be conveyed by the current Game Server encoding.<br />
<br />
{{note}} It is important to ensure that in Mudlet 4.0.0 and beyond the text data only contains characters that can be encoded in the current Game Server encoding, from 4.2.0 the content is checked that it can successfully be converted from the UTF-8 that the Mudlet Lua subsystem uses internally into that particular encoding and if it cannot the function call will fail and not pass any of the data, this will be significant if the text component contains any characters that are not plain ASCII.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- try using this on the command line<br />
`echo This is a sample line from the game<br />
<br />
-- You can use \n to represent a new line - you also want to use it before and after the text you’re testing, like so:<br />
feedTriggers("\nYou sit yourself down.\n")<br />
<br />
-- The function also accept ANSI color codes that are used in games. A sample table can be found http://codeworld.wikidot.com/ansicolorcodes<br />
feedTriggers("\nThis is \27[1;32mgreen\27[0;37m, \27[1;31mred\27[0;37m, \27[46mcyan background\27[0;37m," ..<br />
"\27[32;47mwhite background and green foreground\27[0;37m.\n")<br />
</syntaxhighlight><br />
<br />
==getCharacterName==<br />
;getCharacterName()<br />
<br />
:Returns the name entered into the "Character name" field on the Connection Preferences form. Can be used to find out the name that might need to be handled specially in scripts or anything that needs to be personalized to the player. If there is nothing set in that entry will return an empty string.<br />
<br />
:See also: [[#getProfileName|getProfileName()]]<br />
<br />
{{MudletVersion|4.16}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- cast glamor on yourself<br />
<br />
send("cast 'glamor' " .. getCharacterName())<br />
</syntaxhighlight><br />
<br />
==getModulePath==<br />
;path = getModulePath(module name)<br />
<br />
:Returns the location of a module on the disk. If the given name does not correspond to an installed module, it'll return <code>nil</code><br />
:See also: [[Manual:Lua_Functions#installModule|installModule()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModulePath("mudlet-mapper")<br />
</syntaxhighlight><br />
<br />
==getModulePriority==<br />
;priority = getModulePriority(module name)<br />
<br />
:Returns the priority of a module as an integer. This determines the order modules will be loaded in - default is 0. Useful if you have a module that depends on another module being loaded first, for example.<br />
:Modules with priority <code>-1</code> will be loaded before scripts (Mudlet 4.11+).<br />
<br />
:See also: [[Manual:Lua_Functions#setModulePriority|setModulePriority()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModulePriority("mudlet-mapper")<br />
</syntaxhighlight><br />
<br />
==getModules==<br />
;getModules()<br />
<br />
:Returns installed modules as table.<br />
<br />
:See also: [[#getPackages|getPackages]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Check if the module myTabChat is installed and if it isn't install it and enable sync on it<br />
if not table.contains(getModules(),"myTabChat") then<br />
installModule(getMudletHomeDir().."/modules/myTabChat.xml")<br />
enableModuleSync("myTabChat")<br />
end<br />
<br />
</syntaxhighlight><br />
<br />
==getModuleInfo==<br />
;getModuleInfo(moduleName, [info])<br />
<br />
:Returns table with meta information for a package<br />
<br />
;Parameters<br />
* ''moduleName:''<br />
:Name of the package<br />
* ''info:''<br />
:(optional) specific info wanted to get, if not given all available meta-info is returned<br />
<br />
:See also: [[#getPackageInfo|getPackageInfo]], [[#setModuleInfo|setModuleInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModuleInfo("myModule","author")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==getModuleSync==<br />
;getModuleSync(name)<br />
: returns false if module sync is not active, true if it is active and nil if module is not found.<br />
<br />
;Parameter<br />
* ''name'': name of the module<br />
<br />
:See also: [[Manual:Lua_Functions#enableModuleSync|enableModuleSync()]], [[Manual:Lua_Functions#disableModuleSync|disableModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==getMudletHomeDir==<br />
;getMudletHomeDir()<br />
:Returns the current home directory of the current profile. This can be used to store data, save statistical information, or load resource files from packages.<br />
<br />
{{note}} intentionally uses forward slashes <code>/</code> as separators on Windows since [[Manual:UI_Functions#setLabelStyleSheet|stylesheets]] require them.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- save a table<br />
table.save(getMudletHomeDir().."/myinfo.dat", myinfo)<br />
<br />
-- or access package data. The forward slash works even on Windows fine<br />
local path = getMudletHomeDir().."/mypackagename"<br />
</syntaxhighlight><br />
<br />
==getMudletInfo==<br />
;getMudletInfo()<br />
:Prints debugging information about the Mudlet that you're running - this can come in handy for diagnostics.<br />
<br />
Don't use this command in your scripts to find out if certain features are supported in Mudlet - there are better functions available for this.<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getMudletInfo()<br />
</syntaxhighlight><br />
<br />
==getMudletVersion==<br />
;getMudletVersion(style)<br />
:Returns the current Mudlet version. Note that you shouldn't hardcode against a specific Mudlet version if you'd like to see if a function is present - instead, check for the existence of the function itself. Otherwise, checking for the version can come in handy if you'd like to test for a broken function or so on.<br />
<br />
See also: [[#mudletOlderThan|mudletOlderThan()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Parameters<br />
* ''style:''<br />
:(optional) allows you to choose what you'd like returned. By default, if you don't specify it, a key-value table with all the values will be returned: major version, minor version, revision number and the optional build name.<br />
<br />
;Values you can choose<br />
* ''"string"'':<br />
:Returns the full Mudlet version as text.<br />
* ''"table"'':<br />
:Returns the full Mudlet version as four values (multi-return)<br />
* ''"major"'':<br />
:Returns the major version number (the first one).<br />
* ''"minor"'':<br />
:Returns the minor version number (the second one).<br />
* ''"revision"'':<br />
:Returns the revision version number (the third one).<br />
* ''"build"'':<br />
:Returns the build of Mudlet (the ending suffix, if any).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- see the full Mudlet version as text:<br />
getMudletVersion("string")<br />
-- returns for example "3.0.0-alpha"<br />
<br />
-- check that the major Mudlet version is at least 3:<br />
if getMudletVersion("major") >= 3 then echo("You're running on Mudlet 3+!") end<br />
-- but mudletOlderThan() is much better for this:<br />
if mudletOlderThan(3) then echo("You're running on Mudlet 3+!") end <br />
<br />
-- if you'd like to see if a function is available however, test for it explicitly instead:<br />
if setAppStyleSheet then<br />
-- example credit to http://qt-project.org/doc/qt-4.8/stylesheet-examples.html#customizing-qscrollbar<br />
setAppStyleSheet[[<br />
QScrollBar:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
width: 15px;<br />
margin: 22px 0 22px 0;<br />
}<br />
QScrollBar::handle:vertical {<br />
background: white;<br />
min-height: 20px;<br />
}<br />
QScrollBar::add-line:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
height: 20px;<br />
subcontrol-position: bottom;<br />
subcontrol-origin: margin;<br />
}<br />
QScrollBar::sub-line:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
height: 20px;<br />
subcontrol-position: top;<br />
subcontrol-origin: margin;<br />
}<br />
QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {<br />
border: 2px solid grey;<br />
width: 3px;<br />
height: 3px;<br />
background: white;<br />
}<br />
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {<br />
background: none;<br />
}<br />
]]<br />
end<br />
</syntaxhighlight><br />
<br />
==getNewIDManager==<br />
; getNewIDManager()<br />
<br />
:Returns an IDManager object, for manager your own set of named events and timers isolated from the rest of the profile.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
{{note}} Full IDManager usage can be found at [[Manual:IDManager|IDManager]]<br />
<br />
;Returns<br />
* an IDManager for managing your own named events and timers<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
demonnic = demonnic or {}<br />
demonnic.IDManager = getNewIDManager()<br />
local idm = demonnic.IDManager<br />
-- assumes you have defined demonnic.vitalsUpdate and demonnic.balanceChecker as functions<br />
idm:registerEvent("DemonVitals", "gmcp.Char.Vitals", demonnic.vitalsUpdate)<br />
idm:registerTimer("Balance Check", 1, demonnic.balanceChecker)<br />
idm:stopEvent("DemonVitals")<br />
</syntaxhighlight><br />
<br />
==getNamedEventHandlers==<br />
; handlers = getNamedEventHandlers(userName)<br />
<br />
:Returns a list of all userName's named event handlers' names as a table.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Returns <br />
* a table of handler names. { "DemonVitals", "DemonInv" } for example. {} if none are registered<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local handlers = getNamedEventHandlers()<br />
display(handlers)<br />
-- {}<br />
registerNamedEventHandler("Test1", "testEvent", "testFunction")<br />
registerNamedEventHandler("Test2", "someOtherEvent", myHandlerFunction)<br />
handlers = getNamedEventHandlers()<br />
display(handlers)<br />
-- { "Test1", "Test2" }<br />
</syntaxhighlight><br />
<br />
==getOS==<br />
;getOS()<br />
<br />
:Returns the name of the Operating System (OS). Useful for applying particular scripts only under particular operating systems, such as applying a stylesheet only when the OS is Windows. <br />
:Returned text will be one of these: "windows", "mac", "linux", as well as "cygwin", "hurd", "freebsd", "kfreebsd", "openbsd", "netbsd", "bsd4", "unix" or "unknown" otherwise.<br />
:Additionally returns the version of the OS, and if using Linux, the distribution in use (as of Mudlet 4.12+).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getOS())<br />
<br />
if getOS() == "windows" then<br />
echo("\nWindows OS detected.\n")<br />
else<br />
echo("\nDetected Operating system is NOT windows.\n")<br />
end<br />
<br />
if mudlet.supports.osVersion then<br />
local os, osversion = getOS()<br />
print(f"Running {os} {osversion}")<br />
end<br />
</syntaxhighlight><br />
<br />
==getPackages==<br />
;getPackages()<br />
<br />
:Returns installed packages as table.<br />
<br />
:See also: [[#getModules|getModules]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Check if the generic_mapper package is installed and if so uninstall it<br />
if table.contains(getPackages(),"generic_mapper") then<br />
uninstallPackage("generic_mapper")<br />
end<br />
<br />
</syntaxhighlight><br />
<br />
==getPackageInfo==<br />
;getPackageInfo(packageName, [info])<br />
<br />
:Returns table with meta information for a package<br />
<br />
;Parameters<br />
* ''packageName:''<br />
:Name of the package<br />
* ''info:''<br />
:(optional) specific info wanted to get, if not given all available meta-info is returned<br />
<br />
:See also: [[#getModuleInfo|getModuleInfo]], [[#setPackageInfo|setPackageInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getPackageInfo("myPackage", "version")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==getProfileName==<br />
;getProfileName()<br />
<br />
:Returns the name of the profile. Useful when combined with [[Manual:Mudlet_Object_Functions#raiseGlobalEvent|raiseGlobalEvent()]] to know which profile a global event came from.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- if connected to the Achaea profile, will print Achaea to the main console<br />
echo(getProfileName())<br />
</syntaxhighlight><br />
<br />
==getCommandSeparator==<br />
;getCommandSeparator()<br />
<br />
:Returns the command separator in use by the profile.<br />
<br />
{{MudletVersion|3.18}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- if your command separator is ;;, the following would send("do thing 1;;do thing 2"). <br />
-- This way you can determine what it is set to and use that and share this script with <br />
-- someone who has changed their command separator.<br />
-- Note: This is not really the preferred way to send this, using sendAll("do thing 1", "do thing 2") is,<br />
-- but this illustates the use case.<br />
local s = getCommandSeparator()<br />
expandAlias("do thing 1" .. s .. "do thing 2")<br />
</syntaxhighlight><br />
<br />
==getServerEncoding==<br />
;getServerEncoding()<br />
:Returns the current server [https://www.w3.org/International/questions/qa-what-is-encoding data encoding] in use.<br />
<br />
:See also: [[#setServerEncoding|setServerEncoding()]], [[#getServerEncodingsList|getServerEncodingsList()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getServerEncoding()<br />
</syntaxhighlight><br />
<br />
==getServerEncodingsList==<br />
;getServerEncodingsList()<br />
:Returns an indexed list of the server [https://www.w3.org/International/questions/qa-what-is-encoding data encodings] that Mudlet knows. This is not the list of encodings the servers knows - there's unfortunately no agreed standard for checking that. See [[Manual:Unicode#Changing_encoding|encodings in Mudlet]] for the list of which encodings are available in which Mudlet version.<br />
<br />
:See also: [[#setServerEncoding|setServerEncoding()]], [[#getServerEncoding|getServerEncoding()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- check if UTF-8 is available:<br />
if table.contains(getServerEncodingsList(), "UTF-8") then<br />
print("UTF-8 is available!")<br />
end<br />
</syntaxhighlight><br />
<br />
==getWindowsCodepage==<br />
;getWindowsCodepage()<br />
:Returns the current [https://docs.microsoft.com/en-us/windows/desktop/Intl/code-page-identifiers codepage] of your Windows system.<br />
<br />
{{MudletVersion|3.22}}<br />
{{Note}} This function only works on Windows - It is only needed internally in Mudlet to enable Lua to work with non-ASCII usernames (e.g. Iksiński, Jäger) for the purposes of IO. Linux and macOS work fine with with these out of the box.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
print(getWindowsCodepage())<br />
</syntaxhighlight><br />
<br />
==hfeedTriggers==<br />
;hfeedTriggers(str)<br />
:Like feedTriggers, but you can add color information using #RRGGBB in hex, similar to hecho.<br />
<br />
;Parameters<br />
* ''str'': The string to feed to the trigger engine. Include color information in the same manner as hecho.<br />
:See also: [[Manual:Lua_Functions#dfeedTriggers|dfeedTriggers]]<br />
:See also: [[Manual:Lua_Functions#hecho|hecho]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
hfeedTriggers("#008000,800000green on red#r reset\n")<br />
</syntaxhighlight><br />
<br />
==installModule==<br />
;installModule(location)<br />
:Installs a Mudlet XML, zip, or mpackage as a module.<br />
<br />
;Parameters<br />
* ''location:''<br />
:Exact location of the file install.<br />
<br />
:See also: [[#uninstallModule | uninstallModule()]], [[Manual:Event_Engine#sysLuaInstallModule | Event: sysLuaInstallModule]], [[#setModulePriority | setModulePriority()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
installModule([[C:\Documents and Settings\bub\Desktop\myalias.xml]])<br />
</syntaxhighlight><br />
<br />
==installPackage==<br />
;installPackage(location or url)<br />
:Installs a Mudlet XML or package. Since Mudlet 4.11+ returns <code>true</code> if it worked, or <code>false</code>.<br />
<br />
;Parameters<br />
* ''location:''<br />
:Exact location of the xml or package to install.<br />
Since Mudlet 4.11+ it is possible to pass download link to a package (must start with <code>http</code> or <code>https</code> and end with <code>.xml</code>, <code>.zip</code>, <code>.mpackage</code> or <code>.trigger</code>)<br />
<br />
:See also: [[#uninstallPackage | uninstallPackage()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
installPackage([[C:\Documents and Settings\bub\Desktop\myalias.xml]])<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
installPackage([[https://github.com/Mudlet/Mudlet/blob/development/src/run-lua-code-v4.xml]])<br />
</syntaxhighlight><br />
<br />
==killAnonymousEventHandler==<br />
;killAnonymousEventHandler(handler id)<br />
:Disables and removes the given event handler.<br />
<br />
;Parameters<br />
* ''handler id''<br />
:ID of the event handler to remove as returned by the [[ #registerAnonymousEventHandler | registerAnonymousEventHandler ]] function.<br />
<br />
:See also: [[ #registerAnonymousEventHandler | registerAnonymousEventHandler ]]<br />
<br />
{{MudletVersion|3.5}}<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- registers an event handler that prints the first 5 GMCP events and then terminates itself<br />
<br />
local counter = 0<br />
local handlerId = registerAnonymousEventHandler("gmcp", function(_, origEvent)<br />
print(origEvent)<br />
counter = counter + 1<br />
if counter == 5 then<br />
killAnonymousEventHandler(handlerId)<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
==loadMusicFile==<br />
;loadMusicFile(settings table) or loadMusicFile(name, [url])<br />
:Loads music files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]] and [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]]. Although files could be loaded directly at playing time from [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], loadMusicFile() provides the advantage of loading files in advance. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if file to load is not part of the profile or on the local file system.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#playMusicFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Download from the Internet<br />
loadMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
<br />
-- OR download from the profile<br />
loadMusicFile({name = getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
<br />
-- OR download from the local file system<br />
loadMusicFile({name = "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of loadMusicFile(name[, url]) ----<br />
<br />
-- Download from the Internet<br />
loadMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
)<br />
<br />
-- OR download from the profile<br />
loadMusicFile(getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
<br />
-- OR download from the local file system<br />
loadMusicFile("C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
</syntaxhighlight><br />
<br />
==loadSoundFile==<br />
;loadSoundFile(settings table) or loadSoundFile(name, [url])<br />
:Loads sound files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]] and [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]]. Although files could be loaded directly at playing time from [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], loadSoundFile() provides the advantage of loading files in advance. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if file to load is not part of the profile or on the local file system.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Download from the Internet<br />
loadSoundFile({<br />
name = "cow.wav"<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
<br />
-- OR download from the profile<br />
loadSoundFile({name = getMudletHomeDir().. "/cow.wav"})<br />
<br />
-- OR download from the local file system<br />
loadSoundFile({name = "C:/Users/Tamarindo/Documents/cow.wav"})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of loadSoundFile(name[,url]) ----<br />
<br />
-- Download from the Internet<br />
loadSoundFile("cow.wav", "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/")<br />
<br />
-- OR download from the profile<br />
loadSoundFile(getMudletHomeDir().. "/cow.wav")<br />
<br />
-- OR download from the local file system<br />
loadSoundFile("C:/Users/Tamarindo/Documents/cow.wav")<br />
</syntaxhighlight><br />
<br />
==mudletOlderThan==<br />
;mudletOlderThan(major, [minor], [patch])<br />
:Returns true if Mudlet is older than the given version to check. This is useful if you'd like to use a feature that you can't check for easily, such as coroutines support. However, if you'd like to check if a certain function exists, do not use this and use <code>if mudletfunction then</code> - it'll be much more readable and reliable.<br />
<br />
See also: [[#getMudletVersion|getMudletVersion()]]<br />
<br />
;Parameters<br />
* ''major:''<br />
:Mudlet major version to check. Given a Mudlet version 3.0.1, 3 is the major version, second 0 is the minor version, and third 1 is the patch version.<br />
* ''minor:''<br />
:(optional) minor version to check.<br />
* ''patch:''<br />
:(optional) patch version to check.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- stop doing the script of Mudlet is older than 3.2<br />
if mudletOlderThan(3,2) then return end<br />
<br />
-- or older than 2.1.3<br />
if mudletOlderThan(2, 1, 3) then return end<br />
<br />
-- however, if you'd like to check that a certain function is available, like getMousePosition(), do this instead:<br />
if not getMousePosition then return end<br />
<br />
-- if you'd like to check that coroutines are supported, do this instead:<br />
if not mudlet.supportscoroutines then return end<br />
</syntaxhighlight><br />
<br />
==openWebPage==<br />
;openWebPage(URL)<br />
:Opens the browser to the given webpage.<br />
<br />
;Parameters<br />
* ''URL:''<br />
:Exact URL to open.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
openWebPage("http://google.com")<br />
</syntaxhighlight><br />
<br />
Note: This function can be used to open a local file or file folder as well by using "file:///" and the file path instead of "http://".<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
openWebPage("file:///"..getMudletHomeDir().."file.txt")<br />
</syntaxhighlight><br />
<br />
==playMusicFile==<br />
;playMusicFile(settings table)<br />
:Plays music files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|-<br />
| style="text-align:center;"| No<br />
| volume<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| fadein<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
| fadeout<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| start<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
|-<br />
| style="text-align:center;" |No<br />
| loops<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the media to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| continue <br />
| true or false<br />
| true<br />
| style="text-align:left;" |<br />
*Continues playing matching new music files when true.<br />
*Restarts matching new music files when false.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{Note}} on Windows and certain files are not playing? Try installing the 3rd party [https://codecguide.com/download_k-lite_codec_pack_standard.htm K-lite codec pack].<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Play a music file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
})<br />
<br />
-- OR copy once from the game's profile, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile({<br />
name = getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = 75<br />
})<br />
<br />
-- OR copy once from the local file system, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile({<br />
name = "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = 75<br />
})<br />
<br />
-- OR download once from the Internet, and play music stored in the profile's media directory<br />
---- [fadein] and increase the volume from 1 at the start position to default volume up until the position of 20 seconds<br />
---- [fadeout] and decrease the volume from default volume to one, 53 seconds from the end of the music<br />
---- [start] 10 seconds after position 0 (fadein scales its volume increase over a shorter duration, too)<br />
---- [key] reference of "rugby" for stopping this unique music later<br />
---- [tag] reference of "ambience" to stop and music later with the same tag<br />
---- [continue] playing this music if another request for the same music comes in (false restarts it) <br />
---- [url] to download once from the Internet if the music does not exist in the profile's media directory<br />
playMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = nil -- nil lines are optional, no need to use<br />
, fadein = 20000<br />
, fadeout = 53000<br />
, start = 10000<br />
, loops = nil -- nil lines are optional, no need to use<br />
, key = "rugby"<br />
, tag = "ambience"<br />
, continue = true<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of playMusicFile(name[,volume][,fadein][,fadeout][,loops][,key][,tag][,continue][,url]) ----<br />
<br />
-- Play a music file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
)<br />
<br />
-- OR copy once from the game's profile, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile(<br />
getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR copy once from the local file system, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile(<br />
"C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR download once from the Internet, and play music stored in the profile's media directory<br />
---- [fadein] and increase the volume from 1 at the start position to default volume up until the position of 20 seconds<br />
---- [fadeout] and decrease the volume from default volume to one, 53 seconds from the end of the music<br />
---- [start] 10 seconds after position 0 (fadein scales its volume increase over a shorter duration, too)<br />
---- [key] reference of "rugby" for stopping this unique music later<br />
---- [tag] reference of "ambience" to stop and music later with the same tag<br />
---- [continue] playing this music if another request for the same music comes in (false restarts it) <br />
---- [url] to download once from the Internet if the music does not exist in the profile's media directory<br />
playMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, nil -- volume<br />
, 20000 -- fadein<br />
, 53000 -- fadeout<br />
, 10000 -- start<br />
, nil -- loops<br />
, "rugby" -- key <br />
, "ambience" -- tag<br />
, true -- continue<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/" -- url<br />
)<br />
</syntaxhighlight><br />
<br />
==playSoundFile==<br />
;playSoundFile(settings table)<br />
:Plays sound files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|-<br />
| style="text-align:center;"| No<br />
| volume<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| fadein<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
| fadeout<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| start<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
|-<br />
| style="text-align:center;" |No<br />
| loops<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the media to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| priority<br />
| 1 to 100<br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a lower priority while this media plays.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{Note}} on Windows and certain files are not playing? Try installing the 3rd party [https://codecguide.com/download_k-lite_codec_pack_standard.htm K-lite codec pack].<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Play a sound file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playSoundFile({<br />
name = "cow.wav"<br />
})<br />
<br />
-- OR copy once from the game's profile, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile({<br />
name = getMudletHomeDir().. "/cow.wav"<br />
, volume = 75<br />
})<br />
<br />
-- OR copy once from the local file system, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile({<br />
name = "C:/Users/Tamarindo/Documents/cow.wav"<br />
, volume = 75<br />
})<br />
<br />
-- OR download once from the Internet, and play a sound stored in the profile's media directory<br />
---- [volume] of 75<br />
---- [loops] of 2 (-1 for indefinite repeats, 1+ for finite repeats)<br />
---- [key] reference of "cow" for stopping this unique sound later<br />
---- [tag] reference of "animals" to stop a group of sounds later with the same tag<br />
---- [priority] of 25 (1 to 100, 50 default, a sound with a higher priority would stop this one)<br />
---- [url] to download once from the Internet if the sound does not exist in the profile's media directory<br />
playSoundFile({<br />
name = "cow.wav"<br />
, volume = 75<br />
, fadein = nil -- nil lines are optional, no need to use<br />
, fadeout = nil -- nil lines are optional, no need to use<br />
, start = nil -- nil lines are optional, no need to use<br />
, loops = 2<br />
, key = "cow"<br />
, tag = "animals"<br />
, priority = 25<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of playSoundFile(name[,volume][,fadein][,fadeout][,loops][,key][,tag][,priority][,url]) ----<br />
<br />
-- Play a sound file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playSoundFile(<br />
"cow.wav" -- name<br />
)<br />
<br />
-- OR copy once from the game's profile, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile(<br />
getMudletHomeDir().. "/cow.wav" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR copy once from the local file system, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile(<br />
"C:/Users/Tamarindo/Documents/cow.wav" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR download once from the Internet, and play a sound stored in the profile's media directory<br />
---- [volume] of 75<br />
---- [loops] of 2 (-1 for indefinite repeats, 1+ for finite repeats)<br />
---- [key] reference of "cow" for stopping this unique sound later<br />
---- [tag] reference of "animals" to stop a group of sounds later with the same tag<br />
---- [priority] of 25 (1 to 100, 50 default, a sound with a higher priority would stop this one)<br />
---- [url] to download once from the Internet if the sound does not exist in the profile's media directory<br />
playSoundFile(<br />
"cow.wav" -- name<br />
, 75 -- volume<br />
, nil -- fadein<br />
, nil -- fadeout<br />
, nil -- start<br />
, 2 -- loops<br />
, "cow" -- key <br />
, "animals" -- tag<br />
, 25 -- priority<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/" -- url<br />
)<br />
</syntaxhighlight><br />
<br />
==purgeMediaCache==<br />
;purgeMediaCache()<br />
: Purge all media file stored in the media cache within a given Mudlet profile (media used with MCMP and MSP protocols). As game developers update the media files on their games, this enables the media folder inside the profile to be cleared so that the media files could be refreshed to the latest update(s).<br />
<br />
;Guidance:<br />
<br />
* Instruct a player to type ''lua purgeMediaCache()'' on the command line, or<br />
* Distribute a trigger, button or other scriptable feature for the given profile to call ''purgeMediaCache()''<br />
<br />
: See also: [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]], [[Manual:Scripting#MUD_Client_Media_Protocol|Scripting MCMP]]<br />
<br />
==receiveMSP==<br />
;receiveMSP(command)<br />
: Receives a well-formed Mud Sound Protocol (MSP) message to be processed by the Mudlet client. Reference the [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]] manual for more information on about what can be sent and example triggers.<br />
<br />
: See also: [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Play a cow.wav media file stored in the media folder of the current profile. The sound would play twice at a normal volume.<br />
receiveMSP("!!SOUND(cow.wav L=2 V=50)")<br />
<br />
--Stop any SOUND media files playing stored in the media folder of the current profile.<br />
receiveMSP("!!SOUND(Off)")<br />
<br />
--Play a city.mp3 media file stored in the media folder of the current profile. The music would play once at a low volume.<br />
--The music would continue playing if it was triggered earlier by another room, perhaps in the same area.<br />
receiveMSP([[!!MUSIC(city.mp3 L=1 V=25 C=1)]])<br />
<br />
--Stop any MUSIC media files playing stored in the media folder of the current profile.<br />
receiveMSP("!!MUSIC(Off)")<br />
</syntaxhighlight><br />
<br />
==registerAnonymousEventHandler==<br />
;registerAnonymousEventHandler(event name, functionReference, [one shot])<br />
:Registers a function to an event handler, not requiring you to set one up via script. [[Manual:Event_Engine#Mudlet-raised_events|See here]] for a list of Mudlet-raised events. The function may be refered to either by name as a string containing a global function name, or with the lua function object itself.<br />
<br />
:The optional <code>one shot</code> parameter allows you to automatically kill an event handler after it is done by giving a true value. If the event you waited for did not occur yet, return <code>true</code> from the function to keep it registered.<br />
<br />
:The function returns an ID that can be used in [[Manual:Lua_Functions#killAnonymousEventHandler|killAnonymousEventHandler()]] to unregister the handler again.<br />
<br />
:If you use an asterisk ''("*")'' as the event name, your code will capture all events. Useful for debugging, or integration with external programs.<br />
<br />
{{note}} The ability to refer lua functions directly, the <code>one shot</code> parameter and the returned ID are features of Mudlet 3.5 and above.<br />
<br />
{{note}} The ''"*"'' all-events capture was added in Mudlet 4.10.<br />
<br />
;See also<br />
:[[Manual:Lua_Functions#killAnonymousEventHandler|killAnonymousEventHandler()]], [[Manual:Lua_Functions#raiseEvent|raiseEvent()]], [[Manual:Event_Engine#Mudlet-raised_events|list of Mudlet-raised events]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size<br />
function keepStaticSize()<br />
setMainWindowSize(1280,720)<br />
end -- keepStaticSize<br />
<br />
if keepStaticSizeEventHandlerID then killAnonymousEventHandler(keepStaticSizeEventHandlerID) end -- clean up any already registered handlers for this function<br />
keepStatisSizeEventHandlerID = registerAnonymousEventHandler("sysWindowResizeEvent", "keepStaticSize") -- register the event handler and save the ID for later killing<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- simple inventory tracker for GMCP enabled games. This version does not leak any of the methods<br />
-- or tables into the global namespace. If you want to access it, you should export the inventory<br />
-- table via an own namespace.<br />
local inventory = {}<br />
<br />
local function inventoryAdd()<br />
if gmcp.Char.Items.Add.location == "inv" then<br />
inventory[#inventory + 1] = table.deepcopy(gmcp.Char.Items.Add.item)<br />
end<br />
end<br />
if inventoryAddHandlerID then killAnonymousEventHandler(inventoryAddHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryAddHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Add", inventoryAdd) -- register the event handler and save the ID for later killing<br />
<br />
local function inventoryList()<br />
if gmcp.Char.Items.List.location == "inv" then<br />
inventory = table.deepcopy(gmcp.Char.Items.List.items)<br />
end<br />
end<br />
if inventoryListHandlerID then killAnonymousEventHandler(inventoryListHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryListHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.List", inventoryList) -- register the event handler and save the ID for later killing<br />
<br />
local function inventoryUpdate()<br />
if gmcp.Char.Items.Remove.location == "inv" then<br />
local found<br />
local updatedItem = gmcp.Char.Items.Update.item<br />
for index, item in ipairs(inventory) do<br />
if item.id == updatedItem.id then<br />
found = index<br />
break<br />
end<br />
end<br />
if found then<br />
inventory[found] = table.deepcopy(updatedItem)<br />
end<br />
end<br />
end<br />
if inventoryUpdateHandlerID then killAnonymousEventHandler(inventoryUpdateHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryUpdateHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Update", inventoryUpdate)<br />
<br />
local function inventoryRemove()<br />
if gmcp.Char.Items.Remove.location == "inv" then<br />
local found<br />
local removedItem = gmcp.Char.Items.Remove.item<br />
for index, item in ipairs(inventory) do<br />
if item.id == removedItem.id then<br />
found = index<br />
break<br />
end<br />
end<br />
if found then<br />
table.remove(inventory, found)<br />
end<br />
end<br />
end<br />
if inventoryRemoveHandlerID then killAnonymousEventHandler(inventoryRemoveHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryRemoveHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Remove", inventoryRemove)<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- downloads a package from the internet and kills itself after it is installed.<br />
local saveto = getMudletHomeDir().."/dark-theme-mudlet.zip"<br />
local url = "http://www.mudlet.org/wp-content/files/dark-theme-mudlet.zip"<br />
<br />
if myPackageInstallHandler then killAnonymousEventHandler(myPackageInstallHandler) end<br />
myPackageInstallHandler = registerAnonymousEventHandler(<br />
"sysDownloadDone",<br />
function(_, filename)<br />
if filename ~= saveto then<br />
return true -- keep the event handler since this was not our file<br />
end<br />
installPackage(saveto)<br />
os.remove(b)<br />
end,<br />
true<br />
)<br />
<br />
downloadFile(saveto, url)<br />
cecho("<white>Downloading <green>"..url.."<white> to <green>"..saveto.."\n")<br />
</syntaxhighlight><br />
<br />
==registerNamedEventHandler==<br />
; success = registerNamedEventHandler(userName, handlerName, eventName, functionReference, [oneShot])<br />
<br />
:Registers a named event handler with name handlerName. Named event handlers are protected from duplication and can be stopped and resumed, unlike anonymous event handlers. A separate list is kept per userName<br />
<br />
;See also: [[Manual:Lua_Functions#registerAnonymousEventHandler|registerAnonymousEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]], [[Manual:Lua_Functions#deleteNamedEventHandler|deleteNamedEventHandler()]], [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler. Used to reference the handler in other functions and prevent duplicates. Recommended you use descriptive names, "hp" is likely to collide with something else, "DemonVitals" less so.<br />
* ''eventName:''<br />
: The name of the event the handler responds to. [[Manual:Event_Engine#Mudlet-raised_events|See here]] for a list of Mudlet-raised events.<br />
* ''functionReference:''<br />
: The function reference to run when the event comes in. Can be the name of a function, "handlerFuncion", or the lua function itself. <br />
* ''oneShot:''<br />
: (optional) if true, the event handler will only fire once when the event is raised. If you need to extend a one shot event handler for "one more check" you can have the handler return true, and it will keep firing until the function does not return true.<br />
<br />
;Returns <br />
* true if successful, otherwise errors.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- register a named event handler. Will call demonVitalsHandler(eventName, ...) when gmcp.Char.Vitals is raised.<br />
local ok = registerNamedEventHandler("Demonnic", "DemonVitals", "gmcp.Char.Vitals", "demonVitalsHandler")<br />
if ok then<br />
cecho("Vitals handler switched to demonVitalsHandler")<br />
end<br />
<br />
-- something changes later, and we want to handle vitals with another function, demonBlackoutHandler()<br />
-- note we do not use "" around demonBlackoutHandler but instead pass the function itself. Both work.<br />
-- using the same handlerName ("DemonVitals") means it will automatically unregister the old handler<br />
-- and reregister it using the new information.<br />
local ok = registerNamedEventHandler("Demonnic", "DemonVitals", "gmcp.Char.Vitals", demonBlackoutHandler)<br />
if ok then<br />
cecho("Vitals handler switched to demonBlackoutHandler")<br />
end<br />
<br />
-- Now you want to check your inventory, but you only want to do it once, so you pass the optional oneShot as true<br />
local function handleInv()<br />
local list = gmcp.Char.Items.List<br />
if list.location ~= "inventory" then<br />
return true -- if list.location is, say "room" then we need to keep responding until it's "inventory"<br />
end<br />
display(list.items) -- you would probably store values and update displays or something, but here I'll just show the data as it comes in<br />
end<br />
<br />
-- you can ignore the response from registerNamedEventHandler if you want, it's always going to be true<br />
-- unless there is an error, in which case it throws the error and halts execution anyway. The return is<br />
-- in part for feedback when using the lua alias or other REPL window.<br />
registerNamedEventHandler("Demonnic", "DemonInvCheck", "gmcp.Char.Items.List", handleInv, true)<br />
</syntaxhighlight><br />
<br />
==reloadModule==<br />
;reloadModule(module name)<br />
:Reload a module (by uninstalling and reinstalling).<br />
<br />
:See also: [[#installModule|installModule()]], [[#uninstallModule|uninstallModule()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
reloadModule("3k-mapper")<br />
</syntaxhighlight><br />
<br />
<br />
==removeFileWatch==<br />
;removeFileWatch(path)<br />
:Remove file watch on directory or file. Every change in that file will no longer raise [[Manual:Event_Engine#sysPathChanged|sysPathChanged]] event.<br />
<br />
:See also: [[#addFileWatch|addFileWatch()]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", "herbsChangedHandler")<br />
</syntaxhighlight><br />
<br />
==resetProfile==<br />
;resetProfile()<br />
<br />
:Reloads your entire Mudlet profile - as if you've just opened it. All UI elements will be cleared, so this useful when you're coding your UI.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
resetProfile()<br />
</syntaxhighlight><br />
<br />
The function used to require input from the game to work, but as of Mudlet 3.20 that is no longer the case.<br />
<br />
<br />
{{note}} Don't put resetProfile() in the a script-item in the script editor as the script will be reloaded by resetProfile() as well better use <br />
<syntaxhighlight lang="lua"><br />
lua resetProfile()<br />
</syntaxhighlight><br />
in your commandline or make an Alias containing resetProfile().<br />
<br />
==resumeNamedEventHandler==<br />
; success = resumeNamedEventHandler(userName, handlerName)<br />
<br />
:Resumes a named event handler with name handlerName and causes it to start firing once more.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to resume. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local resumed = resumeNamedEventHandler("Demonnic", "DemonVitals")<br />
if resumed then<br />
cecho("DemonVitals resumed!")<br />
else<br />
cecho("DemonVitals doesn't exist, cannot resume it")<br />
end<br />
</syntaxhighlight><br />
<br />
==saveProfile==<br />
;saveProfile(location)<br />
<br />
:Saves the current Mudlet profile to disk, which is equivalent to pressing the "Save Profile" button.<br />
<br />
;Parameters<br />
* ''location:''<br />
:(optional) folder to save the profile to. If not given, the profile will go into the [[Mudlet_File_Locations|default location]].<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
saveProfile()<br />
<br />
-- save to the desktop on Windows:<br />
saveProfile([[C:\Users\yourusername\Desktop]])<br />
</syntaxhighlight><br />
<br />
==sendSocket==<br />
;sendSocket(data)<br />
<br />
:Sends given binary data as-is to the game. You can use this to implement support for a [[Manual:Supported_Protocols#Adding_support_for_a_telnet_protocol|new telnet protocol]], [http://forums.mudlet.org/viewtopic.php?f=5&t=2272 simultronics] [http://forums.mudlet.org/viewtopic.php?f=5&t=2213#p9810 login] or etcetera.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
TN_IAC = 255<br />
TN_WILL = 251<br />
TN_DO = 253<br />
TN_SB = 250<br />
TN_SE = 240<br />
TN_MSDP = 69<br />
<br />
MSDP_VAL = 1<br />
MSDP_VAR = 2<br />
<br />
sendSocket( string.char( TN_IAC, TN_DO, TN_MSDP ) ) -- sends IAC DO MSDP<br />
<br />
--sends: IAC SB MSDP MSDP_VAR "LIST" MSDP_VAL "COMMANDS" IAC SE<br />
local msg = string.char( TN_IAC, TN_SB, TN_MSDP, MSDP_VAR ) .. " LIST " ..string.char( MSDP_VAL ) .. " COMMANDS " .. string.char( TN_IAC, TN_SE )<br />
sendSocket( msg )<br />
</syntaxhighlight><br />
<br />
{{Note}} Remember that should it be necessary to send the byte value of 255 as a ''data'' byte and not as the Telnet '''IAC''' value it is required to repeat it for Telnet to ignore it and not treat it as the latter.<br />
<br />
==setConfig==<br />
; setConfig(option, value)<br />
<br />
:Sets a Mudlet option to a certain value. This comes in handy for scripts that want to customise Mudlet settings to their preferences - for example, setting up mapper room and exit size to one that works for a certain map, or enabling MSDP for a certain game. For transparency reasons, the Debug window (when open) will show which options were modified by scripts.<br />
:To set many options at once, pass in a table of options. More options will be added over time / per request.<br />
<br />
{{MudletVersion|4.16}}<br />
<br />
;Parameters<br />
* ''option:''<br />
: Particular option to change - see list below for available ones.<br />
* ''value:''<br />
: Value to set - can be a boolean, number, or text depending on the option.<br />
<br />
{| class="wikitable sortable"<br />
|+ General options<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| enableGMCP || Enable GMCP (on by default. Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSDP || Enable MSDP (off by default. Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSSP || Enable MSSP (on by default. Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSP || Enable MSP (on by default. Reconnect after changing) || 4.16 <br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Input line<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| inputLineStrictUnixEndings || Workaround option to use strict UNIX line endings for sending commands || 4.16 <br />
|-<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Main display<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| fixUnnecessaryLinebreaks || Remove extra linebreaks from output (mostly for IRE servers) || 4.16 <br />
|-<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Mapper options<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| mapRoomSize || Size of rooms on map (a good value is 5) || 4.16<br />
|-<br />
| mapExitSize || Size of exits on map (a good value is 10) || 4.16<br />
|-<br />
| mapRoundRooms || Draw rooms round or square || 4.16<br />
|-<br />
| showRoomIdsOnMap || Show room IDs on all rooms (if zoom permits) || 4.16<br />
|-<br />
| showMapInfo || Map overlay text ('Full' or 'Short', can have both at once) || 4.16<br />
|-<br />
| hideMapInfo || Map overlay text ('Full' or 'Short', hide both to hide info altogether) || 4.16<br />
|-<br />
| show3dMapView || Show map as 3D || 4.16<br />
|-<br />
| mapperPanelVisible || Map controls at the bottom || 4.16<br />
|-<br />
| mapShowRoomBorders || Draw a thin border for every room || 4.16<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Special options<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| specialForceCompressionOff || Workaround option to disable MCCP compression, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceGAOff || Workaround option to disable Telnet Go-Ahead, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceCharsetNegotiationOff || Workaround option to disable automatically setting the correct encoding, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceMxpNegotiationOff || Workaround option to disable MXP, in case the game server is not working correctly || 4.16 <br />
|-<br />
|}<br />
<br />
;Returns <br />
* true if successful, or nil+msg if the option doesn't exist. Setting mapper options requires the mapper being open first.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setConfig("mapRoomSize", 5)<br />
<br />
setConfig({mapRoomSize = 6, mapExitSize = 12})<br />
</syntaxhighlight><br />
<br />
==setMergeTables==<br />
;setMergeTables(module)<br />
:Makes Mudlet merge the table of the given GMCP or MSDP module instead of overwriting the data. This is useful if the game sends only partial updates which need combining for the full data. By default "Char.Status" is the only merged module.<br />
<br />
;Parameters<br />
* ''module:''<br />
:Name(s) of the GMCP or MSDP module(s) that should be merged as a string - this will add it to the existing list.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setMergeTables("Char.Skills", "Char.Vitals")<br />
</syntaxhighlight><br />
<br />
==setModuleInfo==<br />
;setModuleInfo(moduleName, info, value)<br />
<br />
:Sets a specific meta info value for a module<br />
<br />
;Parameters<br />
* ''moduleName:''<br />
:Name of the module<br />
* ''info:''<br />
: specific info to set (for example "version")<br />
* ''value:''<br />
: specific value to set (for example "1.0")<br />
<br />
:See also: [[#getModuleInfo|getModuleInfo]], [[#setPackageInfo|getPackageInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setModuleInfo("myModule", "version", "1.0")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==setModulePriority==<br />
;setModulePriority(moduleName, priority)<br />
<br />
:Sets the module priority on a given module as a number - the module priority determines the order modules are loaded in, which can be helpful if you have ones dependent on each other. This can also be set from the module manager window.<br />
: Modules with priority <code>-1</code> will be loaded before scripts (Mudlet 4.11+).<br />
<br />
: See also: [[#getModulePriority|getModulePriority()]]<br />
<br />
<syntaxhighlight lang="lua"><br />
setModulePriority("mudlet-mapper", 1)<br />
</syntaxhighlight><br />
<br />
==setPackageInfo==<br />
;setPackageInfo(packageName, info, value)<br />
<br />
:Sets a specific meta info value for a package<br />
<br />
;Parameters<br />
* ''packageName:''<br />
:Name of the module<br />
* ''info:''<br />
: specific info to set (for example "version")<br />
* ''value:''<br />
: specific value to set (for example "1.0")<br />
<br />
:See also: [[#getPackageInfo|getPackageInfo]], [[#setModuleInfo|setModuleInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setPackageInfo("myPackage", "title", "This is my test package")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==setServerEncoding==<br />
;setServerEncoding(encoding)<br />
:Makes Mudlet use the specified [https://www.w3.org/International/questions/qa-what-is-encoding encoding] for communicating with the game.<br />
<br />
;Parameters<br />
* ''encoding:''<br />
:Encoding to use.<br />
<br />
:See also: [[#getServerEncodingsList|getServerEncodingsList()]], [[#getServerEncoding|getServerEncoding()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- use UTF-8 if Mudlet knows it. Unfortunately there's no way to check if the game's server knows it too.<br />
if table.contains(getServerEncodingsList(), "UTF-8") then<br />
setServerEncoding("UTF-8")<br />
end<br />
</syntaxhighlight><br />
<br />
==showNotification==<br />
;showNotification(title, [content], [expiryTimeInSeconds])<br />
<br />
:Shows a native (system) notification.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
{{Note}} This might not work on all systems, this depends on the system.<br />
<br />
;Parameters<br />
* ''title'' - plain text notification title<br />
* ''content'' - optional argument, plain text notification content, if omitted title argument will be used as content as well<br />
* ''expiryTimeInSeconds'' - optional argument, sets expiration time in seconds for notification, very often ignored by OS<br />
<br />
<syntaxhighlight lang="lua"><br />
showNotification("Notification title", "Notification content", 5)<br />
</syntaxhighlight><br />
<br />
==spawn==<br />
;spawn(readFunction, processToSpawn[, ...arguments])<br />
<br />
:Spawns a process and opens a communicatable link with it - ''read function'' is the function you'd like to use for reading output from the process, and ''t'' is a table containing functions specific to this connection - ''send(data)'', ''true/false = isRunning()'', and ''close()''.<br />
<br />
:This allows you to setup RPC communication with another process.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- simple example on a program that quits right away, but prints whatever it gets using the 'display' function<br />
local f = spawn(display, "ls")<br />
display(f.isRunning())<br />
f.close()<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
local f = spawn(display, "ls", "-la")<br />
display(f.isRunning())<br />
f.close()<br />
</syntaxhighlight><br />
<br />
==startLogging==<br />
;startLogging(state)<br />
<br />
:Control logging of the main console text as text or HTML (as specified by the "Save log files in HTML format instead of plain text" setting on the "General" tab of the "Profile preferences" or "Settings" dialog). Despite being called startLogging it can also stop the process and correctly close the file being created. The file will have an extension of type ".txt" or ".html" as appropriate and the name will be in the form of a date/time "yyyy-MM-dd#hh-mm-ss" using the time/date of when logging started. Note that this control parallels the corresponding icon in the "bottom buttons" for the profile and that button can also start and stop the same logging process and will reflect the state as well.<br />
<br />
;Parameters<br />
* ''state:''<br />
:Required: logging state. Passed as a boolean<br />
<br />
;Returns (4 values)<br />
* ''successful (bool)''<br />
:''true'' if the logging state actually changed; if, for instance, logging was already active and ''true'' was supplied then no change in logging state actually occurred and ''nil'' will be returned (and logging will continue).<br />
* ''message (string)''<br />
:A displayable message given one of four messages depending on the current and previous logging states, this will include the file name except for the case when logging was not taking place and the supplied argument was also ''false''.<br />
* ''fileName (string)''<br />
:The log will be/is being written to the path/file name returned.<br />
* ''code (number)''<br />
:A value indicating the response to the system to this instruction:<br />
* 0 = logging has just stopped<br />
* 1 = logging has just started<br />
* -1 = logging was already in progress so no change in logging state<br />
* -2 = logging was already not in progress so no change in logging state<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- start logging<br />
local success, message, filename, code = startLogging(true)<br />
if code == 1 or code == -1 then print(f"Started logging to {filename}") end<br />
<br />
-- stop logging<br />
startLogging(false)<br />
</syntaxhighlight><br />
<br />
==stopAllNamedEventHandlers==<br />
; stopAllNamedEventHandlers(userName)<br />
<br />
:Stops all named event handlers and prevents them from firing any more. Information is retained and handlers can be resumed.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameter<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
stopAllNamedEventHandlers() -- emergency stop situation, most likely.<br />
</syntaxhighlight><br />
<br />
==stopMusic==<br />
;stopMusic(settings table)<br />
:Stop all music (no filter), or music that meets a combination of filters (name, key, and tag) intended to be paired with [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|-<br />
| style="text-align:center;"| No<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Stop all playing music files for this profile associated with the API<br />
stopMusic()<br />
<br />
-- Stop playing the rugby mp3 by name<br />
stopMusic({name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
<br />
-- Stop playing the unique sound identified as "rugby"<br />
stopMusic({<br />
name = nil -- nil lines are optional, no need to use<br />
, key = "rugby" -- key<br />
, tag = nil -- nil lines are optional, no need to use<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of stopMusic([name][,key][,tag]) ----<br />
<br />
-- Stop all playing music files for this profile associated with the API<br />
stopMusic()<br />
<br />
-- Stop playing the rugby mp3 by name<br />
stopMusic("167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
<br />
-- Stop playing the unique sound identified as "rugby"<br />
stopMusic(<br />
nil -- name<br />
, "rugby" -- key<br />
, nil -- tag<br />
)<br />
</syntaxhighlight><br />
<br />
==stopNamedEventHandler==<br />
; success = stopNamedEventHandler(userName, handlerName)<br />
<br />
:Stops a named event handler with name handlerName and prevents it from firing any more. Information is stored so it can be resumed later if desired.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to stop. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist or was already stopped<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local stopped = stopNamedEventHandler("DemonVitals")<br />
if stopped then<br />
cecho("DemonVitals stopped!")<br />
else<br />
cecho("DemonVitals doesn't exist or already stopped; either way it won't fire any more.")<br />
end<br />
</syntaxhighlight><br />
<br />
==stopSounds==<br />
;stopSounds(settings table)<br />
:Stop all sounds (no filter), or sounds that meets a combination of filters (name, key, tag, and priority) intended to be paired with [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|-<br />
| style="text-align:center;"| No<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| priority<br />
| 1 to 100<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a matching or lower priority.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Stop all playing sound files for this profile associated with the API<br />
stopSounds()<br />
<br />
-- Stop playing the cow sound<br />
stopSounds({name = "cow.wav"})<br />
<br />
-- Stop playing any sounds tagged as "animals" with a priority less than or equal to 50<br />
---- This would not stop sounds tagged as "animals" greater than priority 50. This is an "AND" and not an "OR".<br />
stopSounds({<br />
name = nil -- nil lines are optional, no need to use<br />
, key = nil -- nil lines are optional, no need to use<br />
, tag = "animals"<br />
, priority = 50<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of stopSounds([name][,key][,tag][,priority]) ----<br />
<br />
-- Stop all playing sound files for this profile associated with the API<br />
stopSounds()<br />
<br />
-- Stop playing the cow sound<br />
stopSounds("cow.wav")<br />
<br />
-- Stop playing any sounds tagged as "animals" with a priority less than or equal to 50<br />
---- This would not stop sounds tagged as "animals" greater than priority 50. This is an "AND" and not an "OR".<br />
stopSounds(<br />
nil -- name<br />
, nil -- key<br />
, "animals" -- tag<br />
, 50 -- priority<br />
)<br />
</syntaxhighlight><br />
<br />
==timeframe==<br />
;timeframe(vname, true_time, nil_time, ...)<br />
<br />
:A utility function that helps you change and track variable states without using a lot of tempTimers.<br />
<br />
{{MudletVersion|3.6}}<br />
<br />
;Parameters<br />
* ''vname:''<br />
:A string or function to use as the variable placeholder.<br />
* ''true_time:''<br />
:Time before setting the variable to true. Can be a number or a table in the format: <code>{time, value}</code><br />
* ''nil_time:''<br />
:(optional) Number of seconds until <code>vname</code> is set back to nil. Leaving it undefined will leave it at whatever it was set to last. Can be a number of a table in the format: <code>{time, value}</code><br />
* ''...:''<br />
:(optional) Further list of times and values to set the variable to, in the following format: <code>{time, value}</code><br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- sets the global 'limiter' variable to true immediately (see the 0) and back to nil in one second (that's the 1).<br />
timeframe("limiter", 0, 1)<br />
<br />
-- An angry variable 'giant' immediately set to "fee", followed every second after by "fi", "fo", and "fum" before being reset to nil at four seconds.<br />
timeframe("giant", {0, "fee"}, 4, {1, "fi"}, {2, "fo"}, {3, "fum"})<br />
<br />
-- sets the local 'width' variable to true immediately and back to nil in one second.<br />
local width<br />
timeframe(function(value) width = value end, 0, 1)<br />
</syntaxhighlight><br />
<br />
==translateTable==<br />
;translateTable(directions, [languagecode])<br />
<br />
:Given a table of directions (such as <code>speedWalkDir</code>), translates directions to another language for you. Right now, it can only translate it into the language of Mudlet's user interface - but [https://github.com/Mudlet/Mudlet/issues/new let us know if you need more].<br />
<br />
{{MudletVersion|3.22}}<br />
<br />
;Parameters<br />
* ''directions:''<br />
:An indexed table of directions (eg. <code>{"sw", "w", "nw", "s"}</code>).<br />
* ''languagecode:''<br />
:(optional) Language code (eg <code>ru_RU</code> or <code>it_IT</code>) - by default, <code>mudlet.translations.interfacelanguage</code> is used.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- get the path from room 2 to room 5 and translate directions<br />
if getPath(2, 5) then<br />
speedWalkDir = translateTable(speedWalkDir)<br />
print("Translated directions:")<br />
display(speedWalkDir)<br />
</syntaxhighlight><br />
<br />
==uninstallModule==<br />
;uninstallModule(name)<br />
<br />
:Uninstalls a Mudlet module with the given name.<br />
<br />
:See also: [[#installModule | installModule()]], [[Manual:Event_Engine#sysLuaUninstallModule | Event: sysLuaUninstallModule]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
uninstallModule("myalias")<br />
</syntaxhighlight><br />
<br />
==uninstallPackage==<br />
;uninstallPackage(name)<br />
<br />
:Uninstalls a Mudlet package with the given name.<br />
<br />
:See also: [[#installPackage | installPackage()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
uninstallPackage("myalias")<br />
</syntaxhighlight><br />
<br />
==unzipAsync==<br />
;unzipAsync(path, location)<br />
<br />
:Unzips the zip file at path, extracting the contents to the location provided. Returns true if it is able to start unzipping, or nil+message if it cannot.<br />
Raises the <code>sysUnzipDone</code> event with the zip file location and location unzipped to as arguments if unzipping is successful, and <code>sysUnzipError</code> with the same arguments if it is not.<br />
<br />
Do not use the <code>unzip()</code> function as it is synchronous and will impact Mudlet's performance (ie, freeze Mudlet while unzipping).<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function handleUnzipEvents(event, ...)<br />
local args = {...}<br />
local zipName = args[1]<br />
local unzipLocation = args[2]<br />
if event == "sysUnzipDone" then<br />
cecho(string.format("<green>Unzip successful! Unzipped %s to %s\n", zipName, unzipLocation))<br />
elseif event == "sysUnzipError" then<br />
cecho(string.format("<firebrick>Unzip failed! Tried to unzip %s to %s\n", zipName, unzipLocation))<br />
end<br />
end<br />
if unzipSuccessHandler then killAnonymousEventHandler(unzipSuccessHandler) end<br />
if unzipFailureHandler then killAnonymousEventHandler(unzipFailureHandler) end<br />
unzipSuccessHandler = registerAnonymousEventHandler("sysUnzipDone", "handleUnzipEvents")<br />
unzipFailureHandler = registerAnonymousEventHandler("sysUnzipError", "handleUnzipEvents")<br />
--use the path to your zip file for this, not mine<br />
local zipFileLocation = "/home/demonnic/Downloads/Junkyard_Orc.zip" <br />
--directory to unzip to, it does not need to exist but you do need to be able to create it<br />
local unzipLocation = "/home/demonnic/Downloads/Junkyard_Orcs" <br />
unzipAsync(zipFileLocation, unzipLocation) -- this will work<br />
unzipAsync(zipFileLocation .. "s", unzipLocation) --demonstrate error, will happen first because unzipping takes time</syntaxhighlight><br />
<br />
==yajl.to_string==<br />
;yajl.to_string(data)<br />
<br />
:Encodes a Lua table into JSON data and returns it as a string. This function is very efficient - if you need to encode into JSON, use this.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- on IRE MUD games, you can send a GMCP request to request the skills in a particular skillset. Here's an example:<br />
sendGMCP("Char.Skills.Get "..yajl.to_string{group = "combat"})<br />
<br />
-- you can also use it to convert a Lua table into a string, so you can, for example, store it as room's userdata<br />
local toserialize = yajl.to_string(continents)<br />
setRoomUserData(1, "areaContinents", toserialize)<br />
</syntaxhighlight><br />
<br />
<br />
==yajl.to_value==<br />
;yajl.to_value(data)<br />
<br />
:Decodes JSON data (as a string) into a Lua table. This function is very efficient - if you need to dencode into JSON, use this.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- given the serialization example above with yajl.to_string, you can deserialize room userdata back into a table<br />
local tmp = getRoomUserData(1, "areaContinents")<br />
if tmp == "" then return end<br />
<br />
local continents = yajl.to_value(tmp)<br />
display(continents)<br />
</syntaxhighlight><br />
<br />
[[Category:Mudlet Manual]]<br />
[[Category:Mudlet API]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Miscellaneous_Functions&diff=20312Manual:Miscellaneous Functions2023-02-16T23:36:50Z<p>Kebap: /* getPackageInfo */ Typo</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Mudlet API documentation for miscellaneous functions.}}<br />
= Miscellaneous Functions =<br />
<br />
==addFileWatch==<br />
;addFileWatch(path)<br />
:Adds file watch on directory or file. Every change in that file (or directory) will raise [[Manual:Event_Engine#sysPathChanged|sysPathChanged]] event.<br />
<br />
:See also: [[#removeFileWatch|removeFileWatch()]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", "herbsChangedHandler")<br />
</syntaxhighlight><br />
<br />
==addSupportedTelnetOption==<br />
;addSupportedTelnetOption(option)<br />
:Adds a telnet option, which when queried by a game server, Mudlet will return DO (253) on. Use this to register the telnet option that you will be adding support for with Mudlet - see [[Manual:Supported_Protocols#Adding_support_for_a_telnet_protocol|additional protocols]] section for more.<br />
<br />
;Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
<event handlers that add support for MSDP... see http://www.mudbytes.net/forum/comment/63920/#c63920 for an example><br />
<br />
-- register with Mudlet that it should not decline the request of MSDP support<br />
local TN_MSDP = 69<br />
addSupportedTelnetOption(TN_MSDP)<br />
</syntaxhighlight><br />
<br />
==alert==<br />
;alert([seconds])<br />
:alerts the user to something happening - makes Mudlet flash in the Windows window bar, bounce in the macOS dock, or flash on Linux.<br />
<br />
{{MudletVersion|3.2}}<br />
<br />
;Parameters<br />
* ''seconds:''<br />
:(optional) number of seconds to have the alert for. If not provided, Mudlet will flash until the user opens Mudlet again.<br />
<br />
;Example:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- flash indefinitely until Mudlet is open<br />
alert()<br />
<br />
-- flash for just 3 seconds<br />
alert(3)<br />
</syntaxhighlight><br />
<br />
==cfeedTriggers==<br />
;cfeedTriggers(text)<br />
:Like feedTriggers, but you can add color information using color names, similar to cecho.<br />
<br />
;Parameters<br />
* ''text'': The string to feed to the trigger engine. Include colors by name as black,red,green,yellow,blue,magenta,cyan,white and light_* versions of same. You can also use a number to get the ansi color corresponding to that number.<br />
:See also: [[#feedTriggers|feedTriggers]]<br />
<br />
{{MudletVersion|4.10}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
cfeedTriggers("<green:red>green on red<r> reset <124:100> foreground of ANSI124 and background of ANSI100<r>\n")<br />
</syntaxhighlight><br />
<br />
==closeMudlet==<br />
;closeMudlet()<br />
<br />
:Closes Mudlet and all profiles immediately.<br />
:See also: [[Manual:Lua_Functions#saveProfile|saveProfile()]]<br />
<br />
{{note}} Use with care. This potentially lead to data loss, if "save on close" is not activated and the user didn't save the profile manually as this will NOT ask for confirmation nor will the profile be saved. Also it does not consider if there are ''other'' profiles open if multi-playing: they '''all''' will be closed!<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
closeMudlet()<br />
</syntaxhighlight><br />
<br />
==deleteAllNamedEventHandlers==<br />
; deleteAllNamedEventHandlers(userName)<br />
<br />
:Deletes all named event handlers for userName and prevents them from firing any more. Information is deleted and cannot be retrieved.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteAllNamedEventHandlers("Demonnic") -- emergency stop or debugging situation, most likely.<br />
</syntaxhighlight><br />
<br />
==deleteNamedEventHandler==<br />
; success = deleteNamedEventHandler(userName, handlerName)<br />
<br />
:Deletes a named event handler with name handlerName and prevents it from firing any more. Information is deleted and cannot be retrieved.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to stop. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local deleted = deleteNamedEventHandler("Demonnic", "Vitals")<br />
if deleted then<br />
cecho("Vitals deleted forever!!")<br />
else<br />
cecho("Vitals doesn't exist and so could not be deleted.")<br />
end<br />
</syntaxhighlight><br />
<br />
==denyCurrentSend==<br />
;denyCurrentSend()<br />
<br />
:Cancels a [[Manual:Lua_Functions#send|send()]] or user-entered command, but only if used within a [[Manual:Event_Engine#sysDataSendRequest|sysDataSendRequest]] event.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- cancels all "eat hambuger" commands<br />
function cancelEatHamburger(event, command)<br />
if command == "eat hamburger" then<br />
denyCurrentSend()<br />
cecho("<red>Denied! Didn't let the command through.\n")<br />
end<br />
end<br />
<br />
registerAnonymousEventHandler("sysDataSendRequest", "cancelEatHamburger")<br />
</syntaxhighlight><br />
<br />
==dfeedTriggers==<br />
;dfeedTriggers(str)<br />
:Like feedTriggers, but you can add color information using <r,g,b>, similar to decho.<br />
<br />
;Parameters<br />
* ''str'': The string to feed to the trigger engine. Include color information inside tags like decho.<br />
;See also: [[Manual:Lua_Functions#cfeedTriggers|cfeedTriggers]], [[Manual:Lua_Functions#decho|decho]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
dfeedTriggers("<0,128,0:128,0,0>green on red<r> reset\n")<br />
</syntaxhighlight><br />
<br />
==disableModuleSync==<br />
;disableModuleSync(name)<br />
: Stops syncing the given module.<br />
<br />
;Parameter<br />
* ''name'': name of the module.<br />
<br />
:See also: [[Manual:Lua_Functions#enableModuleSync|enableModuleSync()]], [[Manual:Lua_Functions#getModuleSync|getModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==enableModuleSync==<br />
;enableModuleSync(name)<br />
: Enables the sync for the given module name - any changes done to it will be saved to disk and if the module is installed in any other profile(s), it'll be updated in them as well on profile save.<br />
<br />
;Parameter<br />
* ''name'': name of the module to enable sync on.<br />
<br />
:See also: [[Manual:Lua_Functions#disableModuleSync|disableModuleSync()]], [[Manual:Lua_Functions#getModuleSync|getModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==expandAlias==<br />
;expandAlias(command, [echoBackToBuffer])<br />
:Runs the command as if it was from the command line - so aliases are checked and if none match, it's sent to the game unchanged. <br />
<br />
;Parameters<br />
* ''command''<br />
: Text of the command you want to send to the game. Will be checked for aliases.<br />
* ''echoBackToBuffer''<br />
: (optional) If ''false'', the command will not be echoed back in your buffer. Defaults to ''true'' if omitted.<br />
<br />
{{note}} Using expandAlias is not recommended anymore as it is not very robust and may lead to problems down the road. The recommendation is to use lua functions instead. See [[Manual:Functions_vs_expandAlias]] for details and examples.<br />
<br />
{{note}} If you want to be using the ''matches'' table after calling ''expandAlias'', you should save it first, as, e.g. ''local oldmatches = matches'' before calling ''expandAlias'', since ''expandAlias'' will overwrite it after using it again.<br />
<br />
{{note}} Since '''Mudlet 3.17.1''' the optional second argument to echo the command on screen will be ineffective whilst the game server has negotiated the telnet ECHO option to provide the echoing of text we ''send'' to him.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
expandAlias("t rat")<br />
<br />
-- don't echo the command<br />
expandAlias("t rat", false)<br />
</syntaxhighlight><br />
<br />
==feedTriggers==<br />
;feedTriggers(text[, dataIsUtf8Encoded = true])<br />
:This function will have Mudlet parse the given text as if it came from the game - one great application is trigger testing. The built-in '''`echo''' alias provides this functionality as well.<br />
<br />
;Parameters<br />
* ''text:''<br />
:string which is sent to the trigger processing system almost as if it came from the game server. This string must be byte encoded in a manner to match the currently selected ''Server Encoding''. <br />
* ''dataIsUtf8Encoded'' (available in Mudlet 4.2+):<br />
:Set this to false, if you need pre-Mudlet 4.0 behavior. Most players won't need this.<br />
:(Before Mudlet 4.0 the text had to be encoded directly in whatever encoding the setting in the preferences was set to. <br />
:(Encoding could involve using the Lua string character escaping mechanism of \ and a base 10 number for character codes from \1 up to \255 at maximum)<br />
:Since Mudlet 4.0 it is assumed that the text is UTF-8 encoded. It will then be automatically converted to the currently selected game server encoding.<br />
:Preventing the automatic conversion can be useful to Mudlet developers testing things, or possibly to those who are creating handlers for Telnet protocols within the Lua subsystem, who need to avoid the transcoding of individual protocol bytes, when they might otherwise be seen as extended ASCII characters.)<br />
<br />
;Returns (available in Mudlet 4.2+):<br />
* ''true'' on success, ''nil'' and an error message if the text contains characters that cannot be conveyed by the current Game Server encoding.<br />
<br />
{{note}} It is important to ensure that in Mudlet 4.0.0 and beyond the text data only contains characters that can be encoded in the current Game Server encoding, from 4.2.0 the content is checked that it can successfully be converted from the UTF-8 that the Mudlet Lua subsystem uses internally into that particular encoding and if it cannot the function call will fail and not pass any of the data, this will be significant if the text component contains any characters that are not plain ASCII.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- try using this on the command line<br />
`echo This is a sample line from the game<br />
<br />
-- You can use \n to represent a new line - you also want to use it before and after the text you’re testing, like so:<br />
feedTriggers("\nYou sit yourself down.\n")<br />
<br />
-- The function also accept ANSI color codes that are used in games. A sample table can be found http://codeworld.wikidot.com/ansicolorcodes<br />
feedTriggers("\nThis is \27[1;32mgreen\27[0;37m, \27[1;31mred\27[0;37m, \27[46mcyan background\27[0;37m," ..<br />
"\27[32;47mwhite background and green foreground\27[0;37m.\n")<br />
</syntaxhighlight><br />
<br />
==getCharacterName==<br />
;getCharacterName()<br />
<br />
:Returns the name entered into the "Character name" field on the Connection Preferences form. Can be used to find out the name that might need to be handled specially in scripts or anything that needs to be personalized to the player. If there is nothing set in that entry will return an empty string.<br />
<br />
:See also: [[#getProfileName|getProfileName()]]<br />
<br />
{{MudletVersion|4.16}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- cast glamor on yourself<br />
<br />
send("cast 'glamor' " .. getCharacterName())<br />
</syntaxhighlight><br />
<br />
==getModulePath==<br />
;path = getModulePath(module name)<br />
<br />
:Returns the location of a module on the disk. If the given name does not correspond to an installed module, it'll return <code>nil</code><br />
:See also: [[Manual:Lua_Functions#installModule|installModule()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModulePath("mudlet-mapper")<br />
</syntaxhighlight><br />
<br />
==getModulePriority==<br />
;priority = getModulePriority(module name)<br />
<br />
:Returns the priority of a module as an integer. This determines the order modules will be loaded in - default is 0. Useful if you have a module that depends on another module being loaded first, for example.<br />
:Modules with priority <code>-1</code> will be loaded before scripts (Mudlet 4.11+).<br />
<br />
:See also: [[Manual:Lua_Functions#setModulePriority|setModulePriority()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModulePriority("mudlet-mapper")<br />
</syntaxhighlight><br />
<br />
==getModules==<br />
;getModules()<br />
<br />
:Returns installed modules as table.<br />
<br />
:See also: [[#getPackages|getPackages]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Check if the module myTabChat is installed and if it isn't install it and enable sync on it<br />
if not table.contains(getModules(),"myTabChat") then<br />
installModule(getMudletHomeDir().."/modules/myTabChat.xml")<br />
enableModuleSync("myTabChat")<br />
end<br />
<br />
</syntaxhighlight><br />
<br />
==getModuleInfo==<br />
;getModuleInfo(moduleName, [info])<br />
<br />
:Returns table with meta information for a package<br />
<br />
;Parameters<br />
* ''moduleName:''<br />
:Name of the package<br />
* ''info:''<br />
:(optional) specific info wanted to get, if not given all available meta-info is returned<br />
<br />
:See also: [[#getPackageInfo|getPackageInfo]], [[#setModuleInfo|getModuleInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getModuleInfo("myModule","author")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==getModuleSync==<br />
;getModuleSync(name)<br />
: returns false if module sync is not active, true if it is active and nil if module is not found.<br />
<br />
;Parameter<br />
* ''name'': name of the module<br />
<br />
:See also: [[Manual:Lua_Functions#enableModuleSync|enableModuleSync()]], [[Manual:Lua_Functions#disableModuleSync|disableModuleSync()]]<br />
{{MudletVersion|4.8}}<br />
<br />
==getMudletHomeDir==<br />
;getMudletHomeDir()<br />
:Returns the current home directory of the current profile. This can be used to store data, save statistical information, or load resource files from packages.<br />
<br />
{{note}} intentionally uses forward slashes <code>/</code> as separators on Windows since [[Manual:UI_Functions#setLabelStyleSheet|stylesheets]] require them.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- save a table<br />
table.save(getMudletHomeDir().."/myinfo.dat", myinfo)<br />
<br />
-- or access package data. The forward slash works even on Windows fine<br />
local path = getMudletHomeDir().."/mypackagename"<br />
</syntaxhighlight><br />
<br />
==getMudletInfo==<br />
;getMudletInfo()<br />
:Prints debugging information about the Mudlet that you're running - this can come in handy for diagnostics.<br />
<br />
Don't use this command in your scripts to find out if certain features are supported in Mudlet - there are better functions available for this.<br />
<br />
{{MudletVersion|4.8}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getMudletInfo()<br />
</syntaxhighlight><br />
<br />
==getMudletVersion==<br />
;getMudletVersion(style)<br />
:Returns the current Mudlet version. Note that you shouldn't hardcode against a specific Mudlet version if you'd like to see if a function is present - instead, check for the existence of the function itself. Otherwise, checking for the version can come in handy if you'd like to test for a broken function or so on.<br />
<br />
See also: [[#mudletOlderThan|mudletOlderThan()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Parameters<br />
* ''style:''<br />
:(optional) allows you to choose what you'd like returned. By default, if you don't specify it, a key-value table with all the values will be returned: major version, minor version, revision number and the optional build name.<br />
<br />
;Values you can choose<br />
* ''"string"'':<br />
:Returns the full Mudlet version as text.<br />
* ''"table"'':<br />
:Returns the full Mudlet version as four values (multi-return)<br />
* ''"major"'':<br />
:Returns the major version number (the first one).<br />
* ''"minor"'':<br />
:Returns the minor version number (the second one).<br />
* ''"revision"'':<br />
:Returns the revision version number (the third one).<br />
* ''"build"'':<br />
:Returns the build of Mudlet (the ending suffix, if any).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- see the full Mudlet version as text:<br />
getMudletVersion("string")<br />
-- returns for example "3.0.0-alpha"<br />
<br />
-- check that the major Mudlet version is at least 3:<br />
if getMudletVersion("major") >= 3 then echo("You're running on Mudlet 3+!") end<br />
-- but mudletOlderThan() is much better for this:<br />
if mudletOlderThan(3) then echo("You're running on Mudlet 3+!") end <br />
<br />
-- if you'd like to see if a function is available however, test for it explicitly instead:<br />
if setAppStyleSheet then<br />
-- example credit to http://qt-project.org/doc/qt-4.8/stylesheet-examples.html#customizing-qscrollbar<br />
setAppStyleSheet[[<br />
QScrollBar:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
width: 15px;<br />
margin: 22px 0 22px 0;<br />
}<br />
QScrollBar::handle:vertical {<br />
background: white;<br />
min-height: 20px;<br />
}<br />
QScrollBar::add-line:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
height: 20px;<br />
subcontrol-position: bottom;<br />
subcontrol-origin: margin;<br />
}<br />
QScrollBar::sub-line:vertical {<br />
border: 2px solid grey;<br />
background: #32CC99;<br />
height: 20px;<br />
subcontrol-position: top;<br />
subcontrol-origin: margin;<br />
}<br />
QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical {<br />
border: 2px solid grey;<br />
width: 3px;<br />
height: 3px;<br />
background: white;<br />
}<br />
QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {<br />
background: none;<br />
}<br />
]]<br />
end<br />
</syntaxhighlight><br />
<br />
==getNewIDManager==<br />
; getNewIDManager()<br />
<br />
:Returns an IDManager object, for manager your own set of named events and timers isolated from the rest of the profile.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
{{note}} Full IDManager usage can be found at [[Manual:IDManager|IDManager]]<br />
<br />
;Returns<br />
* an IDManager for managing your own named events and timers<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
demonnic = demonnic or {}<br />
demonnic.IDManager = getNewIDManager()<br />
local idm = demonnic.IDManager<br />
-- assumes you have defined demonnic.vitalsUpdate and demonnic.balanceChecker as functions<br />
idm:registerEvent("DemonVitals", "gmcp.Char.Vitals", demonnic.vitalsUpdate)<br />
idm:registerTimer("Balance Check", 1, demonnic.balanceChecker)<br />
idm:stopEvent("DemonVitals")<br />
</syntaxhighlight><br />
<br />
==getNamedEventHandlers==<br />
; handlers = getNamedEventHandlers(userName)<br />
<br />
:Returns a list of all userName's named event handlers' names as a table.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Returns <br />
* a table of handler names. { "DemonVitals", "DemonInv" } for example. {} if none are registered<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local handlers = getNamedEventHandlers()<br />
display(handlers)<br />
-- {}<br />
registerNamedEventHandler("Test1", "testEvent", "testFunction")<br />
registerNamedEventHandler("Test2", "someOtherEvent", myHandlerFunction)<br />
handlers = getNamedEventHandlers()<br />
display(handlers)<br />
-- { "Test1", "Test2" }<br />
</syntaxhighlight><br />
<br />
==getOS==<br />
;getOS()<br />
<br />
:Returns the name of the Operating System (OS). Useful for applying particular scripts only under particular operating systems, such as applying a stylesheet only when the OS is Windows. <br />
:Returned text will be one of these: "windows", "mac", "linux", as well as "cygwin", "hurd", "freebsd", "kfreebsd", "openbsd", "netbsd", "bsd4", "unix" or "unknown" otherwise.<br />
:Additionally returns the version of the OS, and if using Linux, the distribution in use (as of Mudlet 4.12+).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getOS())<br />
<br />
if getOS() == "windows" then<br />
echo("\nWindows OS detected.\n")<br />
else<br />
echo("\nDetected Operating system is NOT windows.\n")<br />
end<br />
<br />
if mudlet.supports.osVersion then<br />
local os, osversion = getOS()<br />
print(f"Running {os} {osversion}")<br />
end<br />
</syntaxhighlight><br />
<br />
==getPackages==<br />
;getPackages()<br />
<br />
:Returns installed packages as table.<br />
<br />
:See also: [[#getModules|getModules]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Check if the generic_mapper package is installed and if so uninstall it<br />
if table.contains(getPackages(),"generic_mapper") then<br />
uninstallPackage("generic_mapper")<br />
end<br />
<br />
</syntaxhighlight><br />
<br />
==getPackageInfo==<br />
;getPackageInfo(packageName, [info])<br />
<br />
:Returns table with meta information for a package<br />
<br />
;Parameters<br />
* ''packageName:''<br />
:Name of the package<br />
* ''info:''<br />
:(optional) specific info wanted to get, if not given all available meta-info is returned<br />
<br />
:See also: [[#getModuleInfo|getModuleInfo]], [[#setPackageInfo|setPackageInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getPackageInfo("myPackage", "version")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==getProfileName==<br />
;getProfileName()<br />
<br />
:Returns the name of the profile. Useful when combined with [[Manual:Mudlet_Object_Functions#raiseGlobalEvent|raiseGlobalEvent()]] to know which profile a global event came from.<br />
<br />
{{MudletVersion|3.1}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- if connected to the Achaea profile, will print Achaea to the main console<br />
echo(getProfileName())<br />
</syntaxhighlight><br />
<br />
==getCommandSeparator==<br />
;getCommandSeparator()<br />
<br />
:Returns the command separator in use by the profile.<br />
<br />
{{MudletVersion|3.18}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- if your command separator is ;;, the following would send("do thing 1;;do thing 2"). <br />
-- This way you can determine what it is set to and use that and share this script with <br />
-- someone who has changed their command separator.<br />
-- Note: This is not really the preferred way to send this, using sendAll("do thing 1", "do thing 2") is,<br />
-- but this illustates the use case.<br />
local s = getCommandSeparator()<br />
expandAlias("do thing 1" .. s .. "do thing 2")<br />
</syntaxhighlight><br />
<br />
==getServerEncoding==<br />
;getServerEncoding()<br />
:Returns the current server [https://www.w3.org/International/questions/qa-what-is-encoding data encoding] in use.<br />
<br />
:See also: [[#setServerEncoding|setServerEncoding()]], [[#getServerEncodingsList|getServerEncodingsList()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getServerEncoding()<br />
</syntaxhighlight><br />
<br />
==getServerEncodingsList==<br />
;getServerEncodingsList()<br />
:Returns an indexed list of the server [https://www.w3.org/International/questions/qa-what-is-encoding data encodings] that Mudlet knows. This is not the list of encodings the servers knows - there's unfortunately no agreed standard for checking that. See [[Manual:Unicode#Changing_encoding|encodings in Mudlet]] for the list of which encodings are available in which Mudlet version.<br />
<br />
:See also: [[#setServerEncoding|setServerEncoding()]], [[#getServerEncoding|getServerEncoding()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- check if UTF-8 is available:<br />
if table.contains(getServerEncodingsList(), "UTF-8") then<br />
print("UTF-8 is available!")<br />
end<br />
</syntaxhighlight><br />
<br />
==getWindowsCodepage==<br />
;getWindowsCodepage()<br />
:Returns the current [https://docs.microsoft.com/en-us/windows/desktop/Intl/code-page-identifiers codepage] of your Windows system.<br />
<br />
{{MudletVersion|3.22}}<br />
{{Note}} This function only works on Windows - It is only needed internally in Mudlet to enable Lua to work with non-ASCII usernames (e.g. Iksiński, Jäger) for the purposes of IO. Linux and macOS work fine with with these out of the box.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
print(getWindowsCodepage())<br />
</syntaxhighlight><br />
<br />
==hfeedTriggers==<br />
;hfeedTriggers(str)<br />
:Like feedTriggers, but you can add color information using #RRGGBB in hex, similar to hecho.<br />
<br />
;Parameters<br />
* ''str'': The string to feed to the trigger engine. Include color information in the same manner as hecho.<br />
:See also: [[Manual:Lua_Functions#dfeedTriggers|dfeedTriggers]]<br />
:See also: [[Manual:Lua_Functions#hecho|hecho]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
hfeedTriggers("#008000,800000green on red#r reset\n")<br />
</syntaxhighlight><br />
<br />
==installModule==<br />
;installModule(location)<br />
:Installs a Mudlet XML, zip, or mpackage as a module.<br />
<br />
;Parameters<br />
* ''location:''<br />
:Exact location of the file install.<br />
<br />
:See also: [[#uninstallModule | uninstallModule()]], [[Manual:Event_Engine#sysLuaInstallModule | Event: sysLuaInstallModule]], [[#setModulePriority | setModulePriority()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
installModule([[C:\Documents and Settings\bub\Desktop\myalias.xml]])<br />
</syntaxhighlight><br />
<br />
==installPackage==<br />
;installPackage(location or url)<br />
:Installs a Mudlet XML or package. Since Mudlet 4.11+ returns <code>true</code> if it worked, or <code>false</code>.<br />
<br />
;Parameters<br />
* ''location:''<br />
:Exact location of the xml or package to install.<br />
Since Mudlet 4.11+ it is possible to pass download link to a package (must start with <code>http</code> or <code>https</code> and end with <code>.xml</code>, <code>.zip</code>, <code>.mpackage</code> or <code>.trigger</code>)<br />
<br />
:See also: [[#uninstallPackage | uninstallPackage()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
installPackage([[C:\Documents and Settings\bub\Desktop\myalias.xml]])<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
installPackage([[https://github.com/Mudlet/Mudlet/blob/development/src/run-lua-code-v4.xml]])<br />
</syntaxhighlight><br />
<br />
==killAnonymousEventHandler==<br />
;killAnonymousEventHandler(handler id)<br />
:Disables and removes the given event handler.<br />
<br />
;Parameters<br />
* ''handler id''<br />
:ID of the event handler to remove as returned by the [[ #registerAnonymousEventHandler | registerAnonymousEventHandler ]] function.<br />
<br />
:See also: [[ #registerAnonymousEventHandler | registerAnonymousEventHandler ]]<br />
<br />
{{MudletVersion|3.5}}<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- registers an event handler that prints the first 5 GMCP events and then terminates itself<br />
<br />
local counter = 0<br />
local handlerId = registerAnonymousEventHandler("gmcp", function(_, origEvent)<br />
print(origEvent)<br />
counter = counter + 1<br />
if counter == 5 then<br />
killAnonymousEventHandler(handlerId)<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
==loadMusicFile==<br />
;loadMusicFile(settings table) or loadMusicFile(name, [url])<br />
:Loads music files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]] and [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]]. Although files could be loaded directly at playing time from [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], loadMusicFile() provides the advantage of loading files in advance. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if file to load is not part of the profile or on the local file system.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#playMusicFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Download from the Internet<br />
loadMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
<br />
-- OR download from the profile<br />
loadMusicFile({name = getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
<br />
-- OR download from the local file system<br />
loadMusicFile({name = "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of loadMusicFile(name[, url]) ----<br />
<br />
-- Download from the Internet<br />
loadMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
)<br />
<br />
-- OR download from the profile<br />
loadMusicFile(getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
<br />
-- OR download from the local file system<br />
loadMusicFile("C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
</syntaxhighlight><br />
<br />
==loadSoundFile==<br />
;loadSoundFile(settings table) or loadSoundFile(name, [url])<br />
:Loads sound files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]] and [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]]. Although files could be loaded directly at playing time from [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], loadSoundFile() provides the advantage of loading files in advance. <br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if file to load is not part of the profile or on the local file system.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Download from the Internet<br />
loadSoundFile({<br />
name = "cow.wav"<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
<br />
-- OR download from the profile<br />
loadSoundFile({name = getMudletHomeDir().. "/cow.wav"})<br />
<br />
-- OR download from the local file system<br />
loadSoundFile({name = "C:/Users/Tamarindo/Documents/cow.wav"})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of loadSoundFile(name[,url]) ----<br />
<br />
-- Download from the Internet<br />
loadSoundFile("cow.wav", "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/")<br />
<br />
-- OR download from the profile<br />
loadSoundFile(getMudletHomeDir().. "/cow.wav")<br />
<br />
-- OR download from the local file system<br />
loadSoundFile("C:/Users/Tamarindo/Documents/cow.wav")<br />
</syntaxhighlight><br />
<br />
==mudletOlderThan==<br />
;mudletOlderThan(major, [minor], [patch])<br />
:Returns true if Mudlet is older than the given version to check. This is useful if you'd like to use a feature that you can't check for easily, such as coroutines support. However, if you'd like to check if a certain function exists, do not use this and use <code>if mudletfunction then</code> - it'll be much more readable and reliable.<br />
<br />
See also: [[#getMudletVersion|getMudletVersion()]]<br />
<br />
;Parameters<br />
* ''major:''<br />
:Mudlet major version to check. Given a Mudlet version 3.0.1, 3 is the major version, second 0 is the minor version, and third 1 is the patch version.<br />
* ''minor:''<br />
:(optional) minor version to check.<br />
* ''patch:''<br />
:(optional) patch version to check.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- stop doing the script of Mudlet is older than 3.2<br />
if mudletOlderThan(3,2) then return end<br />
<br />
-- or older than 2.1.3<br />
if mudletOlderThan(2, 1, 3) then return end<br />
<br />
-- however, if you'd like to check that a certain function is available, like getMousePosition(), do this instead:<br />
if not getMousePosition then return end<br />
<br />
-- if you'd like to check that coroutines are supported, do this instead:<br />
if not mudlet.supportscoroutines then return end<br />
</syntaxhighlight><br />
<br />
==openWebPage==<br />
;openWebPage(URL)<br />
:Opens the browser to the given webpage.<br />
<br />
;Parameters<br />
* ''URL:''<br />
:Exact URL to open.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
openWebPage("http://google.com")<br />
</syntaxhighlight><br />
<br />
Note: This function can be used to open a local file or file folder as well by using "file:///" and the file path instead of "http://".<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
openWebPage("file:///"..getMudletHomeDir().."file.txt")<br />
</syntaxhighlight><br />
<br />
==playMusicFile==<br />
;playMusicFile(settings table)<br />
:Plays music files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|-<br />
| style="text-align:center;"| No<br />
| volume<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| fadein<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
| fadeout<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| start<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
|-<br />
| style="text-align:center;" |No<br />
| loops<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the media to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| continue <br />
| true or false<br />
| true<br />
| style="text-align:left;" |<br />
*Continues playing matching new music files when true.<br />
*Restarts matching new music files when false.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{Note}} on Windows and certain files are not playing? Try installing the 3rd party [https://codecguide.com/download_k-lite_codec_pack_standard.htm K-lite codec pack].<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Play a music file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
})<br />
<br />
-- OR copy once from the game's profile, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile({<br />
name = getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = 75<br />
})<br />
<br />
-- OR copy once from the local file system, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile({<br />
name = "C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = 75<br />
})<br />
<br />
-- OR download once from the Internet, and play music stored in the profile's media directory<br />
---- [fadein] and increase the volume from 1 at the start position to default volume up until the position of 20 seconds<br />
---- [fadeout] and decrease the volume from default volume to one, 53 seconds from the end of the music<br />
---- [start] 10 seconds after position 0 (fadein scales its volume increase over a shorter duration, too)<br />
---- [key] reference of "rugby" for stopping this unique music later<br />
---- [tag] reference of "ambience" to stop and music later with the same tag<br />
---- [continue] playing this music if another request for the same music comes in (false restarts it) <br />
---- [url] to download once from the Internet if the music does not exist in the profile's media directory<br />
playMusicFile({<br />
name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"<br />
, volume = nil -- nil lines are optional, no need to use<br />
, fadein = 20000<br />
, fadeout = 53000<br />
, start = 10000<br />
, loops = nil -- nil lines are optional, no need to use<br />
, key = "rugby"<br />
, tag = "ambience"<br />
, continue = true<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of playMusicFile(name[,volume][,fadein][,fadeout][,loops][,key][,tag][,continue][,url]) ----<br />
<br />
-- Play a music file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
)<br />
<br />
-- OR copy once from the game's profile, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile(<br />
getMudletHomeDir().. "/167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR copy once from the local file system, and play a music file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playMusicFile(<br />
"C:/Users/Tamarindo/Documents/167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR download once from the Internet, and play music stored in the profile's media directory<br />
---- [fadein] and increase the volume from 1 at the start position to default volume up until the position of 20 seconds<br />
---- [fadeout] and decrease the volume from default volume to one, 53 seconds from the end of the music<br />
---- [start] 10 seconds after position 0 (fadein scales its volume increase over a shorter duration, too)<br />
---- [key] reference of "rugby" for stopping this unique music later<br />
---- [tag] reference of "ambience" to stop and music later with the same tag<br />
---- [continue] playing this music if another request for the same music comes in (false restarts it) <br />
---- [url] to download once from the Internet if the music does not exist in the profile's media directory<br />
playMusicFile(<br />
"167124__patricia-mcmillen__rugby-club-in-spain.mp3" -- name<br />
, nil -- volume<br />
, 20000 -- fadein<br />
, 53000 -- fadeout<br />
, 10000 -- start<br />
, nil -- loops<br />
, "rugby" -- key <br />
, "ambience" -- tag<br />
, true -- continue<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/" -- url<br />
)<br />
</syntaxhighlight><br />
<br />
==playSoundFile==<br />
;playSoundFile(settings table)<br />
:Plays sound files from the Internet or the local file system to the "media" folder of the profile for later use with [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! Default<br />
! style="text-align:left;"| Purpose<br />
|- style="color: green;"<br />
| style="text-align:center;"| Yes<br />
| name<br />
| <file name><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
* May contain directory information (i.e. weather/lightning.wav).<br />
* May be part of the profile (i.e. getMudletHomeDir().. "/cow.mp3")<br />
* May be on the local device (i.e. "C:/Users/YourNameHere/Documents/nevergoingtogiveyouup.mp3")<br />
* Wildcards ''*'' and ''?'' may be used within the name to randomize media files selection.<br />
|-<br />
| style="text-align:center;"| No<br />
| volume<br />
| 1 to 100<br />
| 50<br />
| style="text-align:left;"|<br />
* Relative to the volume set on the player's client.<br />
|-<br />
| style="text-align:center;"| No<br />
| fadein<br />
|<msec><br />
|<br />
|<br />
*Volume increases, or fades in, ranged across a linear pattern from one to the volume set with the "volume" key.<br />
*Start position: Start of media.<br />
*End position: Start of media plus the number of milliseconds (msec) specified.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;" |No<br />
| fadeout<br />
|<msec><br />
|<br />
|<br />
*Volume decreases, or fades out, ranged across a linear pattern from the volume set with the "volume" key to one.<br />
*Start position: End of the media minus the number of milliseconds (msec) specified.<br />
*End position: End of the media.<br />
*1000 milliseconds = 1 second.<br />
|-<br />
| style="text-align:center;"| No<br />
| start<br />
| <msec><br />
| 0<br />
| style="text-align:left;"|<br />
* Begin play at the specified position in milliseconds.<br />
|-<br />
| style="text-align:center;" |No<br />
| loops<br />
| -1, or >= 1<br />
|1<br />
| style="text-align:left;" |<br />
*Number of iterations that the media plays.<br />
* A value of -1 allows the media to loop indefinitely.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| priority<br />
| 1 to 100<br />
|&nbsp;<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a lower priority while this media plays.<br />
|- style="color: blue;"<br />
| style="text-align:center;"| Maybe<br />
| url<br />
| <url><br />
| &nbsp;<br />
| style="text-align:left;"|<br />
* Resource location where the media file may be downloaded.<br />
* Only required if the file is to be downloaded remotely.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{Note}} on Windows and certain files are not playing? Try installing the 3rd party [https://codecguide.com/download_k-lite_codec_pack_standard.htm K-lite codec pack].<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Play a sound file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playSoundFile({<br />
name = "cow.wav"<br />
})<br />
<br />
-- OR copy once from the game's profile, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile({<br />
name = getMudletHomeDir().. "/cow.wav"<br />
, volume = 75<br />
})<br />
<br />
-- OR copy once from the local file system, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile({<br />
name = "C:/Users/Tamarindo/Documents/cow.wav"<br />
, volume = 75<br />
})<br />
<br />
-- OR download once from the Internet, and play a sound stored in the profile's media directory<br />
---- [volume] of 75<br />
---- [loops] of 2 (-1 for indefinite repeats, 1+ for finite repeats)<br />
---- [key] reference of "cow" for stopping this unique sound later<br />
---- [tag] reference of "animals" to stop a group of sounds later with the same tag<br />
---- [priority] of 25 (1 to 100, 50 default, a sound with a higher priority would stop this one)<br />
---- [url] to download once from the Internet if the sound does not exist in the profile's media directory<br />
playSoundFile({<br />
name = "cow.wav"<br />
, volume = 75<br />
, fadein = nil -- nil lines are optional, no need to use<br />
, fadeout = nil -- nil lines are optional, no need to use<br />
, start = nil -- nil lines are optional, no need to use<br />
, loops = 2<br />
, key = "cow"<br />
, tag = "animals"<br />
, priority = 25<br />
, url = "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/"<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of playSoundFile(name[,volume][,fadein][,fadeout][,loops][,key][,tag][,priority][,url]) ----<br />
<br />
-- Play a sound file stored in the profile's media directory (i.e. /Users/Tamarindo/mudlet-data/profiles/StickMUD/media)<br />
playSoundFile(<br />
"cow.wav" -- name<br />
)<br />
<br />
-- OR copy once from the game's profile, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile(<br />
getMudletHomeDir().. "/cow.wav" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR copy once from the local file system, and play a sound file stored in the profile's media directory<br />
---- [volume] of 75 (1 to 100)<br />
playSoundFile(<br />
"C:/Users/Tamarindo/Documents/cow.wav" -- name<br />
, 75 -- volume<br />
)<br />
<br />
-- OR download once from the Internet, and play a sound stored in the profile's media directory<br />
---- [volume] of 75<br />
---- [loops] of 2 (-1 for indefinite repeats, 1+ for finite repeats)<br />
---- [key] reference of "cow" for stopping this unique sound later<br />
---- [tag] reference of "animals" to stop a group of sounds later with the same tag<br />
---- [priority] of 25 (1 to 100, 50 default, a sound with a higher priority would stop this one)<br />
---- [url] to download once from the Internet if the sound does not exist in the profile's media directory<br />
playSoundFile(<br />
"cow.wav" -- name<br />
, 75 -- volume<br />
, nil -- fadein<br />
, nil -- fadeout<br />
, nil -- start<br />
, 2 -- loops<br />
, "cow" -- key <br />
, "animals" -- tag<br />
, 25 -- priority<br />
, "https://raw.githubusercontent.com/StickMUD/StickMUDSounds/master/sounds/" -- url<br />
)<br />
</syntaxhighlight><br />
<br />
==purgeMediaCache==<br />
;purgeMediaCache()<br />
: Purge all media file stored in the media cache within a given Mudlet profile (media used with MCMP and MSP protocols). As game developers update the media files on their games, this enables the media folder inside the profile to be cleared so that the media files could be refreshed to the latest update(s).<br />
<br />
;Guidance:<br />
<br />
* Instruct a player to type ''lua purgeMediaCache()'' on the command line, or<br />
* Distribute a trigger, button or other scriptable feature for the given profile to call ''purgeMediaCache()''<br />
<br />
: See also: [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]], [[Manual:Scripting#MUD_Client_Media_Protocol|Scripting MCMP]]<br />
<br />
==receiveMSP==<br />
;receiveMSP(command)<br />
: Receives a well-formed Mud Sound Protocol (MSP) message to be processed by the Mudlet client. Reference the [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]] manual for more information on about what can be sent and example triggers.<br />
<br />
: See also: [[Manual:Supported_Protocols#MSP|Supported Protocols MSP]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Play a cow.wav media file stored in the media folder of the current profile. The sound would play twice at a normal volume.<br />
receiveMSP("!!SOUND(cow.wav L=2 V=50)")<br />
<br />
--Stop any SOUND media files playing stored in the media folder of the current profile.<br />
receiveMSP("!!SOUND(Off)")<br />
<br />
--Play a city.mp3 media file stored in the media folder of the current profile. The music would play once at a low volume.<br />
--The music would continue playing if it was triggered earlier by another room, perhaps in the same area.<br />
receiveMSP([[!!MUSIC(city.mp3 L=1 V=25 C=1)]])<br />
<br />
--Stop any MUSIC media files playing stored in the media folder of the current profile.<br />
receiveMSP("!!MUSIC(Off)")<br />
</syntaxhighlight><br />
<br />
==registerAnonymousEventHandler==<br />
;registerAnonymousEventHandler(event name, functionReference, [one shot])<br />
:Registers a function to an event handler, not requiring you to set one up via script. [[Manual:Event_Engine#Mudlet-raised_events|See here]] for a list of Mudlet-raised events. The function may be refered to either by name as a string containing a global function name, or with the lua function object itself.<br />
<br />
:The optional <code>one shot</code> parameter allows you to automatically kill an event handler after it is done by giving a true value. If the event you waited for did not occur yet, return <code>true</code> from the function to keep it registered.<br />
<br />
:The function returns an ID that can be used in [[Manual:Lua_Functions#killAnonymousEventHandler|killAnonymousEventHandler()]] to unregister the handler again.<br />
<br />
:If you use an asterisk ''("*")'' as the event name, your code will capture all events. Useful for debugging, or integration with external programs.<br />
<br />
{{note}} The ability to refer lua functions directly, the <code>one shot</code> parameter and the returned ID are features of Mudlet 3.5 and above.<br />
<br />
{{note}} The ''"*"'' all-events capture was added in Mudlet 4.10.<br />
<br />
;See also<br />
:[[Manual:Lua_Functions#killAnonymousEventHandler|killAnonymousEventHandler()]], [[Manual:Lua_Functions#raiseEvent|raiseEvent()]], [[Manual:Event_Engine#Mudlet-raised_events|list of Mudlet-raised events]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example taken from the God Wars 2 (http://godwars2.org) Mudlet UI - forces the window to keep to a certain size<br />
function keepStaticSize()<br />
setMainWindowSize(1280,720)<br />
end -- keepStaticSize<br />
<br />
if keepStaticSizeEventHandlerID then killAnonymousEventHandler(keepStaticSizeEventHandlerID) end -- clean up any already registered handlers for this function<br />
keepStatisSizeEventHandlerID = registerAnonymousEventHandler("sysWindowResizeEvent", "keepStaticSize") -- register the event handler and save the ID for later killing<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- simple inventory tracker for GMCP enabled games. This version does not leak any of the methods<br />
-- or tables into the global namespace. If you want to access it, you should export the inventory<br />
-- table via an own namespace.<br />
local inventory = {}<br />
<br />
local function inventoryAdd()<br />
if gmcp.Char.Items.Add.location == "inv" then<br />
inventory[#inventory + 1] = table.deepcopy(gmcp.Char.Items.Add.item)<br />
end<br />
end<br />
if inventoryAddHandlerID then killAnonymousEventHandler(inventoryAddHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryAddHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Add", inventoryAdd) -- register the event handler and save the ID for later killing<br />
<br />
local function inventoryList()<br />
if gmcp.Char.Items.List.location == "inv" then<br />
inventory = table.deepcopy(gmcp.Char.Items.List.items)<br />
end<br />
end<br />
if inventoryListHandlerID then killAnonymousEventHandler(inventoryListHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryListHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.List", inventoryList) -- register the event handler and save the ID for later killing<br />
<br />
local function inventoryUpdate()<br />
if gmcp.Char.Items.Remove.location == "inv" then<br />
local found<br />
local updatedItem = gmcp.Char.Items.Update.item<br />
for index, item in ipairs(inventory) do<br />
if item.id == updatedItem.id then<br />
found = index<br />
break<br />
end<br />
end<br />
if found then<br />
inventory[found] = table.deepcopy(updatedItem)<br />
end<br />
end<br />
end<br />
if inventoryUpdateHandlerID then killAnonymousEventHandler(inventoryUpdateHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryUpdateHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Update", inventoryUpdate)<br />
<br />
local function inventoryRemove()<br />
if gmcp.Char.Items.Remove.location == "inv" then<br />
local found<br />
local removedItem = gmcp.Char.Items.Remove.item<br />
for index, item in ipairs(inventory) do<br />
if item.id == removedItem.id then<br />
found = index<br />
break<br />
end<br />
end<br />
if found then<br />
table.remove(inventory, found)<br />
end<br />
end<br />
end<br />
if inventoryRemoveHandlerID then killAnonymousEventHandler(inventoryRemoveHandlerID) end -- clean up any already registered handlers for this function<br />
inventoryRemoveHandlerID = registerAnonymousEventHandler("gmcp.Char.Items.Remove", inventoryRemove)<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- downloads a package from the internet and kills itself after it is installed.<br />
local saveto = getMudletHomeDir().."/dark-theme-mudlet.zip"<br />
local url = "http://www.mudlet.org/wp-content/files/dark-theme-mudlet.zip"<br />
<br />
if myPackageInstallHandler then killAnonymousEventHandler(myPackageInstallHandler) end<br />
myPackageInstallHandler = registerAnonymousEventHandler(<br />
"sysDownloadDone",<br />
function(_, filename)<br />
if filename ~= saveto then<br />
return true -- keep the event handler since this was not our file<br />
end<br />
installPackage(saveto)<br />
os.remove(b)<br />
end,<br />
true<br />
)<br />
<br />
downloadFile(saveto, url)<br />
cecho("<white>Downloading <green>"..url.."<white> to <green>"..saveto.."\n")<br />
</syntaxhighlight><br />
<br />
==registerNamedEventHandler==<br />
; success = registerNamedEventHandler(userName, handlerName, eventName, functionReference, [oneShot])<br />
<br />
:Registers a named event handler with name handlerName. Named event handlers are protected from duplication and can be stopped and resumed, unlike anonymous event handlers. A separate list is kept per userName<br />
<br />
;See also: [[Manual:Lua_Functions#registerAnonymousEventHandler|registerAnonymousEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]], [[Manual:Lua_Functions#deleteNamedEventHandler|deleteNamedEventHandler()]], [[Manual:Lua_Functions#registerNamedTimer|registerNamedTimer()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler. Used to reference the handler in other functions and prevent duplicates. Recommended you use descriptive names, "hp" is likely to collide with something else, "DemonVitals" less so.<br />
* ''eventName:''<br />
: The name of the event the handler responds to. [[Manual:Event_Engine#Mudlet-raised_events|See here]] for a list of Mudlet-raised events.<br />
* ''functionReference:''<br />
: The function reference to run when the event comes in. Can be the name of a function, "handlerFuncion", or the lua function itself. <br />
* ''oneShot:''<br />
: (optional) if true, the event handler will only fire once when the event is raised. If you need to extend a one shot event handler for "one more check" you can have the handler return true, and it will keep firing until the function does not return true.<br />
<br />
;Returns <br />
* true if successful, otherwise errors.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- register a named event handler. Will call demonVitalsHandler(eventName, ...) when gmcp.Char.Vitals is raised.<br />
local ok = registerNamedEventHandler("Demonnic", "DemonVitals", "gmcp.Char.Vitals", "demonVitalsHandler")<br />
if ok then<br />
cecho("Vitals handler switched to demonVitalsHandler")<br />
end<br />
<br />
-- something changes later, and we want to handle vitals with another function, demonBlackoutHandler()<br />
-- note we do not use "" around demonBlackoutHandler but instead pass the function itself. Both work.<br />
-- using the same handlerName ("DemonVitals") means it will automatically unregister the old handler<br />
-- and reregister it using the new information.<br />
local ok = registerNamedEventHandler("Demonnic", "DemonVitals", "gmcp.Char.Vitals", demonBlackoutHandler)<br />
if ok then<br />
cecho("Vitals handler switched to demonBlackoutHandler")<br />
end<br />
<br />
-- Now you want to check your inventory, but you only want to do it once, so you pass the optional oneShot as true<br />
local function handleInv()<br />
local list = gmcp.Char.Items.List<br />
if list.location ~= "inventory" then<br />
return true -- if list.location is, say "room" then we need to keep responding until it's "inventory"<br />
end<br />
display(list.items) -- you would probably store values and update displays or something, but here I'll just show the data as it comes in<br />
end<br />
<br />
-- you can ignore the response from registerNamedEventHandler if you want, it's always going to be true<br />
-- unless there is an error, in which case it throws the error and halts execution anyway. The return is<br />
-- in part for feedback when using the lua alias or other REPL window.<br />
registerNamedEventHandler("Demonnic", "DemonInvCheck", "gmcp.Char.Items.List", handleInv, true)<br />
</syntaxhighlight><br />
<br />
==reloadModule==<br />
;reloadModule(module name)<br />
:Reload a module (by uninstalling and reinstalling).<br />
<br />
:See also: [[#installModule|installModule()]], [[#uninstallModule|uninstallModule()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
reloadModule("3k-mapper")<br />
</syntaxhighlight><br />
<br />
<br />
==removeFileWatch==<br />
;removeFileWatch(path)<br />
:Remove file watch on directory or file. Every change in that file will no longer raise [[Manual:Event_Engine#sysPathChanged|sysPathChanged]] event.<br />
<br />
:See also: [[#addFileWatch|addFileWatch()]]<br />
<br />
{{MudletVersion|4.12}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
herbs = {}<br />
local herbsPath = getMudletHomeDir() .. "/herbs.lua"<br />
function herbsChangedHandler(_, path)<br />
if path == herbsPath then<br />
table.load(herbsPath, herbs)<br />
removeFileWatch(herbsPath)<br />
end<br />
end<br />
<br />
addFileWatch(herbsPath)<br />
registerAnonymousEventHandler("sysPathChanged", "herbsChangedHandler")<br />
</syntaxhighlight><br />
<br />
==resetProfile==<br />
;resetProfile()<br />
<br />
:Reloads your entire Mudlet profile - as if you've just opened it. All UI elements will be cleared, so this useful when you're coding your UI.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
resetProfile()<br />
</syntaxhighlight><br />
<br />
The function used to require input from the game to work, but as of Mudlet 3.20 that is no longer the case.<br />
<br />
<br />
{{note}} Don't put resetProfile() in the a script-item in the script editor as the script will be reloaded by resetProfile() as well better use <br />
<syntaxhighlight lang="lua"><br />
lua resetProfile()<br />
</syntaxhighlight><br />
in your commandline or make an Alias containing resetProfile().<br />
<br />
==resumeNamedEventHandler==<br />
; success = resumeNamedEventHandler(userName, handlerName)<br />
<br />
:Resumes a named event handler with name handlerName and causes it to start firing once more.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to resume. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local resumed = resumeNamedEventHandler("Demonnic", "DemonVitals")<br />
if resumed then<br />
cecho("DemonVitals resumed!")<br />
else<br />
cecho("DemonVitals doesn't exist, cannot resume it")<br />
end<br />
</syntaxhighlight><br />
<br />
==saveProfile==<br />
;saveProfile(location)<br />
<br />
:Saves the current Mudlet profile to disk, which is equivalent to pressing the "Save Profile" button.<br />
<br />
;Parameters<br />
* ''location:''<br />
:(optional) folder to save the profile to. If not given, the profile will go into the [[Mudlet_File_Locations|default location]].<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
saveProfile()<br />
<br />
-- save to the desktop on Windows:<br />
saveProfile([[C:\Users\yourusername\Desktop]])<br />
</syntaxhighlight><br />
<br />
==sendSocket==<br />
;sendSocket(data)<br />
<br />
:Sends given binary data as-is to the game. You can use this to implement support for a [[Manual:Supported_Protocols#Adding_support_for_a_telnet_protocol|new telnet protocol]], [http://forums.mudlet.org/viewtopic.php?f=5&t=2272 simultronics] [http://forums.mudlet.org/viewtopic.php?f=5&t=2213#p9810 login] or etcetera.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
TN_IAC = 255<br />
TN_WILL = 251<br />
TN_DO = 253<br />
TN_SB = 250<br />
TN_SE = 240<br />
TN_MSDP = 69<br />
<br />
MSDP_VAL = 1<br />
MSDP_VAR = 2<br />
<br />
sendSocket( string.char( TN_IAC, TN_DO, TN_MSDP ) ) -- sends IAC DO MSDP<br />
<br />
--sends: IAC SB MSDP MSDP_VAR "LIST" MSDP_VAL "COMMANDS" IAC SE<br />
local msg = string.char( TN_IAC, TN_SB, TN_MSDP, MSDP_VAR ) .. " LIST " ..string.char( MSDP_VAL ) .. " COMMANDS " .. string.char( TN_IAC, TN_SE )<br />
sendSocket( msg )<br />
</syntaxhighlight><br />
<br />
{{Note}} Remember that should it be necessary to send the byte value of 255 as a ''data'' byte and not as the Telnet '''IAC''' value it is required to repeat it for Telnet to ignore it and not treat it as the latter.<br />
<br />
==setConfig==<br />
; setConfig(option, value)<br />
<br />
:Sets a Mudlet option to a certain value. This comes in handy for scripts that want to customise Mudlet settings to their preferences - for example, setting up mapper room and exit size to one that works for a certain map, or enabling MSDP for a certain game. For transparency reasons, the Debug window (when open) will show which options were modified by scripts.<br />
:To set many options at once, pass in a table of options. More options will be added over time / per request.<br />
<br />
{{MudletVersion|4.16}}<br />
<br />
;Parameters<br />
* ''option:''<br />
: Particular option to change - see list below for available ones.<br />
* ''value:''<br />
: Value to set - can be a boolean, number, or text depending on the option.<br />
<br />
{| class="wikitable sortable"<br />
|+ General options<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| enableGMCP || Enable GMCP (on by default. Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSDP || Enable MSDP (off by default. Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSSP || Enable MSSP (on by default. Reconnect after changing) || 4.16 <br />
|-<br />
| enableMSP || Enable MSP (on by default. Reconnect after changing) || 4.16 <br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Input line<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| inputLineStrictUnixEndings || Workaround option to use strict UNIX line endings for sending commands || 4.16 <br />
|-<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Main display<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| fixUnnecessaryLinebreaks || Remove extra linebreaks from output (mostly for IRE servers) || 4.16 <br />
|-<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Mapper options<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| mapRoomSize || Size of rooms on map (a good value is 5) || 4.16<br />
|-<br />
| mapExitSize || Size of exits on map (a good value is 10) || 4.16<br />
|-<br />
| mapRoundRooms || Draw rooms round or square || 4.16<br />
|-<br />
| showRoomIdsOnMap || Show room IDs on all rooms (if zoom permits) || 4.16<br />
|-<br />
| showMapInfo || Map overlay text ('Full' or 'Short', can have both at once) || 4.16<br />
|-<br />
| hideMapInfo || Map overlay text ('Full' or 'Short', hide both to hide info altogether) || 4.16<br />
|-<br />
| show3dMapView || Show map as 3D || 4.16<br />
|-<br />
| mapperPanelVisible || Map controls at the bottom || 4.16<br />
|-<br />
| mapShowRoomBorders || Draw a thin border for every room || 4.16<br />
|}<br />
<br />
{| class="wikitable sortable"<br />
|+ Special options<br />
|-<br />
! Option !! Description !! Available in Mudlet<br />
|-<br />
| specialForceCompressionOff || Workaround option to disable MCCP compression, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceGAOff || Workaround option to disable Telnet Go-Ahead, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceCharsetNegotiationOff || Workaround option to disable automatically setting the correct encoding, in case the game server is not working correctly || 4.16 <br />
|-<br />
| specialForceMxpNegotiationOff || Workaround option to disable MXP, in case the game server is not working correctly || 4.16 <br />
|-<br />
|}<br />
<br />
;Returns <br />
* true if successful, or nil+msg if the option doesn't exist. Setting mapper options requires the mapper being open first.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setConfig("mapRoomSize", 5)<br />
<br />
setConfig({mapRoomSize = 6, mapExitSize = 12})<br />
</syntaxhighlight><br />
<br />
==setMergeTables==<br />
;setMergeTables(module)<br />
:Makes Mudlet merge the table of the given GMCP or MSDP module instead of overwriting the data. This is useful if the game sends only partial updates which need combining for the full data. By default "Char.Status" is the only merged module.<br />
<br />
;Parameters<br />
* ''module:''<br />
:Name(s) of the GMCP or MSDP module(s) that should be merged as a string - this will add it to the existing list.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setMergeTables("Char.Skills", "Char.Vitals")<br />
</syntaxhighlight><br />
<br />
==setModuleInfo==<br />
;setModuleInfo(moduleName, info, value)<br />
<br />
:Sets a specific meta info value for a module<br />
<br />
;Parameters<br />
* ''moduleName:''<br />
:Name of the module<br />
* ''info:''<br />
: specific info to set (for example "version")<br />
* ''value:''<br />
: specific value to set (for example "1.0")<br />
<br />
:See also: [[#getModuleInfo|getModuleInfo]], [[#setPackageInfo|getPackageInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setModuleInfo("myModule", "version", "1.0")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==setModulePriority==<br />
;setModulePriority(moduleName, priority)<br />
<br />
:Sets the module priority on a given module as a number - the module priority determines the order modules are loaded in, which can be helpful if you have ones dependent on each other. This can also be set from the module manager window.<br />
: Modules with priority <code>-1</code> will be loaded before scripts (Mudlet 4.11+).<br />
<br />
: See also: [[#getModulePriority|getModulePriority()]]<br />
<br />
<syntaxhighlight lang="lua"><br />
setModulePriority("mudlet-mapper", 1)<br />
</syntaxhighlight><br />
<br />
==setPackageInfo==<br />
;setPackageInfo(packageName, info, value)<br />
<br />
:Sets a specific meta info value for a package<br />
<br />
;Parameters<br />
* ''packageName:''<br />
:Name of the module<br />
* ''info:''<br />
: specific info to set (for example "version")<br />
* ''value:''<br />
: specific value to set (for example "1.0")<br />
<br />
:See also: [[#getPackageInfo|getPackageInfo]], [[#setModuleInfo|setModuleInfo]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setPackageInfo("myPackage", "title", "This is my test package")<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.12}}<br />
<br />
==setServerEncoding==<br />
;setServerEncoding(encoding)<br />
:Makes Mudlet use the specified [https://www.w3.org/International/questions/qa-what-is-encoding encoding] for communicating with the game.<br />
<br />
;Parameters<br />
* ''encoding:''<br />
:Encoding to use.<br />
<br />
:See also: [[#getServerEncodingsList|getServerEncodingsList()]], [[#getServerEncoding|getServerEncoding()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- use UTF-8 if Mudlet knows it. Unfortunately there's no way to check if the game's server knows it too.<br />
if table.contains(getServerEncodingsList(), "UTF-8") then<br />
setServerEncoding("UTF-8")<br />
end<br />
</syntaxhighlight><br />
<br />
==showNotification==<br />
;showNotification(title, [content], [expiryTimeInSeconds])<br />
<br />
:Shows a native (system) notification.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
{{Note}} This might not work on all systems, this depends on the system.<br />
<br />
;Parameters<br />
* ''title'' - plain text notification title<br />
* ''content'' - optional argument, plain text notification content, if omitted title argument will be used as content as well<br />
* ''expiryTimeInSeconds'' - optional argument, sets expiration time in seconds for notification, very often ignored by OS<br />
<br />
<syntaxhighlight lang="lua"><br />
showNotification("Notification title", "Notification content", 5)<br />
</syntaxhighlight><br />
<br />
==spawn==<br />
;spawn(readFunction, processToSpawn[, ...arguments])<br />
<br />
:Spawns a process and opens a communicatable link with it - ''read function'' is the function you'd like to use for reading output from the process, and ''t'' is a table containing functions specific to this connection - ''send(data)'', ''true/false = isRunning()'', and ''close()''.<br />
<br />
:This allows you to setup RPC communication with another process.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- simple example on a program that quits right away, but prints whatever it gets using the 'display' function<br />
local f = spawn(display, "ls")<br />
display(f.isRunning())<br />
f.close()<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
local f = spawn(display, "ls", "-la")<br />
display(f.isRunning())<br />
f.close()<br />
</syntaxhighlight><br />
<br />
==startLogging==<br />
;startLogging(state)<br />
<br />
:Control logging of the main console text as text or HTML (as specified by the "Save log files in HTML format instead of plain text" setting on the "General" tab of the "Profile preferences" or "Settings" dialog). Despite being called startLogging it can also stop the process and correctly close the file being created. The file will have an extension of type ".txt" or ".html" as appropriate and the name will be in the form of a date/time "yyyy-MM-dd#hh-mm-ss" using the time/date of when logging started. Note that this control parallels the corresponding icon in the "bottom buttons" for the profile and that button can also start and stop the same logging process and will reflect the state as well.<br />
<br />
;Parameters<br />
* ''state:''<br />
:Required: logging state. Passed as a boolean<br />
<br />
;Returns (4 values)<br />
* ''successful (bool)''<br />
:''true'' if the logging state actually changed; if, for instance, logging was already active and ''true'' was supplied then no change in logging state actually occurred and ''nil'' will be returned (and logging will continue).<br />
* ''message (string)''<br />
:A displayable message given one of four messages depending on the current and previous logging states, this will include the file name except for the case when logging was not taking place and the supplied argument was also ''false''.<br />
* ''fileName (string)''<br />
:The log will be/is being written to the path/file name returned.<br />
* ''code (number)''<br />
:A value indicating the response to the system to this instruction:<br />
* 0 = logging has just stopped<br />
* 1 = logging has just started<br />
* -1 = logging was already in progress so no change in logging state<br />
* -2 = logging was already not in progress so no change in logging state<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- start logging<br />
local success, message, filename, code = startLogging(true)<br />
if code == 1 or code == -1 then print(f"Started logging to {filename}") end<br />
<br />
-- stop logging<br />
startLogging(false)<br />
</syntaxhighlight><br />
<br />
==stopAllNamedEventHandlers==<br />
; stopAllNamedEventHandlers(userName)<br />
<br />
:Stops all named event handlers and prevents them from firing any more. Information is retained and handlers can be resumed.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#stopNamedEventHandler|stopNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameter<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
stopAllNamedEventHandlers() -- emergency stop situation, most likely.<br />
</syntaxhighlight><br />
<br />
==stopMusic==<br />
;stopMusic(settings table)<br />
:Stop all music (no filter), or music that meets a combination of filters (name, key, and tag) intended to be paired with [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|-<br />
| style="text-align:center;"| No<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopSounds|stopSounds()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Stop all playing music files for this profile associated with the API<br />
stopMusic()<br />
<br />
-- Stop playing the rugby mp3 by name<br />
stopMusic({name = "167124__patricia-mcmillen__rugby-club-in-spain.mp3"})<br />
<br />
-- Stop playing the unique sound identified as "rugby"<br />
stopMusic({<br />
name = nil -- nil lines are optional, no need to use<br />
, key = "rugby" -- key<br />
, tag = nil -- nil lines are optional, no need to use<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of stopMusic([name][,key][,tag]) ----<br />
<br />
-- Stop all playing music files for this profile associated with the API<br />
stopMusic()<br />
<br />
-- Stop playing the rugby mp3 by name<br />
stopMusic("167124__patricia-mcmillen__rugby-club-in-spain.mp3")<br />
<br />
-- Stop playing the unique sound identified as "rugby"<br />
stopMusic(<br />
nil -- name<br />
, "rugby" -- key<br />
, nil -- tag<br />
)<br />
</syntaxhighlight><br />
<br />
==stopNamedEventHandler==<br />
; success = stopNamedEventHandler(userName, handlerName)<br />
<br />
:Stops a named event handler with name handlerName and prevents it from firing any more. Information is stored so it can be resumed later if desired.<br />
<br />
;See also: [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]], [[Manual:Lua_Functions#resumeNamedEventHandler|resumeNamedEventHandler()]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
;Parameters<br />
* ''userName:''<br />
: The user name the event handler was registered under.<br />
* ''handlerName:''<br />
: The name of the handler to stop. Same as used when you called [[Manual:Lua_Functions#registerNamedEventHandler|registerNamedEventHandler()]]<br />
<br />
;Returns <br />
* true if successful, false if it didn't exist or was already stopped<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local stopped = stopNamedEventHandler("DemonVitals")<br />
if stopped then<br />
cecho("DemonVitals stopped!")<br />
else<br />
cecho("DemonVitals doesn't exist or already stopped; either way it won't fire any more.")<br />
end<br />
</syntaxhighlight><br />
<br />
==stopSounds==<br />
;stopSounds(settings table)<br />
:Stop all sounds (no filter), or sounds that meets a combination of filters (name, key, tag, and priority) intended to be paired with [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]].<br />
<br />
{| class="wikitable"<br />
! Required<br />
! Key<br />
! Value<br />
! style="text-align:left;"| Purpose<br />
|-<br />
| style="text-align:center;"| No<br />
| name<br />
| <file name><br />
| style="text-align:left;"|<br />
* Name of the media file.<br />
|-<br />
| style="text-align:center;" |No<br />
| key <br />
|<key><br />
| style="text-align:left;" |<br />
*Uniquely identifies media files with a "key" that is bound to their "name" or "url".<br />
*Halts the play of current media files with the same "key" that have a different "name" or "url" while this media plays.<br />
|-<br />
| style="text-align:center;"| No<br />
| tag<br />
| <tag><br />
| style="text-align:left;"|<br />
* Helps categorize media.<br />
|-<br />
| style="text-align:center;" |No<br />
| priority<br />
| 1 to 100<br />
| style="text-align:left;" |<br />
*Halts the play of current or future played media files with a matching or lower priority.<br />
|-<br />
|}<br />
<br />
See also: [[Manual:Miscellaneous_Functions#loadMusicFile|loadMusicFile()]], [[Manual:Miscellaneous_Functions#loadSoundFile|loadSoundFile()]], [[Manual:Miscellaneous_Functions#playMusicFile|playMusicFile()]], [[Manual:Miscellaneous_Functions#playSoundFile|playSoundFile()]], [[Manual:Miscellaneous_Functions#stopMusic|stopMusic()]], [[Manual:Miscellaneous_Functions#purgeMediaCache|purgeMediaCache()]], [[Manual:Scripting#MUD_Client_Media_Protocol|Mud Client Media Protocol]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Example<br />
<br />
<syntaxhighlight lang="lua"><br />
---- Table Parameter Syntax ----<br />
<br />
-- Stop all playing sound files for this profile associated with the API<br />
stopSounds()<br />
<br />
-- Stop playing the cow sound<br />
stopSounds({name = "cow.wav"})<br />
<br />
-- Stop playing any sounds tagged as "animals" with a priority less than or equal to 50<br />
---- This would not stop sounds tagged as "animals" greater than priority 50. This is an "AND" and not an "OR".<br />
stopSounds({<br />
name = nil -- nil lines are optional, no need to use<br />
, key = nil -- nil lines are optional, no need to use<br />
, tag = "animals"<br />
, priority = 50<br />
})<br />
</syntaxhighlight><br />
<syntaxhighlight lang="lua"><br />
---- Ordered Parameter Syntax of stopSounds([name][,key][,tag][,priority]) ----<br />
<br />
-- Stop all playing sound files for this profile associated with the API<br />
stopSounds()<br />
<br />
-- Stop playing the cow sound<br />
stopSounds("cow.wav")<br />
<br />
-- Stop playing any sounds tagged as "animals" with a priority less than or equal to 50<br />
---- This would not stop sounds tagged as "animals" greater than priority 50. This is an "AND" and not an "OR".<br />
stopSounds(<br />
nil -- name<br />
, nil -- key<br />
, "animals" -- tag<br />
, 50 -- priority<br />
)<br />
</syntaxhighlight><br />
<br />
==timeframe==<br />
;timeframe(vname, true_time, nil_time, ...)<br />
<br />
:A utility function that helps you change and track variable states without using a lot of tempTimers.<br />
<br />
{{MudletVersion|3.6}}<br />
<br />
;Parameters<br />
* ''vname:''<br />
:A string or function to use as the variable placeholder.<br />
* ''true_time:''<br />
:Time before setting the variable to true. Can be a number or a table in the format: <code>{time, value}</code><br />
* ''nil_time:''<br />
:(optional) Number of seconds until <code>vname</code> is set back to nil. Leaving it undefined will leave it at whatever it was set to last. Can be a number of a table in the format: <code>{time, value}</code><br />
* ''...:''<br />
:(optional) Further list of times and values to set the variable to, in the following format: <code>{time, value}</code><br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- sets the global 'limiter' variable to true immediately (see the 0) and back to nil in one second (that's the 1).<br />
timeframe("limiter", 0, 1)<br />
<br />
-- An angry variable 'giant' immediately set to "fee", followed every second after by "fi", "fo", and "fum" before being reset to nil at four seconds.<br />
timeframe("giant", {0, "fee"}, 4, {1, "fi"}, {2, "fo"}, {3, "fum"})<br />
<br />
-- sets the local 'width' variable to true immediately and back to nil in one second.<br />
local width<br />
timeframe(function(value) width = value end, 0, 1)<br />
</syntaxhighlight><br />
<br />
==translateTable==<br />
;translateTable(directions, [languagecode])<br />
<br />
:Given a table of directions (such as <code>speedWalkDir</code>), translates directions to another language for you. Right now, it can only translate it into the language of Mudlet's user interface - but [https://github.com/Mudlet/Mudlet/issues/new let us know if you need more].<br />
<br />
{{MudletVersion|3.22}}<br />
<br />
;Parameters<br />
* ''directions:''<br />
:An indexed table of directions (eg. <code>{"sw", "w", "nw", "s"}</code>).<br />
* ''languagecode:''<br />
:(optional) Language code (eg <code>ru_RU</code> or <code>it_IT</code>) - by default, <code>mudlet.translations.interfacelanguage</code> is used.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- get the path from room 2 to room 5 and translate directions<br />
if getPath(2, 5) then<br />
speedWalkDir = translateTable(speedWalkDir)<br />
print("Translated directions:")<br />
display(speedWalkDir)<br />
</syntaxhighlight><br />
<br />
==uninstallModule==<br />
;uninstallModule(name)<br />
<br />
:Uninstalls a Mudlet module with the given name.<br />
<br />
:See also: [[#installModule | installModule()]], [[Manual:Event_Engine#sysLuaUninstallModule | Event: sysLuaUninstallModule]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
uninstallModule("myalias")<br />
</syntaxhighlight><br />
<br />
==uninstallPackage==<br />
;uninstallPackage(name)<br />
<br />
:Uninstalls a Mudlet package with the given name.<br />
<br />
:See also: [[#installPackage | installPackage()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
uninstallPackage("myalias")<br />
</syntaxhighlight><br />
<br />
==unzipAsync==<br />
;unzipAsync(path, location)<br />
<br />
:Unzips the zip file at path, extracting the contents to the location provided. Returns true if it is able to start unzipping, or nil+message if it cannot.<br />
Raises the <code>sysUnzipDone</code> event with the zip file location and location unzipped to as arguments if unzipping is successful, and <code>sysUnzipError</code> with the same arguments if it is not.<br />
<br />
Do not use the <code>unzip()</code> function as it is synchronous and will impact Mudlet's performance (ie, freeze Mudlet while unzipping).<br />
<br />
{{MudletVersion|4.6}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
function handleUnzipEvents(event, ...)<br />
local args = {...}<br />
local zipName = args[1]<br />
local unzipLocation = args[2]<br />
if event == "sysUnzipDone" then<br />
cecho(string.format("<green>Unzip successful! Unzipped %s to %s\n", zipName, unzipLocation))<br />
elseif event == "sysUnzipError" then<br />
cecho(string.format("<firebrick>Unzip failed! Tried to unzip %s to %s\n", zipName, unzipLocation))<br />
end<br />
end<br />
if unzipSuccessHandler then killAnonymousEventHandler(unzipSuccessHandler) end<br />
if unzipFailureHandler then killAnonymousEventHandler(unzipFailureHandler) end<br />
unzipSuccessHandler = registerAnonymousEventHandler("sysUnzipDone", "handleUnzipEvents")<br />
unzipFailureHandler = registerAnonymousEventHandler("sysUnzipError", "handleUnzipEvents")<br />
--use the path to your zip file for this, not mine<br />
local zipFileLocation = "/home/demonnic/Downloads/Junkyard_Orc.zip" <br />
--directory to unzip to, it does not need to exist but you do need to be able to create it<br />
local unzipLocation = "/home/demonnic/Downloads/Junkyard_Orcs" <br />
unzipAsync(zipFileLocation, unzipLocation) -- this will work<br />
unzipAsync(zipFileLocation .. "s", unzipLocation) --demonstrate error, will happen first because unzipping takes time</syntaxhighlight><br />
<br />
==yajl.to_string==<br />
;yajl.to_string(data)<br />
<br />
:Encodes a Lua table into JSON data and returns it as a string. This function is very efficient - if you need to encode into JSON, use this.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- on IRE MUD games, you can send a GMCP request to request the skills in a particular skillset. Here's an example:<br />
sendGMCP("Char.Skills.Get "..yajl.to_string{group = "combat"})<br />
<br />
-- you can also use it to convert a Lua table into a string, so you can, for example, store it as room's userdata<br />
local toserialize = yajl.to_string(continents)<br />
setRoomUserData(1, "areaContinents", toserialize)<br />
</syntaxhighlight><br />
<br />
<br />
==yajl.to_value==<br />
;yajl.to_value(data)<br />
<br />
:Decodes JSON data (as a string) into a Lua table. This function is very efficient - if you need to dencode into JSON, use this.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- given the serialization example above with yajl.to_string, you can deserialize room userdata back into a table<br />
local tmp = getRoomUserData(1, "areaContinents")<br />
if tmp == "" then return end<br />
<br />
local continents = yajl.to_value(tmp)<br />
display(continents)<br />
</syntaxhighlight><br />
<br />
[[Category:Mudlet Manual]]<br />
[[Category:Mudlet API]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Geyser&diff=20309Manual:Geyser2023-02-09T09:57:15Z<p>Kebap: /* Geyser elements */ Move manual to own headline to make it easier to find</p>
<hr />
<div>{{TOC right}}<br />
<br />
= Introduction =<br />
<br />
The Geyser Layout Manager is an object oriented framework for creating, updating and organizing GUI elements within Mudlet - it allows you to make your UI easier on Mudlet, and makes it easier for the UI to be compatible with different screen sizes.<br />
<br />
=== Motivation ===<br />
<br />
Mudlet makes the creation of label, miniconsoles and gauges a quick and easy thing. Mudlet provides a nice signal when window resize events happen. To help with complex window management, Geyser steps in.<br />
<br />
=== Main Geyser Features ===<br />
<br />
Geyser is based on traditional GUI concepts and should feel similar to using Java's Swing. The biggest difference is in how positions are specified.<br />
<br />
* All window positions are specified relative to their container - nothing new there. However, window positions can also take on percentages and negative pixel and character values. For instance, a window could be constrained to have a height of 50% of its container and a width such that the window's right edge is always 20 characters from its container's right edge. See examples below and the demos/tests that come with Geyser.<br />
* All windows under Geyser control are automatically resized as necessary when the main Mudlet window is resized. Once you create a window and assign it to a container, you never have to worry about positioning it again. Nonetheless, it's very easy to shift the container that a window is in, maintaining its constraints so that it resizes as needed according to the dimensions of the new container.<br />
* Due to the container hierarchy, hiding a container window automatically hides all its contained windows too. The same for show. With clever construction and labels with callbacks, this lets one make complex GUI elements that are minimizable or maximizable or ...<br />
* However, there is always some overhead for automation systems and Geyser is no exception. Fortunately, most of the overhead is during window creation and resize events - not things that happen frequently.<br />
<br />
=== Getting pictures for your stuff ===<br />
You can find good, freely-available assets for your UI here:<br />
* [https://kenney.nl/assets?q=2d kenney.nl]<br />
* [https://opengameart.org/ opengameart.org]<br />
* [https://game-icons.net/ game-icons.net]<br />
<br />
=== Constraints format ===<br />
<br />
Geyser position constraints are a string composed of a number and a format type. For example, "10px" means 10 pixels, either pixels from the origin (e.g. x or y) or a value for the width or height. A negative number indicates distance from a container's right or bottom border depending on whether is a constraint for x/width or y/height, respectively. Percentages for width and height are in terms of the container's dimensions and negative values are converted to the equivalent positive value. A 100% width subwindow with an x-coordinate of 10 will have part of itself displayed outside the confines of its container. There is no hard limit on maximum window size, just as with regular Mudlet windows. If a number, n, is passed as a constraint instead of a string, it is assumed to be equivalent to "npx". Any Lua table that contains entries for x, y, width and height in the proper format can be used for Geyser constructors and setting constraints. Just like in Mudlet, 0,0 coordinates mean the top-left corner.<br />
<br />
The following is a valid example for coordinates of a Geyser object:<br />
<br />
<syntaxhighlight lang="lua"><br />
{x = "20px", y = "-10c", width = "40%", height = 30}<br />
</syntaxhighlight><br />
<br />
=== Math in Geyser ===<br />
You can also use math in your Geyser constraints just to line things up just right! Want to have a label occupy full height but not the first 30 pixels? You can:<br />
<br />
<syntaxhighlight lang="lua"><br />
footer = Geyser.Label:new({<br />
name = "footer",<br />
x = 0, y = 30,<br />
width = "100%-30px",<br />
}, main_window)<br />
</syntaxhighlight><br />
<br />
= Geyser elements =<br />
The purpose of this document is to go through every Geyser element and provide practical examples on how they are used. Read it from top to bottom, preferably doing all of the examples to understand how they work!<br />
<br />
== Technical manual ==<br />
<br />
See https://www.mudlet.org/geyser/files/index.html for a brief and technical overview of all Geyser elements and their functions.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html Geyser.Container]==<br />
An invisible, organizing object in Geyser - use it to divide your screen and position elements accordingly. '''[http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html See here]''' for all of the functions that are available to you to use.<br />
<br />
A container is also the base class - which means that everything (labels, miniconsoles and gauges) can use its functions, since everything else is at heart a container.<br />
<br />
=== Creating a container ===<br />
To get started with a container, here's an example that'll create a 200px border on the left side of Mudlet for you, and make a container cover all of it - so you can place other visual elements inside it:<br />
<br />
<syntaxhighlight lang="lua"><br />
setBorderLeft(200)<br />
left_container = Geyser.Container:new({<br />
name = "left_container", -- give it a unique name here<br />
x=0, y=0, -- have it start at the top-left corner of mudlet<br />
width = 200, height="100%", -- with a width of 200, and a height of the full screen, hence 100%<br />
})<br />
</syntaxhighlight><br />
<br />
Right away, you'll see space appear on the left side. It'll be black, as the container is an invisible unit by itself. You can make sure it's there by making it flash by doing this from the input line:<br />
<br />
<syntaxhighlight lang="lua">lua left_container:flash()</syntaxhighlight><br />
<br />
The command will cause your container to flash for a moment for you, revealing itself.<br />
<br />
{{Note}} If you hide a container and create new Geyser elements within it, they'll be shown automatically for you.<br />
<br />
=== Container within a container ===<br />
You can place containers within other containers by specifying which "parent" the new container should have when you create one. Given our [[#Creating a container|previous example]], you can split the left side into two halves like this:<br />
<br />
<syntaxhighlight lang="lua"><br />
left_container_top = Geyser.Container:new({<br />
name = "left_container_top",<br />
x=0, y=0, -- this container occupies the top, so it starts top-left as well<br />
width = "100%", height="50%", -- but only uses up half of the height<br />
}, left_container) -- this is the important bit - it says that left_container_top should be inside left_container<br />
<br />
left_container_bottom = Geyser.Container:new({<br />
name = "left_container_bottom",<br />
x=0, y="50%", -- this container starts halfway down the first one<br />
width = "100%", height="50%", -- and has the same half height of the original container<br />
}, left_container) <br />
</syntaxhighlight><br />
<br />
=== Aligning relative to bottom or right sides ===<br />
The aligning point within Mudlet is the top-left corner, and it's the same for the elements they are aligned - the position you specify is used by the top-left corner of the element.<br />
<br />
Using Geyser, you can align to the opposite side as well, using the coordinates in negatives, while keeping the dimensions of the object in mind. For example, if you want to align a box that's 20px wide on the usual left side, you'd give it a width of 20 and an x value of 0. If you'd like to align it on the right side, then you'd give it an x value of -20. The box will spawn 20px away from the right side and "grow" to the right by 20px.<br />
<br />
<syntaxhighlight lang="lua"><br />
right_container = Geyser.Container:new({<br />
name = "right_container",<br />
x="-20%", y=0, -- makes the container start 20% of the screen away from the right side<br />
width = "20%", height="50%", -- filling it up until the end<br />
}) <br />
</syntaxhighlight><br />
<br />
Do make sure to account for the scrollbar, as Mudlet UI elements can overlap it. You can also move the scrollbar with [[Manual:UI_Functions#setBorderRight|setBorderRight()]].<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html Geyser.Label]==<br />
Labels allow you to use pictures in your interface, as well as nicely-formatted text - see docs for label [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html functions].<br />
<br />
=== Basic label ===<br />
<br />
Here's an example to get you started with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
</syntaxhighlight><br />
<br />
This labels '''x''' coordinate is specified as 50% - and because it's not attached to any container, this implies that the window will start halfway at the main window. You can tell it's not attached to a container because there's nothing in between the last ''}'' and '')'', the place where the container goes.<br />
<br />
The '''y''' coordinate is 0 - which means that the label will start at the top of the screen. With the width being 50%, the label will occupy 50% of the screen - and since it starts at the halfway point, it means it'll occupy the entire right side. A height of 100% means that it'll stretch from the top to the full bottom.<br />
<br />
Here's what that'll look like:<br />
<br />
[[File:Simple-label.png|center|600px]]<br />
<br />
<br />
Playing around with the starting location and dimensions, we can also place it in the center of the screen with:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
})<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
[[File:Simple_label_centered.png|center|600px]]<br />
<br />
To change the message on a label, you can use the ''mylabel:echo()'' function, where ''mylabel'' is the name of the label you gave it:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("hello!")<br />
</syntaxhighlight><br />
<br />
To get rid of the label, use the '':hide()'' function:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:hide()<br />
</syntaxhighlight><br />
<br />
=== Coloring text ===<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black", -- default text colour<br />
color = "SeaGreen" -- default label background<br />
})<br />
<br />
-- You can also change colour of text on demand with:<br />
testlabel:echo[[<p style="color:blue;">You can change the text color of a whole sentence or paragraph...</p><p>...or you can change the text color of one <span style="color:green;">word</span> or even a single l<span style="color:red;">e</span>tter.</p>]]<br />
</syntaxhighlight><br />
<br />
=== Setting the font size ===<br />
<br />
To set a different font size for your Label, use the ''setFontSize()'' method. For example:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel:setFontSize(14)<br />
</syntaxhighlight><br />
<br />
The font size is set in Pt, so anything above 30 will likely be too large to be useful.<br />
<br />
=== Label inside a container ===<br />
<br />
Once you've got your containers and mastered the basic labels, you can drop labels into your nicely-organized containers. Doing so is similar to nesting containers:<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "25%", y = "25%",<br />
width = "50%", height = "50%",<br />
fgColor = "black",<br />
message = [[<center>heey</center>]]<br />
}, left_container_bottom) -- this is where we tell it what container to go into<br />
testlabel:setColor(0,255,0,150)<br />
</syntaxhighlight><br />
<br />
That label is exactly the same as the one above that goes across the screen, except it's in our bottom-left container - so it looks appropriately different:<br />
<br />
[[File:Label in a container.png|center]]<br />
<br />
=== Image on a label ===<br />
One of the more amazing things labels allow you to do is put pictures anywhere on your Mudlet screen, that blend in very well. To do so, once the label is created, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setBackgroundImage setBackgroundImage()] function with the exact path to the image ([[File:Skullface.png]]):<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 0, y = "-14px",<br />
width = "16px", height = "14px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/skullface.png]]) -- update location to actual image location on your computer<br />
</syntaxhighlight><br />
<br />
This'll plop the picture to the bottom-left of your screen. To make the picture show, download the skullface picture above - save it to your desktop, and adjust the location of the image within [[]]'s to what it is on your computer. For example, if you saved this on your Windows 7 desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[C:/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
(yes, that's / and not \ - \ has been known not to work)<br />
<br />
If you saved this on your Mac desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/Users/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
If you saved this on your Ubuntu desktop, it would be:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label:setBackgroundImage([[/home/<your user name>/Desktop/skullface.png]])<br />
</syntaxhighlight><br />
<br />
Using this basic building block, you can work up to making yourself a UI!<br />
<br />
=== Stretching an image on a label ===<br />
If you'd like your image not to keep its original size, but instead use up the available space of the label - you can use the [http://doc.qt.io/qt-5/stylesheet-reference.html#border-image border-image] stylesheet property to do so.<br />
<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- change the location to your picture<br />
-- on windows, use / to separate folders still, not \<br />
label:setStyleSheet[[<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);<br />
]]<br />
</syntaxhighlight><br />
<br />
{{note}} If you're on a Mudlet earlier than 3.15 and are having difficulty with the image coming up, it may be because of strange differences between Qt's CSS engine which does not affect mudlet's Lua. You may want to try appending :gsub("\\","/") to your string including getMudletHomeDir() (e.g. <code>getMudletHomeDir():gsub("\\","/")</code>). No longer necessary after Mudlet 3.15.<br />
<br />
=== Aligning an image within a label ===<br />
You can use background-image in combination with background-position to align an image within a label (if, say, the image is much smaller than the label).<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this will set and align an image top-right of the label<br />
if stunning then<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-ok.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
else<br />
mylabel:setStyleSheet([[<br />
background-image: url("/home/vadi/Games/Mudlet/Offensive/Artwork/dialog-no.png");<br />
background-repeat: no-repeat; background-position: top right; background-origin: margin;<br />
]])<br />
end<br />
</syntaxhighlight><br />
<br />
=== Showing / hiding a label ===<br />
You can show and hide labels, as you can any container, miniconsole or a gauge in Geyser with [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:show Geyser.Container:show()] and [http://www.mudlet.org/geyser/files/geyser/GeyserContainer.html#Geyser.Container:hide Geyser.Container:hide()]. Remember that since labels are a type of a container, all container functions work on them.<br />
<br />
Hiding a label will allow you to click through on what is below the label, as well as free up the visual space for something else.<br />
<br />
<syntaxhighlight lang="lua"><br />
testlabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- hide the label with:<br />
testlabel:hide()<br />
<br />
-- show the label with:<br />
testlabel:show()<br />
</syntaxhighlight><br />
<br />
=== Clickable images ===<br />
Tacking onto the fact that you can plop images anywhere on your Mudlet screen now, you can also make them react to your clicks. You can do so with the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setClickCallback setClickCallback()] function - by giving it a function to call when your label is clicked, you'll make it react.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "-215px", y = "0px",<br />
width = "200px", height = "200px",<br />
})<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/qubodup-opengameart-cc0-200px-missile_icon.png]]) -- update location to actual image location on your computer<br />
picture_label:setClickCallback("on_bomb_press")<br />
<br />
function on_bomb_press()<br />
send("say BOOM!")<br />
end<br />
</syntaxhighlight><br />
<br />
That's it! Pressing on the image will make the ''on_bomb_press()'' function go off, which will do its code of ''send("say BOOM!")''. Download the picture for use [http://opengameart.org/content/missile-rts-icon here].<br />
<br />
[[File:Clickable_image.png|500px|center]]<br />
<br />
=== Styling labels ===<br />
Besides putting text or images on labels, you can also style them using Qt's stylesheets feature. Doing so allows you to create various graphics that make the label look more appealing:<br />
<br />
[[File:Label_styling_examples.png|center]]<br />
<br />
To set a stylesheet on a label, use the [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:setStyleSheet Geyser.Label:setStyleSheet()] function on your label, describing the stylesheet you'd like to give it. A stylesheet consists of properties you set - for example the background color, borders, padding, and so forth. You describe properties in the following format: ''property name''''':'''''values''''';'''. See here for a [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties list of all supported properties]. For example, to make your labels background be yellow, you'd use the background-color property:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "mylabel",<br />
x = "50%", y = "50%",<br />
width = 200, height = 100<br />
})<br />
<br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet.png|center]]<br />
<br />
Which is nice, but not particularly impressive.<br />
<br />
Scrolling down the list of properties, you'll come along a border one. Plopping it into our stylesheet nets the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: yellow;<br />
border: 5px solid white;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border.png|center]]<br />
<br />
Which gives a border!<br />
<br />
Fiddling with it some more and applying new properties we find on that page, we get a rounded border on our label:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background-color: grey;<br />
border-width: 15px;<br />
border-style: solid;<br />
border-color: green;<br />
border-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
<br />
[[File:Basic_stylesheet_border_radius.png|center]]<br />
<br />
Which'll conclude our exploration for now. Try out all of the other possible options available there - there's loads, from [http://doc.qt.io/qt-5/stylesheet-reference.html#border-style funky borders], to tiling images and fancy color combinations using gradients.<br />
<br />
You should also check out [[Manual:Geyser#Geyser.StyleSheet|Geyser.StyleSheet]] for a way to manage your stylesheets with adjustable properties and the ability to take defaults from another stylesheet.<br />
<br />
=== Adding a tooltip to a label ===<br />
<br />
Since Mudlet 4.6, you can now add a tooltip to labels and gauges. You can start by making a simple label and echoing some text to it:<br />
<br />
<syntaxhighlight lang="lua"><br />
testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = "50%",<br />
y = "50%",<br />
height = "25%",<br />
width = "25%",<br />
})<br />
testLabel:echo("This is on the label!")<br />
testLabel:setAlignment("center")<br />
-- sets the tooltip text<br />
testLabel:setToolTip("This is the tooltip", "10")<br />
<br />
<br />
-- optionally - you can customise the tooltip, too!<br />
testLabel:setStyleSheet("QToolTip{background: yellow; color: blue; border:none;}")<br />
</syntaxhighlight><br />
<br />
Without tooltip<br />
[[File:TestLabelForTooltips.png|thumb|center]]<br />
<br />
With tooltip<br />
<br />
[[File:LabelTooltip.png|thumb|center]]<br />
<br />
=== Avoid stylesheet inheritance by tooltip ===<br />
<br />
{{note}} If you set a new stylesheet for a label and with that a background image it is possible that through inheritance the tooltip also has this stylesheet image.<br />
<br />
To avoid this specify that the stylesheet is meant for the Label by using QLabel{...} in your Label stylesheet for exampleː<br />
<syntaxhighlight lang="lua"><br />
label = Geyser.Label:new({<br />
name = "label",<br />
x = "50%", y = "50%",<br />
width = "50%", height = "50%",<br />
})<br />
<br />
-- by using QLabel{...} the stylesheet won't be given to the tooltip as well<br />
label:setStyleSheet[[<br />
QLabel{<br />
border-image: url(/home/vadi/Desktop/iso-avatar-draft_0.png);}<br />
]]<br />
</syntaxhighlight><br />
<br />
<br />
=== Aligning text/images inside a label ===<br />
By default, text is [http://qt-project.org/doc/qt-5/qlabel.html#alignment-prop centered vertically and left aligned] in a label. To align it to a specific side, use the stylesheets we learnt about earlier with the qproperty-alignment:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel = Geyser.Label:new({<br />
name = "testlabel",<br />
x = "50%", y = 0,<br />
width = "50%", height = "100%",<br />
fgColor = "black",<br />
color = "SeaGreen",<br />
message = [[<center>heey</center>]]<br />
})<br />
<br />
-- specify one property this way:<br />
mylabel:setStyleSheet([[qproperty-alignment: 'AlignTop';]])<br />
<br />
-- or multiple ones separated with a |, for example this will align text to top-left:<br />
mylabel:setStyleSheet([[<br />
qproperty-alignment: 'AlignLeft | AlignTop';<br />
]])<br />
<br />
mylabel:echo("hi!")<br />
</syntaxhighlight><br />
<br />
[[File:Text_aligned.png|center]]<br />
<br />
=== Enabling wordwrap in a label ===<br />
If you need to enable word wrapping in a label (which by default is off), add the following line to the labels stylesheet:<br />
<br />
qproperty-wordWrap: true;<br />
<br />
As an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
If you'd like to set multiple properties, set them all at once - not via multiple :setStyleSheet() calls:<br />
<br />
<syntaxhighlight lang="lua"><br />
mylabel:setStyleSheet([[<br />
background: red;<br />
qproperty-wordWrap: true;<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Adding a hover effect to a label ===<br />
The labels support adding stylesheets for specific cases, such as when a mouse is [http://doc.qt.io/qt-5/stylesheet-reference.html#hover-ps hovering] over them. To make this work, you provide CSS for when the label is in its usual state, and for when it is hovered over:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this example will add a border to the label when it is hovered over<br />
mylabell:setStyleSheet([[<br />
QLabel{ border-radius: 4px; }<br />
QLabel::hover{<br />
background-color: rgba(0,0,0,0%);<br />
border: 4px double green;<br />
border-radius: 4px;<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Checkboxes ===<br />
Combining the fact that you can click on a label with an image to do something with the fact that you can change pictures on a label at will, you can make an image that changes itself when you click on it.<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = "50%", y = "50%",<br />
width = "21px", height = "19px"<br />
})<br />
-- a little trick we do to make the background of the label be transparent<br />
picture_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
picture_label:setClickCallback("on_checkbox_press")<br />
<br />
function on_checkbox_press()<br />
if checkbox_ticked then<br />
checkbox_ticked = false<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_unticked.png]])<br />
echo("Checkbox unticked.\n")<br />
else<br />
checkbox_ticked = true<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/checkbox_ticked.png]])<br />
echo("Checkbox TICKED!\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
The ''on_checkbox_press()'' function this time keeps the track of the checkbox with the ''checkbox_ticked'' variable and sets the image appropriately. You can download the ticked ([[File:Checkbox_ticked.png]]) and unticked images ([[File:Checkbox_unticked.png]]) or the [http://wiki.mudlet.org/images/6/6d/Checkbox.mpackage whole package] altogether.<br />
<br />
[[File:Checkbox_demo.png|500px|center]]<br />
<br />
=== Animated labels with sprites ===<br />
You can animate sprite packs using timers. Assuming you have the sprite pack downloaded, try this example:<br />
<br />
<syntaxhighlight lang="lua"><br />
picture_label = Geyser.Label:new({<br />
name = "picture_label",<br />
x = 10, y = "-24px",<br />
width = "16px", height = "14px",<br />
})<br />
<br />
santa_counter = nil<br />
<br />
function animate_santa()<br />
santa_counter = (santa_counter or 0) + 1<br />
if santa_counter > 8 then santa_counter = 1 end<br />
<br />
picture_label:setBackgroundImage([[/home/vadi/Desktop/santa/santa]]..santa_counter..[[.png]]) -- update location to actual image location on your computer<br />
santa_timer = tempTimer(.16, animate_santa)<br />
end<br />
<br />
animate_santa()<br />
</syntaxhighlight><br />
<br />
The completed package is available [http://wiki.mudlet.org/images/6/6b/Dancing-santa.mpackage here], install it and do '''start/end animation''' to watch.<br />
<br />
=== Inserting extra spaces and newlines ===<br />
Echoing text into Mudlet and Geyser labels is different from miniconsoles and the main window, due to their nature. One of the differences is that extra spaces in a label, by default, get compressed down to one. '''To add extra spaces in a label''', replace extra spaces with '''&amp;nbsp;''' or by wrapping your text with them inside '''<nowiki><pre>my text here</pre></nowiki>'''.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- this won't work, it'll show as one space:<br />
mylabel:echo("You -> point")<br />
<br />
-- but this would, because it replaces all spaces with &nbsp before echoing<br />
mylabel:echo(string.gsub("You -> point", " ", "&nbsp;"))<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- here is another way to go about this - and it additionally makes the font be monospaced:<br />
mylabel:echo("<pre>You -> point</pre>")<br />
</syntaxhighlight><br />
<br />
'''To add a new line in a label''' (aka linebreak), use '''<nowiki><br></nowiki>''' (instead of ''\n'' as you are used to in an echo).<br />
<syntaxhighlight lang="lua"><br />
mylabel:echo("These<br>words<br>are<br>split")<br />
</syntaxhighlight><br />
<br />
=== Transparent labels ===<br />
One of the possible ways of achieving transparency on a label is to add <code>background-color: rgba(0,0,0,0%);</code> to its stylesheet. Here's an example:<br />
<br />
<syntaxhighlight lang="lua"><br />
my_transparent_label:setStyleSheet([[<br />
background-color: rgba(0,0,0,0%);<br />
]])<br />
</syntaxhighlight><br />
<br />
Want to get transparency in a miniconsole? You can [[Manual:Geyser#Change_your_miniconsole_background_image|do that as well]].<br />
<br />
=== Custom mouse cursor ===<br />
You can change the shape of the cursor when it's over your label with:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCursor("Forbidden") -- will change your mouse cursor to "forbidden" (as in "can't do this") cursor<br />
</syntaxhighlight><br />
Possible cursor shapes are [[CursorShapes| available here]], and you can import this [[Media:Cursor grid.zip|demo package]] to try them all out.<br />
<br />
It is also possible to change the mouse cursor to a custom made cursor by:<br />
<syntaxhighlight lang="lua"><br />
mylabel:setCustomCursor(getMudletHomeDir().."/custom_cursor.png")<br />
</syntaxhighlight><br />
It is recommended that the custom cursor is a png with size of 32x32 to be supported on all systems.<br />
<br />
[[File:Changecursoroverlabel.gif]]<br />
<br />
{{Note}} Available in Mudlet 4.8+<br />
<br />
=== Flyout Labels ===<br />
<br />
Flyout labels allow you to create 'dropdown' or 'flyout' menus - menus that reveal more items once you hover your mouse over them. To create flyout labels:<br />
# add <code>nestable=true</code> (left click to open menu) or <code>nestflyout=true</code> (mouse hover to open menu) to your main label.<br />
# use [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] on your main label to add flyout labels to it.<br />
## [http://www.mudlet.org/geyser/files/geyser/GeyserLabel.html#Geyser.Label:addChild :addChild()] uses the same arguments as when creating a new label but also takes the '''layoutDir''' option to specify in which direction and axis should the labels align, where 2 letters combine into the option: first letter R for right, L for left, T for top, B for bottom, followed by the orientation: V for vertical or H for horizontal. So options are: <code>layoutDir="RV"</code>, <code>layoutDir="RH"</code>, <code>layoutDir="LV"</code>, <code>layoutDir="LH"</code>, and so on.<br />
# optionally, add <code>flyOut=true</code> to your flyout labels to make the labels dissapear when the mouse isn't hovering over them anymore.<br />
<br />
Note that the main flyout label cannot go into a container and needs to be on its own.<br />
<br />
{{note}} Requires Mudlet 3.0.<br />
<br />
==== Demo ====<br />
Here's an example that follows the steps above:<br />
<br />
<syntaxhighlight lang="lua"><br />
label0 = Geyser.Label:new({name="label0", <br />
x="50%",y="50%",height=50,width=300,nestable=true, <br />
message="<center>Clicky clicky</center>"})<br />
<br />
-- and add 3 labels to it with RV layout - so Right of the label, aligned Vertically<br />
label1 = label0:addChild({name="label1",height=30,width=70, layoutDir="RV", flyOut=true, message="label one"})<br />
label1:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label2 = label0:addChild({name="label2",height=30,width=70, layoutDir="RV", flyOut=true, message="label two"}) <br />
label2:setStyleSheet([[background-color: green; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
<br />
label3 = label0:addChild({name="label3",height=30,width=70, layoutDir="RV", flyOut=true, message="label three"})<br />
label3:setStyleSheet([[background-color: red; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px; font-size: 7pt;]])<br />
</syntaxhighlight><br />
<br />
A more thorough example. Try it out to see what you can create with flyout labels:<br />
<syntaxhighlight lang="lua"><br />
-- create a label with a nestable=true property to say that it can nest labels<br />
mainlabel = Geyser.Label:new({name="testa", x=400,y=50,height=50,width=300,nestflyout=true, message="<center>HOVER HERE TO SEE FLY-OUT LABELS!</center>"})<br />
<br />
-- create 15 labels and store them in a table <br />
table_for_flyout_labels = {}<br />
for i=1,15 do<br />
-- options to layoutDir are the direction the window should go (R for right, L for left, T for top, B for bottom), followed by how the nested labels should be oriented (V for vertical or H for horizontal). So "BH" here means it'll go on the bottom of the label, while expanding horizontally<br />
table_for_flyout_labels[i] = mainlabel:addChild({name="test"..tostring(i),height=30,width=70, layoutDir="BH", flyOut=true, message="test"..tostring(i)})<br />
<br />
table_for_flyout_labels[i]:setStyleSheet([[background-color: purple; border-width: 2px; border-style: solid; border-color: blue; border-radius: 2px;]])<br />
end<br />
<br />
-- make the test5 label look a bit special as it has got a surprise<br />
table_for_flyout_labels[5]:echo("Hover here")<br />
<br />
-- add even more nested labels to the 5th label!<br />
even_more_flyout_labels = {}<br />
for i=1,60 do<br />
-- here, the layout will be to the right of it, while expanding vertically<br />
even_more_flyout_labels[i]=table_for_flyout_labels[5]:addChild({name="hover label "..tostring(i),height=30,width=100, layoutDir="RV", flyOut=true, message="label "..tostring(i)})<br />
even_more_flyout_labels[i]:setClickCallback("testFunc", even_more_flyout_labels[i].name)<br />
even_more_flyout_labels[i]:setStyleSheet([[background-color: grey; border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]])<br />
end<br />
<br />
function testFunc(name)<br />
display(name)<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look something like this: <br />
<br />
[[File:Flyout_labels_demo.png|150px]]<br />
<br />
==== Demo of layouts ====<br />
Here's another demo that explains all of the layout styles quite well:<br />
<syntaxhighlight lang="lua"><br />
local directions = {"R", "L", "T", "B"}<br />
local orientations = {"V", "H"}<br />
local mappings = {R = "right", L = "left", T = "top", B = "bottom", V = "vertical", H = "horizontal"}<br />
<br />
local combinations, combination_labels = {}, {}<br />
for _, direction in pairs(directions) do<br />
for _, orientation in pairs(orientations) do<br />
combinations[#combinations+1] = direction..orientation<br />
end<br />
end<br />
<br />
local function get_foreground_text_colour(r,g,b)<br />
local luminosity = (0.2126 * ((r/255)^2.2)) + (0.7152 * ((g/255)^2.2)) + (0.0722 * ((b /255)^2.2))<br />
if luminosity > 0.5 then<br />
return "black"<br />
else<br />
return "white"<br />
end<br />
end<br />
<br />
local function get_random_colour_rgb()<br />
return math.random(1,255), math.random(1,255), math.random(1,255)<br />
end<br />
<br />
-- create a label with a nestable=true property to say that it can nest labels<br />
all_possible_combinations_label = Geyser.Label:new({name="all_possible_combinations_label", x=0,y="-400",height=50,width=500,<br />
nestable = true, message="<center>Click to see a listing of possible combinations</center>"})<br />
<br />
for i = 1, #combinations do<br />
local combination = combinations[i]<br />
combination_labels[i] = all_possible_combinations_label:addChild({name="combo_"..combination,height=30,width=150, nestable = true, flyOut=true, layoutDir="BH", message="<center>Combination "..combination.."</center>"})<br />
<br />
local r,g,b = get_random_colour_rgb()<br />
local text_colour = get_foreground_text_colour(r,g,b)<br />
<br />
local combination_labels_children = {}<br />
for ii = 1, 3 do<br />
combination_labels_children[ii] = combination_labels[i]:addChild({<br />
name="combo_"..combination.."_"..ii, height = 30, width = 150, layoutDir=combination, flyOut = true,<br />
message = string.format("<center><b>%s</b>%s+<b>%s</b>%s layout</center>", <br />
combination:sub(1,1), mappings[combination:sub(1,1)]:sub(2), combination:sub(2,2), mappings[combination:sub(2,2)]:sub(2)),<br />
fgColor = text_colour})<br />
<br />
combination_labels_children[ii]:setStyleSheet(string.format([[background-color:rgb(%d, %d, %d); border-width: 2px; border-style: solid; border-color: green; border-width: 2px; font-size: 7pt;]], r,g,b))<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
It'll look like this:<br />
<br />
[[File:Flyoutlabels-layout-demo.png]]<br />
<br />
=== Geyser.Label right click menu ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
You can create a right click menu for a label just by using the function (assuming your label name is 'myLabel'):<br />
<syntaxhighlight lang="lua"> myLabelːcreateRightClickMenu({MenuItems = menuTable}) -- scroll down for a fuller example with more details </syntaxhighlight><br />
<br />
The menu table comprises of all the items and their names. To create a parent menu just create a nested table of names.<br />
<br />
Example of a menuTable:<br />
<syntaxhighlight lang="lua"> menuTable = {"First Item", "Second Item (Parent)", {"First ChildItem", "Second ChildItem"}, "Third Item"} </syntaxhighlight><br />
<br />
The menu would look like thisː<br />
<br />
[[File:RCDemo1.gif|250px]]<br />
<br />
You can give more constraints to further style and enhance your right click menu.<br />
<br />
==== Style your right click menu ====<br />
Your right click menu has 2 default styles integratedː "light" and "dark" which are defined by the constraint "Style".<br />
<br />
To set a default style just give the constraint Style the preferred value, for exampleː<br />
<syntaxhighlight lang="lua"> Style = "dark" </syntaxhighlight><br />
<br />
To give different levels of your menu different style just add the number of the level to the constraint, for exampleː<br />
<syntaxhighlight lang="lua"> Style2 = "light" -- Gives the second level of your menu the "light" style</syntaxhighlight><br />
<br />
For adding your own stylesheet use the constraint MenuStyle (use the same method as above to define stylesheets for different levels)<br />
<syntaxhighlight lang="lua"> MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]] <br />
-- Gives the second level of your menu this stylesheet</syntaxhighlight><br />
<br />
The same methods are used for defining the format, width and height for the menu item.<br />
<syntaxhighlight lang="lua"> <br />
MenuWidth = 70 -- standard menu width if nothing else is given<br />
MenuWidth2 = 80 -- menu width for the second level <br />
MenuFormat1 = "c10" -- menu format for the first level (format works like any other label echo format, in this case c is center and 10 is the font-size)<br />
MenuHeight = 30<br />
</syntaxhighlight><br />
<br />
==== Set onClick action for your menu item ====<br />
To set an action if your menu item is clicked use the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<syntaxhighlight lang="lua"> <br />
myLabelːsetMenuAction("First Item", function() echo("Clicked on the first item\n") end<br />
myLabelːsetMenuAction("Second Item (Parent).First ChildItem", function() echo("Clicked on the first child item\n") end) -- To set an action to a child item find it by using "Parent.Child" as name (only one parent is needed to be given the parents parent is not needed)<br />
</syntaxhighlight><br />
<br />
==== Access an menu item directly ====<br />
The simplest way to access a menu item directly is by just using the function (assuming your label name is 'myLabel' and using the same MenuItems as defined above)<br />
<br />
For example to change the menu item textː<br />
<syntaxhighlight lang="lua"> <br />
myLabelːfindMenuElement("First Item"):echo([[my first Item]])<br />
</syntaxhighlight><br />
<br />
==== Right click menu example ====<br />
Better then any further explanation is probably this practical example. <br />
<br />
<syntaxhighlight lang="lua"> <br />
-- create the label the right click menu will be in<br />
myRightClickLabel = myRightClickLabel or Geyser.Label:new({<br />
name = "myRightClickLabel", message = "Please right click!", <br />
format = "cb15", x=10, y=10, width ="30%", height = "15%", <br />
color = "purple"})<br />
<br />
-- right click menu creation with custom styleheet on level2 and default "Dark" style <br />
myRightClickLabel:createRightClickMenu({<br />
MenuItems = {"Emergency", "Drink",{"ManaPotion","HealthPotion"}, "Disappear", "Cast",{"Blindness", "Blink"}}, <br />
Style = "Dark", <br />
MenuWidth2 = 80, <br />
MenuFormat1 = "c10",<br />
MenuStyle2 = [[QLabel::hover{ background-color: rgba(0,255,150,100%); color: white;} QLabel::!hover{color: brown; background-color: rgba(100,240,240,100%);} ]]<br />
})<br />
<br />
myRightClickLabel:setMenuAction("Emergency", function() <br />
cecho("<red:pink>[Emergency Mode] Run as fast as possible!\n") <br />
send("emergency") <br />
closeAllLevels(myRightClickLabel) -- this can be used to close the right click menu if clicked on this item<br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.ManaPotion", function()<br />
cecho("<blue>Drinking my mana potion.\n") <br />
send("drink mp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Drink.HealthPotion", function() <br />
cecho("<red>Drinking my health potion.\n") <br />
send("drink hp") <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Disappear", function() <br />
cecho("<grey>Disappearing.. \n") <br />
send("disappear") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blindness", function() <br />
cecho("<light_blue>Casting blindness \n") <br />
send("cast blindness enemy") <br />
closeAllLevels(myRightClickLabel) <br />
end )<br />
<br />
myRightClickLabel:setMenuAction("Cast.Blink", function() <br />
cecho("<light_blue>Casting blink \n") <br />
send("cast blink") <br />
end )<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
<br />
[[File:Right click example demo.gif]]<br />
<br />
==== Add right click menu to label with already existing left click action ====<br />
If your label has an already existing left click action you'll have to create the right click menu<br />
"before" creating the labels "setClickCallBack" action and then just put into your labels onClick function<br />
(assuming your label name is 'myLabel' and 'event' is the last parameter of your onClick function)<br />
<br />
<syntaxhighlight lang="lua"> <br />
myLabel:onRightClick(event)<br />
</syntaxhighlight><br />
<br />
=== Geyser name ===<br />
Make sure to give your Geyser Labels, miniconsoles, and userwindows a <code>name</code> - while it'll technically work without one, items will be duplicated when you re-save them if they're lacking a name.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserStyleSheet.html Geyser.StyleSheet]==<br />
<br />
Allows you to create a managed stylesheet to make it easier to set and change properties. Also allows you to inherit properties from another stylesheet, making it easier to manage multiple styles at once.<br />
<br />
=== Basic Usage ===<br />
<br />
Here's an example to get you started. This creates a basic stylesheet to set the background color black and the foreground/text color to green, then applies it to a Geyser Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
local testLabel = Geyser.Label:new({<br />
name = "testLabel",<br />
x = 100,<br />
y = 100,<br />
height = 100,<br />
width = 300,<br />
stylesheet = stylesheet:getCSS(),<br />
})<br />
<br />
-- Alternate method of creating a stylesheet using a table of properties<br />
local stylesheet = Geyser.StyleSheet:new({<br />
['background-color'] = "black",<br />
['color'] = "green",<br />
})<br />
</syntaxhighlight><br />
<br />
=== Getting the CSS string === <br />
<br />
As shown above, you can use getCSS to get the stylesheet as a string.<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getCSS())<br />
--[[<br />
"background-color: black;\ncolor: green;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Including a target ===<br />
<br />
You can include a 'target' for your stylesheet to be applied to, such as QLabel, QPlainTextEdit, etc.<br />
<br />
<syntaxhighlight lang="lua"><br />
-- QPlainTextEdit is useful for styling command lines in particular, to keep the style from bleeding into any associated miniconsole or userwindow.<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
QPlainTextEdit {<br />
background-color: black;<br />
color: green;<br />
}]])<br />
<br />
-- or as an optional third argument. Passing nil for the parent explicitly <br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]], nil, "QPlainTextEdit")<br />
<br />
-- or using the setTarget function after the fact<br />
local stylesheet = Geyser.StyleSheet:new([[<br />
background-color: black;<br />
color: green;<br />
]])<br />
stylesheet:setTarget("QPlainTextEdit")<br />
</syntaxhighlight><br />
<br />
=== Changing a property ===<br />
<br />
Assuming you started with the example above, if you wanted to change the background color to purple you would do the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("background-color", "purple")<br />
testLabel:setStyleSheet(stylesheet:getCSS())<br />
</syntaxhighlight><br />
<br />
Or if you wanted to set the font, you would do:<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", [["Ubuntu Mono"]])<br />
</syntaxhighlight><br />
<br />
Note the way we set the font with the double quotes included in the string, this is because the quotes have to be there in the final stylesheet. You could use single quotes instead of the bracket notation as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:set("font", '"Ubuntu Mono"')<br />
</syntaxhighlight><br />
<br />
=== Getting the value of a property ===<br />
<br />
Again assuming you started with the example code above it's as easy as<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:get("color") -- will return "green"<br />
</syntaxhighlight><br />
<br />
=== Getting a table of properties and their values ===<br />
<br />
<syntaxhighlight lang="lua"><br />
display(stylesheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
</syntaxhighlight><br />
<br />
=== Setting the properties via table ===<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setStyleTable({<br />
["background-color"] = "purple",<br />
color = "green",<br />
font = '"Ubuntu Mono"',<br />
})<br />
</syntaxhighlight><br />
<br />
=== Resetting the style with a string ===<br />
<br />
Creating a new Geyser.StyleSheet would break any inheritance for stylesheets which had this one as a parent (see below), so if you wish to reset the style via CSS string you should use :setCSS<br />
<br />
<syntaxhighlight lang="lua"><br />
stylesheet:setCSS([[<br />
background-color: black;<br />
color: green;<br />
font: "Ubuntu Mono";<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Inheriting properties ===<br />
<br />
As with most things Geyser, just pass the parent in when you create the new stylesheet<br />
<br />
<syntaxhighlight lang="lua"><br />
local childsheet = Geyser.StyleSheet:new("color: blue;", stylesheet)<br />
display(childsheet:getStyleTable())<br />
--[[<br />
{<br />
["background-color"] = "purple",<br />
color = "blue",<br />
font = '"Ubuntu Mono"'<br />
}<br />
--]]<br />
<br />
display(childsheet:get("background-color")<br />
--"purple"<br />
<br />
-- show only properties set in this stylesheet, without inheritance<br />
display(childsheet:getStyleTable(false))<br />
--[[<br />
{<br />
color = "blue"<br />
}<br />
--]]<br />
<br />
-- can do the same for the CSS string<br />
display(childsheet:getCSS(false))<br />
--[[<br />
"color: blue;"<br />
--]]<br />
</syntaxhighlight><br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html Geyser.MiniConsole]==<br />
This allows you to spawn a Mudlet miniconsole - unlike labels, these aren't as styleable, but they do format text better. They make a good fit for text-based menus, chat and map capture, and other things.<br />
<br />
Spawning one is very similar to other Geyser elements - paste this into a new script:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x="70%", y="50%",<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="30%", height="50%",<br />
})<br />
</syntaxhighlight><br />
<br />
This'll make you one at the bottom-right of the screen. The miniconsole will have a grey background by default, but you can set it to any color you'd like with [http://www.mudlet.org/geyser/files/geyser/GeyserWindow.html#Geyser.Window:setColor miniconsole:setColor()]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setColor("black") -- give it a nice black background<br />
</syntaxhighlight><br />
<br />
A special dimension property that MiniConsoles have is a character - instead of specifying a miniconsole to be % of a container or a certain number of pixels, you can specify it as a certain number of characters. You do this by using "c" at the end of a number. This way, you can, for example, specify miniconsole to be 10 letters long and 2 lines high:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="70%", y="50%",<br />
wrapAt = 10,<br />
width="10c", height="2c",<br />
})<br />
flatbox:setColor("red")<br />
flatbox:echo("ABCDEFGHIJ") -- that is 10 letters<br />
</syntaxhighlight><br />
<br />
=== Adding text ===<br />
You can use [[Manual:Technical_Manual#echo|echo()]] the same way with a miniconsole to add text as to the usual window:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("hello!")<br />
</syntaxhighlight><br />
<br />
As well as [[Manual:Technical_Manual#cecho|cecho]], [[Manual:Technical_Manual#decho|decho]], or [[Manual:Technical_Manual#hecho|hecho]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:cecho("<green>hey, <blue>colored <red>text!\n")<br />
</syntaxhighlight><br />
<br />
=== Copying lines with color ===<br />
To copy a line over to the miniconsole, as it is from the game with all colors preserved, you can [[Manual:UI_Functions#selectCurrentLine|select]], [[Manual:UI_Functions#copy|copy]], and [[Manual:UI_Functions#appendBuffer|append]] it. For an example, try making a trigger with this as the ''perl regex'' pattern type:<br />
<br />
<syntaxhighlight lang="lua"><br />
^<br />
</syntaxhighlight><br />
<br />
That'll make the trigger go off on every line. Then give it the following script (assumed you have made the HelloWorld miniconsole from earlier):<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
... and you'll see all MUD output duplicated exactly as it is to the miniconsole. Amazing! It's very efficient as well, so you can have many miniconsoles, even in spam, not lag you down.<br />
<br />
=== Clearing the miniconsole ===<br />
Clearing the miniconsole just requires using the following script (assumes you have made the HelloWorld miniconsole from earlier):<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:clear()<br />
</syntaxhighlight><br />
<br />
=== Doing edits in copied lines ===<br />
Sometimes you'll want to edit the line before stuffing it into the miniconsole. For example, if you're making a chat capture, you'd want to condense a really long org name into something that's more space-friendly.<br />
<br />
To do so, you'd use the [[Manual:Technical_Manual#selectString|selectString()]] the text you'd like to modify, [[Manual:Technical_Manual#replace|replace()]] it with a different one:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectString("Your", 1) -- select the word you'd like to replace - in this case, 'Your'<br />
setBgColor(getBgColor()) -- preserve the background color in the replacement<br />
setFgColor(getFgColor()) -- preserve the foreground color in the replacement<br />
replace("Mine") -- replace the selection with the wird 'Mine'<br />
<br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
</syntaxhighlight><br />
<br />
=== Gagging from the main window ===<br />
If you'd like to gag the line from the main window so it only shows up in your miniconsole, [[Manual:Technical_Manual#deleteLine|delete]] it after moving it over:<br />
<br />
<syntaxhighlight lang="lua"><br />
selectCurrentLine()<br />
copy()<br />
HelloWorld:appendBuffer()<br />
deleteLine()<br />
</syntaxhighlight><br />
<br />
=== Clickable menus ===<br />
Using the [[Manual:Technical_Manual#echoLink|echoLink]], [[Manual:Technical_Manual#insertLink|insertLink]] and [[Manual:Technical_Manual#setLink|setLink]] functions, you can turn text into one that reacts on a click. Combined with your power of placing text anywhere on the screen with a miniconsole, you can make menus with options. Here is one such example, where selecting an item causes an echo to happen:<br />
<br />
<syntaxhighlight lang="lua"><br />
flatbox = Geyser.MiniConsole:new({<br />
name="flatbox",<br />
x="20%", y="80%",<br />
width="40c", height="4c",<br />
})<br />
flatbox:setColor("red")<br />
clearWindow("flatbox")<br />
<br />
flatbox:cecho("<white:red>Choose one of the following options:\n")<br />
<br />
flatbox:fg("white")<br />
flatbox:bg("red")<br />
<br />
for _, fruit in ipairs{"banana", "apple", "orange"} do<br />
echoLink("flatbox", "* "..fruit:title().."\n", [[echo("You picked ]]..fruit..[[\n")]], "The "..fruit.." option", true)<br />
end<br />
<br />
resetFormat()<br />
</syntaxhighlight><br />
<br />
This will produce something like the following:<br />
<br />
[[File:Fruit_menu.png|center]]<br />
<br />
=== Change your miniconsole background image ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
To set a custom background image for your miniconsole, use [https://www.mudlet.org/geyser/files/geyser/GeyserMiniConsole.html#Geyser.MiniConsole:setBackgroundImage :setBackgroundImage()]:<br />
<syntaxhighlight lang="lua"><br />
miniconsole_withBgImg = Geyser.MiniConsole:new({name = "BackgroundonConsole", x="50%", y="50%", width = "20%", height = "40%"})<br />
miniconsole_withBgImg:setBackgroundImage(":/Mudlet_splashscreen_development.png", "center")<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:decho("<:0,0,0,130> This is a decho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 6 do<br />
miniconsole_withBgImg:hecho("#,80000000 This is a hecho test with semi-transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:decho("<:0,0,0> This is a decho test with no transparent background\n")<br />
end<br />
<br />
for i = 1, 2 do<br />
miniconsole_withBgImg:hecho("#,000000 This is a hecho test with no transparent background\n")<br />
end<br />
</syntaxhighlight><br />
<br />
=== Enable and use your miniconsole command line ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Every miniconsole has a hidden command line. Enable it with:<br />
<syntaxhighlight lang="lua"><br />
HelloWorldContainer = HelloWorldContainer or Adjustable.Container:new({name="HelloWorldContainer", titleText = "Container with a command line"})<br />
<br />
HelloWorld = Geyser.MiniConsole:new({<br />
name="HelloWorld",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "purple",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, HelloWorldContainer)<br />
<br />
HelloWorld:enableCommandLine()<br />
</syntaxhighlight><br />
<br />
=== Set an action to your miniconsole command line ===<br />
If no action is set to your miniconsole command line the commands are send to the game the same way as for the main command line. Aliases still work as usual, and if you have command echo enabled in preferences, it'll show in both miniconsole and the main window.<br />
<br />
It is also possible to set an action to your command line, this enables you to use the command line as custom text input.<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:enableCommandLine()<br />
local function channelChat(text)<br />
send("chat "..text)<br />
HelloWorld:echo("[chat] " ..text.."\n")<br />
end<br />
<br />
HelloWorld:setCmdAction(channelChat)<br />
</syntaxhighlight><br />
<br />
This will send your miniconsole command line input to the chat channel.<br />
<br />
More complicated/sophisticated actions are possible, setCmdAction works the same way as the Label clickCallback functions - that is, you can pass arguments to it.<br />
<br />
==[http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html Geyser.Gauge]==<br />
<!--<br />
This is a composite window. Gauge duplicates the functionality of the built in Mudlet gauges, but in a clean and easily extended way. Internally, a Geyser Gauge is a container holding two Labels, front and back, which are initially scaled to fill the entire Gauge container. Hence, a gauge, g, can be given callbacks with the g.front:setClickCallback() method.<br />
<br />
The backgroundColor parameter initially sets the colors of the gauge, but of course the front and back components can be accessed individually as labels for high control over their looks. Gauges can be horizontal or vertical and decrease in value left to right, right to left, down up or up down depending on the value of the orientation parameter.<br />
--><br />
<br />
A Gauge allows you to represent numbers on a scale - and most typically, you've seen it be used as your standard hp/mana/whatever bar. A basic bar is made similarly to other Geyser elements. To set the value on the gauge that it should represent, use the [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] function:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="5%",<br />
})<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
That'll spawn you a pretty basic gauge with a horizontal orientation and a grey colour - and as a test, with a random value.<br />
<br />
[[File:Basic_gauge.png|center]]<br />
<br />
=== Updating a gauge ===<br />
You'd want your gauge to stay in sync with your actual values. To make that happen, you want to call [http://www.mudlet.org/geyser/files/geyser/GeyserGauge.html#Geyser.Gauge:setValue setValue()] whenever the value that the gauge is tracking changes.<br />
<br />
So for example, if you make a health bar - wherever you get your new health at (be it prompt, gmcp, atcp or whatever), update the gauge as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- theoretical example<br />
current_health, max_health = tonumber(matches[2]), tonumber(matches[3])<br />
<br />
-- update the bar<br />
hp_bar:setValue(current_health, max_health)<br />
</syntaxhighlight><br />
<br />
You can also write down how much health have you got on the bar with:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local hp = math.random(1,100) <br />
hpbar:setValue(current_health, max_health, "<b>"..max_health.."hp</b>")<br />
<br />
-- example using GMCP in IRE games:<br />
hpbar:setValue((100/gmcp.Char.Vitals.maxhp)*gmcp.Char.Vitals.hp,100,gmcp.Char.Vitals.hp)<br />
</syntaxhighlight><br />
<br />
[[File:Hpbar_basic.png|center]]<br />
<br />
=== Styling a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. Combining this with Geyser:Label.setStyleSheet, you can improve the visuals of your gauges by using Qt-supported CSS. The syntax for specifying CSS is a bit different - it requires a semicolon after every property, and is done in the format of ''property name''''':'''''values''''';'''. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here] and you can use [https://build-system.fman.io/qt-designer-download Qt Designer] to create them. Practical example:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #98f041, stop: 0.1 #8cf029, stop: 0.49 #66cc00, stop: 0.5 #52a300, stop: 1 #66cc00);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #78bd33, stop: 0.1 #6ebd20, stop: 0.49 #4c9900, stop: 0.5 #387000, stop: 1 #4c9900);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;<br />
]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge.png|center]]<br />
<br />
The same style can be adjusted by colors to red as well:<br />
<br />
<syntaxhighlight lang="lua"><br />
hpbar = Geyser.Gauge:new({<br />
name="hpbar",<br />
x="50%", y="85%",<br />
width="45%", height="20px",<br />
})<br />
hpbar.front:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #f04141, stop: 0.1 #ef2929, stop: 0.49 #cc0000, stop: 0.5 #a40000, stop: 1 #cc0000);<br />
border-top: 1px black solid;<br />
border-left: 1px black solid;<br />
border-bottom: 1px black solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
hpbar.back:setStyleSheet([[background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #bd3333, stop: 0.1 #bd2020, stop: 0.49 #990000, stop: 0.5 #700000, stop: 1 #990000);<br />
border-width: 1px;<br />
border-color: black;<br />
border-style: solid;<br />
border-radius: 7;<br />
padding: 3px;]])<br />
<br />
hpbar:setValue(math.random(1,100),100)<br />
</syntaxhighlight><br />
<br />
[[File:Fancy_Geyser_gauge_red.png|center]]<br />
<br />
=== Updating a gauge ===<br />
The Geyser gauge is composed of three labels - one is called ''mygauge.front'', ''mygauge.back'' and ''mygauge.text''. To make a gauge clickable you can set a ClickCallBack on the top label which is ''mygauge.text'' example: <syntaxhighlight lang="lua">mygauge.text:setClickCallback("functionName", variableToSendToFunctionName)</syntaxhighlight><br><br />
If you would like to have different click events for the top or back of a gauge you can enable clickThrough for the top or ''mygauge.text'' label example<br />
<br />
<syntaxhighlight lang="lua"><br />
mygauge.text:enableClickthrough()<br />
mygauge.front:setClickCallback("functionOne", variableToSendToFunctionOne)<br />
mygauge.back:setClickCallback("functionTwo", variableToSendToFunctionTwo)<br />
</syntaxhighlight><br />
<br />
<br />
=== Tooltips on gauges ===<br />
Tooltips are available since Mudlet 4.6 as explained in above section [[#Adding_a_tooltip_to_a_label]], and as gauges are really only made up of labels as well, you could add a tooltip then by just using <syntaxhighlight lang="lua">mygauge.text:setToolTip("This is the gauge's tooltip", "10")</syntaxhighlight> the same as it's handled for clickback.<br />
<br />
== HBox/VBox ==<br />
<br />
These are special types of containers. Every window in these is horizontally or vertically aligned in the order they were added.<br />
<br />
<sub>Added to Mudlet in 2.0-rc4</sub><br />
<br />
== Geyser.UserWindow ==<br />
Allows you to use Mudlets UserWindows within Geyser, which allows you to use all the functionality of a MiniConsole in its basic form.<br />
The big advantage is the possibility to add other Geyser Elements like Labels, MiniConsole, Gauges, Mappers to the UserWindow.<br />
The UserWindow then can act as container for those elements with all the perks of dynamic resizing or any other Geyser functionality.<br />
<br />
{{note}} available in Mudlet 4.6.1+<br />
<br />
===Basic floating userwindow ===<br />
This will create a movable floating userwindow.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "TestUserWindow",<br />
titleText ="My Test UserWindow", -- only available since Mudlet 4.8+<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
</syntaxhighlight><br />
<br />
You can change the title of the userwindow by using the parameger titleText and the functions below (as of Mudlet 4.8+)ː<br />
<br />
To set a new title after creation useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setTitle("My new title Text")<br />
</syntaxhighlight><br />
<br />
To revert to the standard title useː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:resetTitle()<br />
</syntaxhighlight><br />
<br />
To '''save the position''' of the userwindow - say in case you've dragged it onto another monitor and would like it to stay there when you restart Mudlet - use [[Manual:UI_Functions#saveWindowLayout|saveWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
saveWindowLayout()<br />
</syntaxhighlight><br />
<br />
To restore it afterwards, use [[Manual:UI_Functions#loadWindowLayout|loadWindowLayout()]]:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- create your userwindows first with Geyser.UserWindow:new<br />
-- then restore them to the positions they were at:<br />
loadWindowLayout()<br />
</syntaxhighlight><br />
<br />
=== Docked UserWindow ===<br />
To create the window docked at the right side,<br />
set the variable docked (at creation of the container) to true.<br />
Be aware that with this variable set to true the position and the size at creation of the userwindow will be ignored.<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true<br />
<br />
})<br />
</syntaxhighlight><br />
<br />
Since Mudlet 4.8+ it is also possible to choose the docking Position of the UserWindow at creation and by function withː<br />
<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "DockedTestUserWindow",<br />
docked = true,<br />
dockPosition = "top" -- Possible dockPositions are left "l", right "r", top "t", bottom "b" and floating "f" <br />
})<br />
</syntaxhighlight><br />
<br />
To change it for a already created UserWindow use the function setDockPosition(dockPosition) likeː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:setDockPosition("left")<br />
</syntaxhighlight><br />
<br />
=== Disable/enable UserWindow autoDock ===<br />
{{note}} available in Mudlet 4.8+<br />
<br />
The auto docking feature can be really annoying at times. To disable it use the functionsː<br />
<syntaxhighlight lang="lua"><br />
testuserwindow:disableAutoDock() -- disables autoDock. Docking still possible with ːsetDockPosition<br />
testuserwindow:enableAutoDock() -- reenables autoDock<br />
</syntaxhighlight><br />
<br />
=== Styling the UserWindow border and title area ===<br />
{{note}} available in Mudlet 4.10+ and Linux only<br />
<br />
Geyser.UserWindows can accept a stylesheet to change the appearance of the border and title area and make<br />
the UserWindow look more appealing. This unfortunately only works in Linux, as in macOS and Windows, it is the OS theme that is used here. <br />
<br />
<syntaxhighlight lang="lua"><br />
myUserWindow = myUserWindow or Geyser.UserWindow:new({<br />
name = "myUserWindow", titleText = "myUserWindow", autoDock = false<br />
})<br />
<br />
myUserWindow:setStyleSheet( <br />
[[QDockWidget{<br />
border: 1px solid green; /* UserWindow border style */<br />
font: bold 15pt "Arial"; /* Font of the titleBar */<br />
color: rgb(0,0,150); /* Font color */<br />
}<br />
<br />
QDockWidget::title{ <br />
background-color: rgb(0,255,150); /* TitleBar color */<br />
border: 2px solid red; /* TitleBar border */<br />
border-radius: 2px; /* TitleBar border radius */<br />
text-align: center; /* alignment of the titleText */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
This looks likeː<br />
<br />
[[File:UserWindowStyleSheet.png]]<br />
<br />
=== UserWindow as Container ===<br />
This is the feature which shows the versatile nature of Geyser.UserWindows.<br />
The UserWindow act as container and is at that possible to dynamically resize the containing Geyser Elments.<br />
Put a label in the UserWindow resize it as rectangle.<br />
<syntaxhighlight lang="lua"><br />
testuserwindow = Geyser.UserWindow:new({<br />
name = "ParentTestUserWindow",<br />
x = "20%", y="20%",<br />
width="30%", height ="40%"<br />
})<br />
<br />
testuserwindow:setColor("dark_green") -- give the userwindow a bit of color <br />
<br />
labelinuserw = Geyser.Label:new({<br />
name = "LabelinUserWindow",<br />
x=20, y=20,<br />
width = -20, height = -20,<br />
color="light_blue", fontSize=20,<br />
},testuserwindow)<br />
<br />
labelinuserw:echo("This is a label in an userwindow", "black", "c")<br />
</syntaxhighlight><br />
[[File:LabelInUserWindow.png]]<br />
<br />
The same way you are able to add your favorite Geyser Application (like tabbed chat, animated timers, gauges) to an UserWindow.<br />
<br />
Note that you don't need to add MiniConsoles to a UserWindow - as UserWindows already have them built-in.<br />
<br />
[[File:Tabbedchatinuserwindow.png]]<br />
<br />
== Geyser.CommandLine ==<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Allows you to create your custom command lines which can resize/move like any other Geyser object.<br />
<br />
If you just need a command line which is integrated in a miniconsole or userwindow, check out [[Manual:Geyser#Enable and use your miniconsole command line|:enableCommandLine()]].<br />
<br />
=== Creating a Geyser.CommandLine ===<br />
An example to get you startedː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine = myCommandLine or Geyser.CommandLine:new({<br />
name = "myCommandLine", <br />
x = "-20%", y = -40, <br />
width = "20%", height = 40,<br />
stylesheet = "border: 1px solid silver;"<br />
})<br />
</syntaxhighlight><br />
This creates a new command line in the right bottom of your screen.<br />
<br />
=== Bind action to your command line input ===<br />
If you use your previously created command line, any command will just be send to the game, after having been checked for aliases.<br />
<br />
To react to any input in a custom manner, we can set an action to the command line and use the input as parameter.<br />
<br />
Example of a command line changing the background color of your main console (assumes you have created "myCommandLine" from earlier): <br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setAction(<br />
function(commandLineInput)<br />
r, g, b = Geyser.Color.parse(commandLineInput) -- gets the r, g, b values of the color you input to the command line<br />
if b then -- checks if the color is valid<br />
setBackgroundColor(r, g, b)<br />
else<br />
echo("\n"..commandLineInput.." is not a valid color. Try again.")<br />
end<br />
end)<br />
</syntaxhighlight><br />
<br />
=== Styling a command line ===<br />
You can style your Geyser command line by using Qt-supported CSS. A list of all possible properties you can use is [http://doc.qt.io/qt-5/stylesheet-reference.html#list-of-properties available here].<br />
<br />
Practical example (assuming "myCommandLine" is created)ː<br />
<syntaxhighlight lang="lua"><br />
myCommandLine:setStyleSheet([[<br />
QPlainTextEdit{ /* QPlainTextEdit is used to prevent the styleSheet bleeding to the right click menu*/<br />
border: 1px solid silver; /* Command line border style */<br />
background-color: rgb(0,255,150); /* Command line background color */<br />
font: bold 12pt "Arial"; /* Font and font-size of your command line */<br />
color: rgb(0,0,150); /* Command line text color */<br />
}<br />
]])<br />
</syntaxhighlight><br />
<br />
=== Create an extra command line in Mudlet ===<br />
If your goal is to just have an extra command/input line - say, for role-playing purposes: copy/paste the example below into a new script in Mudletː<br />
<br />
<syntaxhighlight lang="lua"><br />
inputContainer = inputContainer or Adjustable.Container:new({<br />
x = 0, y = "-4c", <br />
name = "InputContainer", padding = 2, <br />
width = "100%", height = "4c", <br />
autoLoad = false<br />
})<br />
<br />
extraCmdLine = extraCmdLine or Geyser.CommandLine:new({<br />
name = "extraCmdLine", <br />
x = 0, y = 0, width = "100%", height = "100%"<br />
}, inputContainer)<br />
<br />
inputContainer:attachToBorder("bottom")<br />
</syntaxhighlight><br />
<br />
This will look likeː <br />
<br />
[[File:AdditionalCommandLine.png|extra command line]]<br />
<br />
== Adjustable.Container ==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
Adjustable Containers are a new "GeyserClass" which act as containers for Geyser elements, but with more flexible and user configurable features. They are referred to as "adjustable" because they can be minimized, loaded, saved, moved, adjusted in size with the mouse pointer, and attached to borders. <br />
<br />
A brief video of [https://www.youtube.com/watch?v=GT2ScizuM48&feature=youtu.be Introduction to Adjustable Containers] is available.<br />
<br />
=== Creating an Adjustable.Container ===<br />
An Adjustable.Container is created just like any other Geyser Object. For example, we might experiment with creating a new Adjustable.Container by running the following line of lua code:<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
</syntaxhighlight><br />
This will create a new Adjustable.Container with the name ''testContainer''. Specifying the adjustable container's name is important for saving. Defining a variable, such as ''testCon'' in our above example, allows functions to be used with the Adjustable.Container.<br />
<br />
Our newly created Adjustable.Container may be used the same way as any other Geyser.Container might. For example, let's put a Geyser.Label in our new testContainer:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon = testCon or Adjustable.Container:new({name="testContainer"})<br />
testLabel = Geyser.Label:new({name="myTestLabel", x=0, y=0, height="100%", width="100%", color="green"},testCon)<br />
</syntaxhighlight><br />
<br />
The above code creates a new, green-colored Geyser.Label in the ''testCon'' adjustable.container as shown below:<br />
<br />
[[File:GreenLabelinAdjustableContainer.png]]<br />
<br />
You can also create one for miniconsole:<br />
<br />
<syntaxhighlight lang="lua"><br />
miniconsoleContainer = miniconsoleContainer or Adjustable.Container:new({name="miniconsoleContainer"})<br />
myMiniconsole = Geyser.MiniConsole:new({<br />
name="myMiniconsole",<br />
x=0, y=0,<br />
autoWrap = true,<br />
color = "black",<br />
scrollBar = false,<br />
fontSize = 8,<br />
width="100%", height="100%",<br />
}, miniconsoleContainer)<br />
<br />
myMiniconsole:echo("Hello!\n")<br />
</syntaxhighlight><br />
<br />
That will give you:<br />
<br />
[[File:Adjustable container miniconsole.png]]<br />
<br />
=== Key Functions ===<br />
A listing of key functions for the Adjustable.Container module can be found hereː https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html<br />
<br />
To make the Adjustable Container show on screen use the following:<syntaxhighlight lang="lua"><br />
testCon:show() --will cause the Adjustable Container to show if not showing<br />
</syntaxhighlight><br />
<br />
===<div id="valid constraints"> Valid Constraints</div>===<br />
Adjustable Container constraints and their default values can be found at [https://www.mudlet.org/geyser/files/geyser/AdjustableContainer.html#Adjustable.Container:new].<br />
<br />
These are in addition to the standard Geyser.Container constraints.<br />
<br />
=== Change Title Text ===<br />
To specify the title text of a new container, use the constraint <code>titleText</code> in the constructor (see [[Manual:Geyser#valid constraints|valid constraints]]).<br />
<br />
To change the title text after a container has already been created, use <code>setTitle</code>. Continuing from the previous example, the title for an existing container named "testCon" might be adjusted in a number of ways: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Title") -- changes the container's title to "Title"<br />
</syntaxhighlight><br />
<br />
A container's title text defaults to the color green, but this can also be adjusted by using <code>setTitle</code>: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle("Red Title Test","red") -- changes the container's title text to "Red Title Test" and displays the text in the specified color "red".<br />
</syntaxhighlight><br />
<br />
To restore a container's default title text, <code>setTitle</code> is issued without any specified title or color: <br />
<br />
<syntaxhighlight lang="lua"><br />
testCon:setTitle() -- resets the container's title text<br />
</syntaxhighlight><br />
<br />
=== AutoSave and AutoLoad ===<br />
The following Adjustable.Container settings can be saved and loadedː<br />
<br />
<code>x</code>, <code>y</code>, <code>height</code>, <code>width</code>, <code>minimized</code>, <code>locked</code>, <code>lock Style</code>, <code>padding</code>, and <code>hidden</code>.<br />
<br />
These settings will be automatically saved when the Mudlet profile is closed, and automatically loaded when a previous Adjustable.Container is created within the corresponding profile.<br />
<br />
To prevent automatic saving and/or loading of these settings, the <code>autoLoad</code> and <code>autoSave</code> constraints can be included in the constructor. For example, the following code will prevent the settings of the ''testCon2'' Adjustable.Container from being loaded upon creation:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", autoLoad=false})<br />
</syntaxhighlight><br />
<br />
To also prevent the ''testCon2'' Adjustable.Container from automatically saving its settings when the Mudlet profile is closed, the <code>autoSave=false</code> constraint would be added at creation as follows:<br />
<br />
<syntaxhighlight lang="lua"><br />
testCont2 = testCont2 or Adjustable.Container:new({name="testCont2", autoLoad=false, autoSave=false})<br />
</syntaxhighlight><br />
<br />
Automatic saving can also be deactivated after an Adjustable.Container has been created, by invoking <code>testCont:disableAutoSave()</code><br />
<br />
Note that even with autoSave and autoLoad disabled, it is still possible to save and load manually through the right-click menu and/or by using <code>testCont:save()</code> or <code>testCont:load()</code> in a script.<br />
<br />
To save/load all your containers manually at the same time, we use <code>Adjustable.Container:saveAll()</code> and/or <code>Adjustable.Container:loadAll()</code><br />
<br />
=== "All" Functions ===<br />
The following functions affect all Adjustable Containers at the same time.<br />
<br />
{{note}} You must create the Adjustable Containers before these functions will have an effect.<br />
<br />
<code>Adjustable.Container.loadAll()</code> loads all the settings from your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container.saveAll()</code> saves all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container.loadAll()</code> loads all the settings from your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:showAll()</code> shows all your Adjustable Containers at once.<br />
<br />
<code>Adjustable.Container:doAll(myfunc)</code> creates a function that will affect all your Adjustable Containers. For example:<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:hide() end) -- hides all your adjustable containers<br />
</syntaxhighlight><br />
<br />
=== Custom Save/Load Directories and Slots ===<br />
{{note}} available in Mudlet 4.10+<br />
==== Custom Directory ====<br />
If no option set your Adjustable.Container saves/loads its settings in your profile directory.<br />
<br />
It is possible to change the default save/load directory by using for example a different defaultDir as constraint when creating your Adjustable.Container.<br />
<br />
{{note}} This can be especially useful for authors of packages which want to ship their own save files.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = "/home/edru/MyAdjustableContainerSettings/"}) -- noteː the directory will be created if it doesn't exist<br />
</syntaxhighlight><br />
<br />
Example for save files in a package (assuming the packagename is "AdjustableContainerTest" and the settings are saved in "myPersonalAdjSettings"<br />
<syntaxhighlight lang="lua"><br />
local packageName = "AdjustableContainerTest"<br />
testCon2 = testCon2 or Adjustable.Container:new({name="testCon2", defaultDir = string.format("%s/%s/myPersonalAdjSettings/", getMudletHomeDir(), packageName)})<br />
</syntaxhighlight><br />
<br />
==== Custom Slot ====<br />
Another useful addition is to choose a save slot depending on the situation or to reset to a default save state.<br />
<br />
To save to a different slot just add it as parameter when saving.<br />
<br />
For exampleː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːsave("combatSlot")<br />
</syntaxhighlight><br />
<br />
To then load from that slot just useː<br />
<syntaxhighlight lang="lua"><br />
testCon2ːload("combatSlot")<br />
</syntaxhighlight><br />
<br />
{{note}} This also allows package/module authors to choose a "default" save setting to reset to.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
Adjustable.ContainerːsaveAll("default") -- saves the default settings<br />
<br />
-- to reset to default settings then just use<br />
Adjustable.ContainerːloadAll("default") -- loads the default settings<br />
</syntaxhighlight><br />
<br />
This can also be used to change the whole GUI on the fly.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
-- in combat situation use combat settings<br />
Adjustable.ContainerːloadAll("combat") -- loads special combat settings<br />
-- combat is over <br />
Adjustable.ContainerːloadAll("default") --reverts to the default settings<br />
</syntaxhighlight><br />
<br />
==== Delete Save File ====<br />
To delete the save file just useː<br />
<syntaxhighlight lang="lua"><br />
testCont2:deleteSaveFile()<br />
</syntaxhighlight><br />
<br />
===Right-click menu===<br />
Your Adjustable Container has also integrated a right-click menu with the main key functions for easier usability:<br />
<br />
[[File:AdjustableContainerRightClickMenu.png]]<br />
<br />
The right-click menu automatically shows you the possible positions to attach to (top, right, bottom, or left) when it's near one of them. For example, to attach a window to the right of the screen, drag it over to the right - and then the 'Attach to - right' will appear as an option:<br />
<br />
[[File:Adjustable Container - attach to right.png]]<br />
<br />
It also shows the lockstyle selection, which allows you to choose what happens when you press <code>Lock</code>, with 4 lockstyles available by default:<br />
<br />
* standard: this is the default lockstyle, with a small margin on top to keep the right click menu usable.<br />
* light: only hides the min/restore and close labels. Borders and margin are not affected.<br />
* full: the container gets fully locked without any margin left for the right click menu.<br />
* border: keeps the borders of the container visible while locked.<br />
<br />
From Mudlet 4.10+ on it is also possible to change your right-click menu style to dark mode by<br />
<br />
<syntaxhighlight lang="lua"><br />
myAdjustableContainer:changeMenuStyle("dark") -- possible menu styles are "dark" or "light"<br />
</syntaxhighlight><br />
<br />
=== Create a Custom Menu with Custom Items ===<br />
To create a new menu element in your right click menu called "Custom" and add an item to it use:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newCustomItem(name, func)<br />
-- for example<br />
testcontainer:newCustomItem("Hello world", function(self) echo("Hello world\n") self:flash() end)<br />
-- this will write "Hello world" to the main console and flashes your container.<br />
</syntaxhighlight><br />
<br />
=== Add new LockStyles ===<br />
For more advanced users it's possible to add a new Lockstyles by:<br />
<syntaxhighlight lang="lua"><br />
testcontainer:newLockStyle(name, func)<br />
-- for example<br />
testcontainer:newLockStyle("NewLockStyle", function(self) self.Inside:move(40, 40) self.Inside:resize(-40,-40) self:setTitle("") end)<br />
</syntaxhighlight><br />
<br />
=== Change Adjustable Container Style ===<br />
Additionally to the standard container constraints Adjustable Containers allow you to change at creation: the internal Label style, the menu style, min/close buttons, the menu text, title text... <br />
<br />
( see [[Manual:Geyser#valid constraints|valid constraints]])<br />
An example of a Adjustable Container with different style.<br />
<syntaxhighlight lang="lua"><br />
testCont =<br />
testCont or<br />
Adjustable.Container:new(<br />
{<br />
name = "TestNewStyleContainer",<br />
adjLabelstyle = "background-color:rgba(220,220,220,100%); border: 5px groove grey;",<br />
buttonstyle=[[<br />
QLabel{ border-radius: 7px; background-color: rgba(140,140,140,100%);}<br />
QLabel::hover{ background-color: rgba(160,160,160,50%);}<br />
]],<br />
buttonFontSize = 10,<br />
buttonsize = 20,<br />
titleText = "My new Style",<br />
titleTxtColor = "black",<br />
padding = 15,<br />
}<br />
)<br />
</syntaxhighlight><br />
This code creates a container which looks like this:<br />
<br />
[[File:NewStyleAdjustableContainer.png|Adjustable Container with different style]]<br />
<br />
<br />
=== Attach your Adjustable Container to a Border ===<br />
The simplest way to attach your container to a border is to move your container near the border you want it to attach and use the <br />
right click menu <code> Attach to:</code><br />
<br />
There is also the function <code> TestCont:attachToBorder("right") -- attach TestCont to the right border </code><br />
<br />
To change the margin between container and border use the constraint <code> attachedMargin </code > or the function <code> TestContːsetBorderMargin(10) -- 10 is the margin in px </code><br />
<br />
{{note}} The border is set in percentages and adjusts with screen-size<br />
<br />
=== Create a moveable border frame ===<br />
{{note}} available in Mudlet 4.10+<br />
<br />
Adjustable Container can be connected to a border and therefore act like a frame.<br />
<br />
This only works if your container is attached to a specific border and the border to connect to has also at least one container attached to it.<br />
Use the function <code>connectToBorder</code><br />
<br />
<syntaxhighlight lang="lua"><br />
TestCont:connectToBorder("left") -- possible borders are "top", "bottom", "right", "left"<br />
</syntaxhighlight><br />
<br />
Minimizing automatically disconnects from a border. Another way is to use the function <code>disconnect</code>.<br />
<br />
{{note}}Connected container are still resizable even if locked.<br />
<br />
If you like to do everything with your right click menu there is the function<br />
<br />
<syntaxhighlight lang="lua"><br />
TestContːaddConnectMenu()<br />
</syntaxhighlight><br />
If you want to add the connect menu items to all Adjustable Containers just<br />
<syntaxhighlight lang="lua"><br />
Adjustable.Container:doAll(function(self) self:addConnectMenu() end)<br />
</syntaxhighlight><br />
<br />
There is also a brief video of how to [https://www.youtube.com/watch?v=Ex-q5zAEfpc connect your Adjustable Container] available.<br />
<br />
Exampleː<br />
<syntaxhighlight lang="lua"><br />
GUI = GUI or {}<br />
<br />
GUI.top = Adjustable.Container:new({name = "top", y="0%", height = "10%", autoLoad = false})<br />
GUI.bottom = Adjustable.Container:new({name = "bottom", height = "20%", y = "-20%", autoLoad = false})<br />
GUI.right = Adjustable.Container:new({name = "right", y = "0%", height = "100%", x = "-20%", width = "20%", autoLoad = false})<br />
GUI.left = Adjustable.Container:new({name = "left", x = "0%", y = "0%", height = "100%", width = "20%", autoLoad = false})<br />
<br />
<br />
GUI.top:attachToBorder("top")<br />
GUI.bottom:attachToBorder("bottom")<br />
GUI.left:attachToBorder("left")<br />
GUI.right:attachToBorder("right")<br />
<br />
GUI.top:connectToBorder("left")<br />
GUI.top:connectToBorder("right")<br />
GUI.bottom:connectToBorder("left")<br />
GUI.bottom:connectToBorder("right")<br />
</syntaxhighlight><br />
Here's what the frame will look like:<br />
<br />
[[File:Adjustable_frame.gif]]<br />
<br />
=== Add a scrollable box ===<br />
{{note}} available in Mudlet 4.15+<br />
<br />
To add a scrollable box to an adjustable label, try the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
ScrollContainer = ScrollContainer or Adjustable.Container:new({name = "ScrollContainer"})<br />
ContainerBox = ContainerBox or Geyser.ScrollBox:new({name = "ContainerBox", x = 0, y = 0, height = "100%", width = "100%"}, ScrollContainer)</syntaxhighlight><br />
<br />
[[File:Scrollbox-in-container.png|thumb|center]]<br />
<br />
==Change Container==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
With this command it is possible to change an elements or even a containers location to that from another container.<br />
For example:<br />
<syntaxhighlight lang="lua"><br />
mycontainerone:changeContainer(mycontainertwo)<br />
--puts container one into container two which means container two will be the parent of container one<br />
</syntaxhighlight><br />
It is also possible to change to a container which is not located on the main window:<br />
<syntaxhighlight lang="lua"><br />
myEmco:changeContainer(emco_userwindow)<br />
--puts my tabbed chat Emco into my userwindow<br />
--to put it back to the main window change to a container located on the main window<br />
myEmco:changeContainer(mymainwindow_container)<br />
--or if it the element wasn't in a container use the main Geyser Root container called Geyser<br />
myEmco:changeContainer(Geyser)<br />
</syntaxhighlight><br />
<br />
==Geyser.Mapper==<br />
{{note}} available in Mudlet 4.8+<br />
<br />
It‘s possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation use: (this will create a map window docked at the left corner)<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded= false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are "left", "right", "top", "bottom", and "floating".<br><br />
To change the dockPosition after creation use:<br />
<br />
<syntaxhighlight lang="lua"><br />
myMapWidget:setDockPosition("floating")<br />
-- this will change myMapWidget dockPosition to floating <br />
</syntaxhighlight><br />
<br />
= Tutorial =<br />
Note: This tutorial assumes you know how scripts in Mudlet work. If not then you should look at the manual first. Also it only shows how Geyser basically works and explains Geysers special windows. It wont go into detail about the windows that where already in Mudlet.<br />
<br />
=== Hello World ===<br />
Let's start with something simple. A Label.<br />
<br />
<syntaxhighlight lang="lua"><br />
Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_1.png]]<br />
<br />
This code creates a blank Label with a size of 200x50 at a position of 50 points horizontal and vertical from its parent window - which is the main window since we didn't specify any.<br />
<br />
You can manipulate the Label through the normal functions but Geyser.Label:new() returns an object which can be used to manipulate the label directly. So you should store it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local HelloWorld = Geyser.Label:new({<br />
name="HelloWorld",<br />
x=50, y=50,<br />
width=200, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
Then you can, for example print a text on it:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_2.png]]<br />
<br />
You can put a format parameter so that the text is, for example, centered.<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_3.png]]<br />
<br />
The second parameter is the color. We set it to nil which means the labels foreground color will be used.<br />
<br />
The color parameter either accepts a string ("red"), a hex value("#FF0000" or "0xFF0000" or "|cFF0000"), or a decimal value "&lt;255,0,0&gt;"<br />
<br />
Example:<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:echo("Hello World", "red", "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
{{note}} This will automatically set the foreground color, so any echo, without the color parameter set, after that will use the same color.<br />
<br />
You can also set the foreground color with the setFgColor method:<br />
<br />
<syntaxhighlight lang="lua"><br />
HelloWorld:setFgColor("red")<br />
HelloWorld:echo("Hello World", nil, "c")<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_HW_4.png]]<br />
<br />
=== Containers ===<br />
<br />
Containers are windows that can contain other windows. Actually, since all other Geyser windows subclass container, every window can do that. But containers do not have any visible content by themselves. <br />
<br />
Let's show that by an example:<br />
<syntaxhighlight lang="lua"><br />
local container = Geyser.Container:new({<br />
name="container",<br />
x=50, y=50,<br />
width=250, height=50,<br />
})<br />
</syntaxhighlight><br />
<br />
This will create a container, but if you look at the screen you will see nothing at the positon.<br />
There is a way to make containers visible though:<br />
<syntaxhighlight lang="lua"><br />
container:flash()<br />
</syntaxhighlight><br />
<br />
This will flash the container for a short period of time.<br />
<br />
[[Image:Geyser_Container_1.png]]<br />
<br />
flash() accepts a number as paremeter which defines the time, in seconds, the flash is shown.<br />
<br />
Now, that the container is created, you can add other windows to it. There are 2 ways:<br />
<br />
Directly when creating the window:<br />
<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
},<br />
container)<br />
container_label:echo("This is a label in a container", nil, "c")<br />
</syntaxhighlight><br />
<br />
Later, after the window was created<br />
<syntaxhighlight lang="lua"><br />
local container_label = Geyser.Label:new({<br />
name="container_label",<br />
x=0, y=0,<br />
width="100%", height="100%",<br />
})<br />
container_label:echo("This is a label in a container", nil, "c")<br />
container:add(container_label)<br />
</syntaxhighlight><br />
<br />
Both will lead to the same outcome.<br />
<br />
[[Image:Geyser_Container_2.png]]<br />
<br />
Note that we gave a width and height of "100%" to the constructor of the label. This means that the label will take 100% of the containers width and height. If values are given in percent they will even resize with its parent:<br />
<br />
<syntaxhighlight lang="lua"><br />
container:resize(325, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_3.png]]<br />
<br />
The first parameter is the width, the second the height. If the value is nil the current value is used.<br />
<br />
As said in the "Hello World" tutorial the position is relative to its parent window. That's why we could set both x and y to 0 and it is at the position we wanted - the position of the container.<br />
<br />
When we now move the container the label moves with it:<br />
<syntaxhighlight lang="lua"><br />
container:move(400, nil)<br />
</syntaxhighlight><br />
<br />
[[Image:Geyser_Container_4.png]]<br />
<br />
The first parameter is the x-, the second the y-position. If the value is nil the current value is used.<br />
<br />
=== VBox and HBox ===<br />
<br />
The VBox and HBox classes are special Containers.<br />
They will automatically align its containing windows vertically or horizontally, respectively, in the order they where added to them.<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local HBox = Geyser.HBox:new({<br />
name="HBox",<br />
x=0, y=0,<br />
width=400, height=30,<br />
})<br />
<br />
</syntaxhighlight><br />
<br />
Like containers you won't see them by themselves.<br />
<br />
Adding children works like with containers<br />
<syntaxhighlight lang="lua"><br />
<br />
local label1 = Geyser.Label:new({<br />
name="Label1",<br />
},<br />
HBox)<br />
label1:echo("Label 1", "black", "c")<br />
label1:setColor(255, 0, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_1.png]]<br />
<br />
We didn't set any position or size, but the label gets the same size as the HBox.<br />
<br />
If we add another window:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label2 = Geyser.Label:new({<br />
name="Label2",<br />
},<br />
HBox)<br />
label2:echo("Label 2", "black", "c")<br />
label2:setColor(0, 255, 0)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_2.png]]<br />
<br />
the size will be divided equally between them!<br />
<br />
What if you want a child that takes more or less space than the others?<br />
That's possible too:<br />
<syntaxhighlight lang="lua"><br />
<br />
local label3 = Geyser.Label:new({<br />
name="Label3",<br />
h_stretch_factor=2.0,<br />
},<br />
HBox)<br />
label3:echo("Label 3", nil, "c")<br />
label3:setColor(0, 0, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_3.png]]<br />
<br />
As you can see, Label 3 takes the same space as Label 1 and 2 Together. <br />
That's because we supplied a horizontal stretch factor with "h_stretch_factor=2.0"<br />
<br />
This works also with a vertical stretch factor, just replace "h_stretch_factor" with "v_stretch_factor"<br />
<br />
Now you may have windows that should not be stretched at all.<br />
To accomplish this you have to set the horizontal and/or vertical policy:<br />
<br />
<syntaxhighlight lang="lua"><br />
<br />
local label4 = Geyser.Label:new({<br />
name="Label4",<br />
width="13%",<br />
h_policy=Geyser.Fixed,<br />
},<br />
HBox)<br />
label4:echo("Label 4", "black", "c")<br />
label4:setColor(0, 255, 255)<br />
<br />
</syntaxhighlight><br />
<br />
[[Image:HVBox_4.png]]<br />
<br />
Possible values for the policies are Geyser.Fixed and Geyser.Dynamic (which is the default). They can also be applied to VBox and HBox in exactly the same way.<br />
<br />
Note that, like in the example above, the label will retain relative values (like percent) if used.<br />
<br />
The VBox works like the HBox, only that the child windows are aligned vertically.<br />
<br />
= Walkthroughs =<br />
Here are a few walkthroughs that will show you how to combine Geyser elements to create some simple GUI widgets.<br />
<br />
===Create a Clickable Compass===<br />
[[File: compass.png]]<br />
The following will walk you through the process of creating your own clickable compass using the Geyser framework.<br />
====Setup the image files====<br />
The compass requires a handful of images to work properly. You can find them here: https://www.dropbox.com/sh/53l7xrn4ds35wnq/WpWOziVKmH <br><br />
Download each image and place it in your profile folder. You can find your profile folder with getMudletHomeDir()<br><br />
If you're using Mudlet 2.1+ you can enter '''lua getMudletHomeDir()''' from the command line to return the profile folder path on your computer.<br />
<br />
====Create a new script====<br />
Script Name: '''''compass.resize'''''<br><br />
Registered Event Handlers: '''''sysWindowResizeEvent'''''<p><br />
Every snippet of code will be placed within this script.<br />
====Store the screen size====<br />
We'll want to store the screen size in some local variables so they can be easily referenced to later on.<br />
<syntaxhighlight lang="lua">local mw, mh = getMainWindowSize()</syntaxhighlight><br />
<br />
====Create a global table or namespace====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''compass''''' and everything we make from here on out will be stored within the compass table. We'll also add a few values to it: dirs and ratio. '''''compass.dirs''''' will store each direction while '''''compass.ratio''''' will store the ratio of our screen size so you can 'square up' your compass.<br />
<syntaxhighlight lang="lua">compass = compass or {<br />
dirs = {"nw","n","ne","w","center","e","sw","s","se"},<br />
ratio = mw / mh<br />
}</syntaxhighlight><br />
<br />
====Create the parent label====<br />
[[File: grey.png|thumbnail]]<br />
The 'parent label' refers to the label on the bottom layer. The entire compass will be created within this label. It's container is '''main''' for it's parent is the main window.<br />
<syntaxhighlight lang="lua">compass.back = Geyser.Label:new({<br />
name = "compass.back",<br />
x = "25%",<br />
y = "25%",<br />
width = "10%",<br />
height = "10%",<br />
},main)</syntaxhighlight><br />
<br />
====Set the parent label stylesheet====<br />
[[File: blue.png|thumbnail]]<br />
This will create the blue sphere that makes up most of the compass. The background color is a radial gradient that goes from a deep blue to a brighter shade. The border radius rounds the edges. When the radius is exactly half of the label width it forms a circle. The arrows of the compass actually protrude from the sphere so we give it a margin to suck it in a bit for this effect.<br />
<syntaxhighlight lang="lua">compass.back:setStyleSheet([[<br />
background-color: QRadialGradient(cx:.3,cy:1,radius:1,stop:0 rgb(0,0,50),stop:.5 rgb(0,0,100),stop:1 rgb(0,0,255));<br />
border-radius: ]]..tostring(compass.back:get_width()/2-14)..[[px;<br />
margin: 10px;<br />
]])</syntaxhighlight><br />
<br />
====Create a 3x3 grid====<br />
The compass is split into 9 sections. One for each cardinal direction plus an extra space that sits in the center. This 3x3 grid is created by 3 VBoxes that sit within a single HBox (or vice versa but I flipped a coin and this is what it gave me).<br><br />
So first off, we create the HBox. It will be the same size as its parent, ''compass.back''.<br />
<syntaxhighlight lang="lua"> compass.box = Geyser.HBox:new({<br />
name = "compass.box",<br />
x = 0,<br />
y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},compass.back)</syntaxhighlight><br />
Next, we create our 3 VBoxes. You don't need to specify position or size because these are placed within ''compass.box'', an HBox.<br />
<syntaxhighlight lang="lua"> compass.row1 = Geyser.VBox:new({<br />
name = "compass.row1",<br />
},compass.box)<br />
compass.row2 = Geyser.VBox:new({<br />
name = "compass.row2",<br />
},compass.box)<br />
compass.row3 = Geyser.VBox:new({<br />
name = "compass.row3",<br />
},compass.box)</syntaxhighlight><br />
Finally, we add our 9 labels. Take note that they are split up into even groups of 3. Each group is placed into a different ''compass.row#''<br />
<syntaxhighlight lang="lua"> compass.nw = Geyser.Label:new({<br />
name = "compass.nw",<br />
},compass.row1)<br />
<br />
compass.w = Geyser.Label:new({<br />
name = "compass.w",<br />
},compass.row1)<br />
<br />
compass.sw = Geyser.Label:new({<br />
name = "compass.sw",<br />
},compass.row1)<br />
<br />
compass.n = Geyser.Label:new({<br />
name = "compass.n",<br />
},compass.row2)<br />
<br />
compass.center = Geyser.Label:new({<br />
name = "compass.center",<br />
},compass.row2)<br />
<br />
compass.s = Geyser.Label:new({<br />
name = "compass.s",<br />
},compass.row2)<br />
<br />
compass.ne = Geyser.Label:new({<br />
name = "compass.ne",<br />
},compass.row3)<br />
<br />
compass.e = Geyser.Label:new({<br />
name = "compass.e",<br />
},compass.row3)<br />
<br />
compass.se = Geyser.Label:new({<br />
name = "compass.se",<br />
},compass.row3)</syntaxhighlight><br />
====Create a callback function====<br />
We'll want our compass to head in the direction of the arrow we're clicking. This is where we specify so. When the arrow is clicked, this function will be ran with the arrow direction as the argument.<br />
<syntaxhighlight lang="lua">function compass.click(name)<br />
send(name)<br />
end</syntaxhighlight><br />
====Create the hover functions====<br />
We want our arrows to turn yellow when we hover over them. We do so by simply resetting the label's stylesheet and changing the border image. Don't forget to include the margin as we still want that.<br />
<syntaxhighlight lang="lua">function compass.onEnter(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[hover.png");<br />
margin: 5px;<br />
]])<br />
end<br />
<br />
function compass.onLeave(name)<br />
compass[name]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..name..[[.png");<br />
margin: 5px;<br />
]])<br />
end</syntaxhighlight><br />
====Set the stylesheets in the grid====<br />
[[File: Sample.png|thumb]]<br />
Each of the 9 labels need an image of an arrow. Rather than setting each individually, we'll iterate over the ''compass.dirs'' table we made awhile back and add the respective image to each. The names of images are a reflection of the ''compass.dirs'' table. This keeps it consistent and easy to refer to. During the iteration, the callback, setLabelOnEnter and setLabelOnLeave are also set for each label.<br />
<syntaxhighlight lang="lua">for k,v in pairs(compass.dirs) do<br />
compass[v]:setStyleSheet([[<br />
border-image: url("]]..getMudletHomeDir()..[[/]]..v..[[.png");<br />
margin: 5px;<br />
]])<br />
compass[v]:setClickCallback("compass.click",v)<br />
setLabelOnEnter("compass."..v,"compass.onEnter",v)<br />
setLabelOnLeave("compass."..v,"compass.onLeave",v)<br />
end</syntaxhighlight><br />
<br />
====Resize the compass into a square====<br />
[[File: final.png|thumb]]<br />
Most screen size ratios aren't a perfect 1:1. This will cause a 10% x 10% label to be far from square. By setting our height (the smaller of the two numbers) to our width, we can resize our compass to a near perfect square. This function is also the name of our script because we want it to run each time sysWindowResizeEvent is raised.<br />
<syntaxhighlight lang="lua">function compass.resize()<br />
compass.back:resize(compass.back.width, compass.back:get_width())<br />
end<br />
<br />
compass.resize()</syntaxhighlight><br />
<br />
===Create a Tabbed Window===<br />
[[File: tabwindow.png]]<br />
The following will walk you through the process of creating your own tabbed window using the Geyser framework.<br />
<br />
====Create a new script====<br />
Script Name: '''''Tabbed Window'''''<br><br />
Every snippet of code will be placed within this script.<br />
====Create a global table====<br />
Creating a global table will make each of your variables unique. Our namespace will be called '''''menu''''' and everything we make from here on out will be stored within the menu table. We'll also add a few values to it: tabs, color1, color2, width, height and current. <br><br />
''''tabs'''' will be a table that stores all our tab names. If we want our tabs to have different names, we alter this table.<br><br />
''''color1'''' and ''''color2'''' will store the colors of our tabbed window. If we want to change the color of our tabbed window, we alter these values.<br><br />
''''width'''' and ''''height'''' will store the size of our tabbed window. If we want to change the size of the tabbed window, we alter these values.<br><br />
''''current'''' keeps track of which tab is selected. We will set this to the first tab in the table by default. We do this outside the initial table creation so we can easily access menu.tabs<br><br />
<syntaxhighlight lang="lua">menu = menu or {<br />
tabs = {"Tab1","Tab2","Tab3","Tab4"},<br />
color1 = "rgb(0,0,70)",<br />
color2 = "rgb(0,0,50)",<br />
width = "20%",<br />
height = "40%",<br />
}<br />
menu.current = menu.current or menu.tabs[1]</syntaxhighlight><br />
<br />
====Create the main container====<br />
Our tabbed window will need a container. This will be the bottom layer. Containers are invisible so no need to set a stylesheet.<br />
<syntaxhighlight lang="lua">menu.container = Geyser.Container:new({<br />
name = "menu.back",<br />
x = "50%", y = "25%",<br />
width = menu.width,<br />
height = menu.height,<br />
},main)</syntaxhighlight><br />
====Create an HBox====<br />
All of our tabs will be evenly spaced. So we'll create an HBox to sit at the top of our container.<br />
<syntaxhighlight lang="lua">menu.header = Geyser.HBox:new({<br />
name = "menu.header",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "10%",<br />
},menu.container)</syntaxhighlight><br />
====Create a label====<br />
This label will serve as a container for each window. It sits right underneath the HBox we just created for the tabs.<br />
<syntaxhighlight lang="lua">menu.footer = Geyser.Label:new({<br />
name = "menu.footer",<br />
x = 0, y = "10%",<br />
width = "100%",<br />
height = "90%",<br />
},menu.container)</syntaxhighlight><br />
We don't want this to be a big grey box at startup, so we'll set the stylesheet to appear like the rest of the windows.<br />
<syntaxhighlight lang="lua"><br />
menu.footer:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])</syntaxhighlight><br />
Each window actually has two labels. One for the light blue background, and another for the dark blue center. This will create that dark blue center.<br />
<syntaxhighlight lang="lua">menu.center = Geyser.Label:new({<br />
name = "menu.center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
menu.center:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])</syntaxhighlight><br />
====Add your tabs and their windows====<br />
Now we'll want to add our tabs and windows. We do this in a single for loop of the ''''menu.tabs'''' table since it holds all our tab names.<br />
<syntaxhighlight lang="lua">for k,v in pairs(menu.tabs) do<br />
</syntaxhighlight><br />
This will create the tabs. Each tab will be named: menu.<tabname>tab<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"] = Geyser.Label:new({<br />
name = "menu."..v.."tab",<br />
},menu.header)<br />
</syntaxhighlight><br />
Here is where we set the tab stylesheet. Each tab has a rounded top, so we set the border-radius of the top-left and top-right to 10px. Each tab has a small space for separation so we give the right and left sides a tiny margin of 1px.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-top-left-radius: 10px;<br />
border-top-right-radius: 10px;<br />
margin-right: 1px;<br />
margin-left: 1px;<br />
]])<br />
</syntaxhighlight><br />
This will display the name of each tab on the tab.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:echo("<center>"..v)<br />
</syntaxhighlight><br />
We need our tabs to do stuff when clicked, so we'll assign it a callback function, '''''menu.click''''', which we'll create later on. Our tab name is the argument.<br />
<syntaxhighlight lang="lua"><br />
menu[v.."tab"]:setClickCallback("menu.click",v)<br />
</syntaxhighlight><br />
Now we create the windows that appear when each tab is clicked. Each window has two labels, one atop the other. The first, which we'll create here, has rounded edges on its bottom.<br />
<syntaxhighlight lang="lua"><br />
menu[v] = Geyser.Label:new({<br />
name = "menu."..v,<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.footer)<br />
<br />
menu[v]:setStyleSheet([[<br />
background-color: ]]..menu.color1..[[;<br />
border-bottom-left-radius: 10px;<br />
border-bottom-right-radius: 10px;<br />
]])<br />
</syntaxhighlight><br />
The second label serves as the window's center and has rounded edges on all sides. And a margin of 5px from it's parent, the label we just created. When adding stuff to your windows, this is the label you'll want to use. '''''menu.<tabname>center'''''<br />
<syntaxhighlight lang="lua"><br />
menu[v.."center"] = Geyser.Label:new({<br />
name = "menu."..v.."center",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu[v])<br />
</syntaxhighlight><syntaxhighlight lang="lua"><br />
menu[v.."center"]:setStyleSheet([[<br />
background-color: ]]..menu.color2..[[;<br />
border-radius: 10px;<br />
margin: 5px;<br />
]])<br />
</syntaxhighlight><br />
Finally, we hide all the windows and end the for loop.<br />
<syntaxhighlight lang="lua"><br />
menu[v]:hide()<br />
end</syntaxhighlight><br />
====Create a callback function====<br />
The last step is to create our callback function for when a tab is clicked. This will hide that tab that is stored in '''''menu.current''''', set menu.current to the clicked tab, and then show the menu.current tab.<br />
<syntaxhighlight lang="lua">function menu.click(tab)<br />
menu[menu.current]:hide()<br />
menu.current = tab<br />
menu[menu.current]:show()<br />
end</syntaxhighlight><br />
====Adding content to your windows====<br />
Add content to '''menu.<tab name>center'''<br />
So if we wanted to display our gold in a window we could:<syntaxhighlight lang="lua">menu.Tab1center:echo(myGold)</syntaxhighlight><br />
If we wanted to add a map to a window we could:<br />
<syntaxhighlight lang="lua">myMap = Geyser.Mapper:new({<br />
name = "myMap",<br />
x = 0, y = 0,<br />
width = "100%",<br />
height = "100%",<br />
},menu.Tab2center)</syntaxhighlight><br />
<br />
===Create a Window with a resize label===<br />
<br />
Previous tutorial is now done much simpler [[Manual:Geyser#Adjustable.Container|Adjustable containers]], have a look at those instead.<br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:String_Functions&diff=20306Manual:String Functions2023-02-05T19:22:57Z<p>Kebap: /* string.dump */ Do not shadow built-in "string" in example</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Mudlet API documentation for functions used to manipulate strings.}}<br />
= String Functions =<br />
A collection of functions used to manipulate strings.<br />
==addWordToDictionary==<br />
;addWordToDictionary(word)<br />
:Adds the given word to the custom profile or shared dictionary (whichever is selected in preferences).<br />
<br />
: Returns true on success (the word was actually ''added'' to the dictionary by this call) and nil+msg on error - including if the word was already there - this is so that if you have other scripts that you wish to run when a word was added you can make their execution conditional on success here.<br />
<br />
:See also: [[#removeWordFromDictionary|removeWordFromDictionary()]]<br />
<br />
;Parameters<br />
* ''word:'' custom word to add to the dictionary.<br />
<br />
{{MudletVersion|3.18}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addWordToDictionary("Darkwind")<br />
addWordToDictionary("黑暗的风")<br />
addWordToDictionary("норм")<br />
</syntaxhighlight><br />
<br />
;Example - function making use of return value:<br />
<syntaxhighlight lang="lua"><br />
function rememberPlayerName(name)<br />
if addWordToDictionary(name) then<br />
echo("Added '" .. name .. "' to dictionary...\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==cecho2string==<br />
; plainText = cecho2string(formattedText)<br />
<br />
:Strips the text formatting from the string passed in, leaving behind only the text.<br />
<br />
;See also: [[Manual:Lua_Functions#ansi2string|ansi2string()]], [[Manual:Lua_Functions#hecho2string|hecho2string()]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Parameters<br />
* ''formattedText:''<br />
: The string you want to strip the formatting codes from<br />
<br />
;Returns <br />
* The string with the formatting codes stripped out.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local exampleString = "<red>Formatted <b>string</b>"<br />
local plainText = cecho2string(exampleString)<br />
-- "Formatted string"<br />
</syntaxhighlight><br />
<br />
==decho2string==<br />
; plainText = decho2string(formattedText)<br />
<br />
:Strips the text formatting from the string passed in, leaving behind only the text.<br />
<br />
;See also: [[Manual:Lua_Functions#ansi2string|ansi2string()]], [[Manual:Lua_Functions#cecho2string|cecho2string()]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Parameters<br />
* ''formattedText:''<br />
: The string you want to strip the formatting codes from<br />
<br />
;Returns <br />
* The string with the formatting codes stripped out.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local exampleString = "<255,0,0>Formatted <b>string</b>"<br />
local plainText = decho2string(exampleString)<br />
-- "Formatted string"<br />
</syntaxhighlight><br />
<br />
==f==<br />
; formattedString = f(str)<br />
: Allows you to combine variables and functions into text (string interpolation) using <code>{}</code>.<br />
<br />
; Parameters<br />
* ''str:''<br />
: The string to perform interpolation against.<br />
<br />
{{MudletVersion|4.11}}<br />
; Example:<br />
<br />
<syntaxhighlight lang=lua><br />
-- old way:<br />
cecho("\nHello, "..matches[2]..", how is it going?")<br />
<br />
-- new way:<br />
cecho(f("\nHello {matches[2]}, how is it going?"))<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang=lua><br />
testResult = "successful"<br />
-- old way:<br />
echo("The test was "..testResult.."\n")<br />
-- with f:<br />
echo(f("The test was {testResult}\n"))<br />
-- echoes "The test was successful\n"<br />
<br />
local testResult = "a failure"<br />
echo(f("The test was {testResult}\n"))<br />
-- echoes "The test was a failure\n" as it sees the local scope over global.<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang=lua><br />
-- You can also execute simple expressions<br />
echo(f("2 + 2 = {2 + 2}\n"))<br />
-- echoes "2 + 2 = 4\n"<br />
<br />
-- Or more complicated ones<br />
local function testFunc(item)<br />
return item:title()<br />
end<br />
<br />
echo(f("You should properly capitalize names, such as {testFunc('marilyn')}\n"))<br />
-- echoes "You should properly capitalize names, such as Marilyn\n"<br />
<br />
echo(f("You should properly capitalize names, such as {string.title('robert')}\n")<br />
-- same thing, but uses string.title directly and Robert instead of Marilyn<br />
</syntaxhighlight><br />
<br />
<br />
'''Caution!'''<br />
When using within closures, might not resolve variables correctly if they go out of a scope when closure is called.<br />
<syntaxhighlight lang=lua><br />
function formatter2000()<br />
local upvalue = "2000"<br />
local formatter = function() <br />
echo(f("Let's evaluate: {upvalue}\n"))<br />
end<br />
formatter() -- here evaulation inside f function will work<br />
return formatter<br />
end<br />
<br />
formatter2000()() -- here evaluation inside f function will return nil<br />
-- result<br />
-- Let's evaluate: 2000<br />
-- Let's evaulate: nil<br />
</syntaxhighlight><br />
<br />
You can work around this by doing the following<br />
<syntaxhighlight lang=lua><br />
function formatter2000()<br />
local upvalue = "2000"<br />
local formatter = function()<br />
local upvalue = upvalue -- this keeps upvalue in scope for the function later<br />
echo(f("Let's evaluate: {upvalue}\n"))<br />
end<br />
formatter() -- here evaulation inside f function will work<br />
return formatter<br />
end<br />
<br />
formatter2000()() -- here evaluation inside f function will return 2000 once again<br />
<br />
-- result<br />
-- Let's evaluate: 2000<br />
-- Let's evaulate: 2000<br />
</syntaxhighlight><br />
<br />
==getDictionaryWordList==<br />
;getDictionaryWordList()<br />
:Returns the profile or shared custom dictionary word list (whichever is selected in preferences) - that is, words added via right-click "add word to dictionary" or [[#addWordToDictionary|addWordToDictionary()]].<br />
<br />
: Returns an indexed table of words.<br />
<br />
{{MudletVersion|3.18}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getDictionaryWordList())<br />
</syntaxhighlight><br />
<br />
==hecho2string==<br />
; plainText = hecho2string(formattedText)<br />
<br />
:Strips the text formatting from the string passed in, leaving behind only the text.<br />
<br />
;See also: [[Manual:Lua_Functions#ansi2string|ansi2string()]], [[Manual:Lua_Functions#decho2string|decho2string()]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Parameters<br />
* ''formattedText:''<br />
: The string you want to strip the formatting codes from<br />
<br />
;Returns <br />
* The string with the formatting codes stripped out.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local exampleString = "#ff0000Formatted #bstring#/b"<br />
local plainText = cecho2string(exampleString)<br />
-- "Formatted string"<br />
</syntaxhighlight><br />
<br />
==removeWordFromDictionary==<br />
;removeWordFromDictionary(word)<br />
:Removed the given word to the custom profile or shared dictionary (whichever is selected in preferences).<br />
<br />
: Returns true on success (if the word was present and removed by this call) and nil+msg on error.<br />
<br />
:See also: [[#addWordToDictionary|addWordToDictionary()]]<br />
<br />
;Parameters<br />
* ''word:'' custom word to remove from the dictionary.<br />
<br />
{{MudletVersion|3.18}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
removeWordFromDictionary("Darkwind")<br />
removeWordFromDictionary("黑暗的风")<br />
removeWordFromDictionary("норм")<br />
</syntaxhighlight><br />
<br />
==spellCheckWord==<br />
;spellCheckWord(word, [customDictionary])<br />
:Spellchecks the given word against the custom or the system dictionary.<br />
<br />
: Returns true if the word is spelled correctly or false if it's not, and nil+msg on error.<br />
<br />
:See also: [[#addWordToDictionary|addWordToDictionary()]], [[#removeWordFromDictionary|removeWordFromDictionary()]], [[#spellSuggestWord|spellSuggestWord()]]<br />
<br />
;Parameters<br />
* ''word'': word to spellcheck.<br />
* ''customDictionary'' (optional): dictionary to use. If true, the profile or shared dictionary will be used (depending on your settings). If omitted or false, the system dictionary (the language you have selected in settings) will be used.<br />
<br />
{{MudletVersion|3.18}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- spellcheck against the language dictionary<br />
if spellCheckWord("run") then<br />
echo("'run' is spelled ok!\n")<br />
end<br />
<br />
-- spellcheck against the custom 'add word to dictionary'<br />
if spellCheckWord("Darkwind", true) then<br />
echo("'Darkwind' is spelled OK!\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==spellSuggestWord==<br />
;spellSuggestWord(word, [customDictionary])<br />
:Suggests similar words for the given word.<br />
<br />
: Returns a table of suggestions or nil+msg on error.<br />
<br />
:See also: [[#spellCheckWord|spellCheckWord()]]<br />
<br />
;Parameters<br />
* ''word'': word to give suggestions on.<br />
* ''customDictionary'' (optional): dictionary to use. If true, the profile or shared dictionary will be used (depending on your settings). If omitted or false, the system dictionary (the language you have selected in settings) will be used.<br />
<br />
{{MudletVersion|3.18}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(spellSuggestWord("Darkwind"))<br />
</syntaxhighlight><br />
<br />
==string.byte, utf8.byte==<br />
;string.byte(string [, i [, j]]) or utf8.byte(string [, i [, j]])<br />
;<nowiki>mystring:byte([, i [, j]])</nowiki><br />
: Returns the internal numerical codes of the characters <code>s[i], s[i+1], ···, s[j]</code>. The default value for <code>i</code> is <code>1</code>; the default value for <code>j</code> is <code>i</code>.<br />
: Note that numerical codes are not necessarily portable across platforms.<br />
: string.byte() works with English text only, use utf8.byte() for the international version.<br />
: See also: [[#string.char.2C_utf8.char|string.char]], [[#string.char.2C_utf8.char|utf8.char]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- the following call will return the ASCII values of "A", "B" and "C"<br />
a, b, c = string.byte("ABC", 1, 3)<br />
echo(a .. " - " .. b .. " - " .. c) -- shows "65 - 66 - 67"<br />
<br />
-- same for the international version but with the Unicode values<br />
a, b, c = utf8.byte("дом", 1, 3)<br />
echo(a .. " - " .. b .. " - " .. c) -- shows "1076 - 1086 - 1084"<br />
</syntaxhighlight><br />
<br />
==string.char, utf8.char==<br />
;string.char(···) or utf8.char(···)<br />
: Receives zero or more integers. Returns a string with length equal to the number of arguments, in which each character has the internal numerical code equal to its corresponding argument.<br />
: Note that numerical codes are not necessarily portable across platforms.<br />
: string.char() works with English text only, use utf8.char() for the international version.<br />
: See also: [[#string.byte.2C_utf8.byte|string.byte]], [[#string.byte.2C_utf8.byte|utf8.byte]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- the following call will return the string "ABC" corresponding to the ASCII values 65, 66, 67<br />
mystring = string.char(65, 66, 67)<br />
<br />
-- same for the infernational version which will return text "дом" for the Unicode values 1076, 1086, 1084<br />
mystring = utf8.char(1076,1086,1084)<br />
print(mystring)<br />
</syntaxhighlight><br />
<br />
==string.cut==<br />
;string.cut(string, maxLen)<br />
: Cuts string to the specified maximum length.<br />
: Returns the modified string.<br />
<br />
;Parameters:<br />
* ''string:''<br />
: The text you wish to cut. Passed as a string.<br />
* ''maxLen:''<br />
: The maximum length you wish the string to be. Passed as an integer number.<br />
<br />
See also: [[#utf8.remove|utf8.remove()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--The following call will return 'abc' and store it in myString<br />
myString = string.cut("abcde", 3)<br />
--You can easily pad string to certain length. Example below will print 'abcde ' e.g. pad/cut string to 10 characters.<br />
local s = "abcde"<br />
s = string.cut(s .. " ", 10) -- append 10 spaces<br />
echo("'" .. s .. "'")<br />
</syntaxhighlight><br />
<br />
==string.dump==<br />
;string.dump()<br />
Converts a function into a binary string. You can use the loadstring() function later to get the function back.<br />
: string.dump() works with both English and non-English text fine.<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
testString = string.dump(echo("this is a string"))<br />
--The following should then echo "this is a string"<br />
loadstring(testString)()<br />
</syntaxhighlight><br />
<br />
==string.enclose==<br />
;string.enclose(string)<br />
: Wraps a string with [[ ]]<br />
: Returns the altered string.<br />
<br />
;Parameters:<br />
* ''String:''<br />
:The string to enclose. Passed as a string.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--This will echo '[[Oh noes!]]' to the main window<br />
echo("'" .. string.enclose("Oh noes!") .. "'")<br />
</syntaxhighlight><br />
<br />
==string.ends==<br />
;string.ends(String, Suffix)<br />
: Test if string is ending with specified suffix.<br />
: Returns true or false.<br />
: See also: [[#string.starts|string.starts]]<br />
<br />
;Parameters:<br />
* ''String:''<br />
: The string to test. Passed as a string.<br />
* ''Suffix:''<br />
: The suffix to test for. Passed as a string.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--This will test if the incoming line ends with "in bed" and if not will add it to the end.<br />
if not string.ends(line, "in bed") then<br />
echo("in bed\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==string.find, utf8.find==<br />
;string.find(text, pattern [, init [, plain]]) or utf8.find<br />
: Looks for the first match of pattern in the string text. If it finds a match, then find returns the indices of text where this occurrence starts and ends; otherwise, it returns nil. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative. A value of true as a fourth, optional argument plain turns off the pattern matching facilities, so the function does a plain "find substring" operation, with no characters in pattern being considered "magic". Note that if plain is given, then init must be given as well.<br />
If the pattern has captures, then in a successful match the captured values are also returned, after the two indices.<br />
: string.find() works with English text only, use utf8.find() for the international version.<br />
;Example<br />
<syntaxhighlight lang=lua><br />
-- check if the word appears in a variable<br />
if string.find(matches[2], "rabbit") then<br />
echo("Found a rabbit!\n")<br />
end<br />
<br />
-- the following example will print: "3, 4"<br />
local start, stop = string.find("This is a test.", "is")<br />
if start then<br />
print(start .. ", " .. stop)<br />
end<br />
-- note that here "is" is being found at the end of the word "This", rather than the expected second word<br />
<br />
-- to make it match the word on its own, prefix %f[%a] and suffix %f[%A]<br />
if string.find("This is a test", "%f[%a]is%f[%A]") then<br />
echo("This 'is' is the actual stand-alone word\n")<br />
end<br />
</syntaxhighlight><br />
* Return value:<br />
: nil or start and stop position of the first matched text, followed by any captured text.<br />
<br />
==string.findPattern==<br />
; string.findPattern(text, pattern)<br />
: Return first matching substring or nil.<br />
<br />
; Parameters<br />
* ''text:''<br />
: The text you are searching the pattern for.<br />
* ''pattern:''<br />
: The pattern you are trying to find in the text.<br />
<br />
; Example:<br />
Following example will print: "I did find: Troll" string.<br />
<syntaxhighlight lang="lua"><br />
local match = string.findPattern("Troll is here!", "Troll")<br />
if match then<br />
echo("I did find: " .. match)<br />
end<br />
</syntaxhighlight><br />
:This example will find substring regardless of case.<br />
<syntaxhighlight lang="lua">local match = string.findPattern("Troll is here!", string.genNocasePattern("troll"))<br />
if match then<br />
echo("I did find: " .. match)<br />
end<br />
</syntaxhighlight><br />
* Return value:<br />
: nil or first matching substring<br />
See also: [[#string.genNocasePattern|string.genNocasePattern()]]<br />
<br />
==string.format==<br />
;string.format(formatstring,...)<br />
: Returns a formatted version of its variable number of arguments following the description given in its first argument (which must be a string). The format string follows the same rules as the printf family of standard C functions. The only differences are that the options/modifiers *, l, L, n, p, and h are not supported and that there is an extra option, q. The q option formats a string in a form suitable to be safely read back by the Lua interpreter: the string is written between double quotes, and all double quotes, newlines, embedded zeros, and backslashes in the string are correctly escaped when written. For instance, the call<br />
<syntaxhighlight lang=lua><br />
string.format('%q', 'a string with "quotes" and \n new line')<br />
</syntaxhighlight><br />
will produce the string:<br />
<syntaxhighlight lang=lua><br />
"a string with \"quotes\" and \<br />
new line"<br />
</syntaxhighlight><br />
The options c, d, E, e, f, g, G, i, o, u, X, and x all expect a number as argument, whereas q and s expect a string.<br />
<br />
This function does not accept string values containing embedded zeros, except as arguments to the q option.<br />
<br />
string.format() works fine with both English and non-English text.<br />
<br />
;Example<br />
<syntaxhighlight lang=lua><br />
some_data = "MudletUser1"<br />
<br />
-- pad data 20 characters wide to the left<br />
display(string.format("%20s", some_data))<br />
-- result: " MudletUser1"<br />
<br />
-- pad same data but instead to the the right<br />
display(string.format("%-20s", some_data))<br />
-- result: "MudletUser1 "<br />
<br />
-- pad but first truncate data to 6 characters<br />
display(string.format("%20s", string.sub(some_data, 1, 6)))<br />
-- result: " Mudlet"<br />
</syntaxhighlight><br />
<br />
==string.genNocasePattern==<br />
; string.genNocasePattern(template)<br />
: Generate case insensitive search pattern from string.<br />
<br />
; Parameters<br />
* template: The original string to be used as the base.<br />
<br />
; Example:<br />
<syntaxhighlight lang="lua"><br />
echo(string.genNocasePattern("123abc"))<br />
-- result: "123[aA][bB][cC]"<br />
</syntaxhighlight><br />
<br />
==string.gfind==<br />
;string.gfind()<br />
: This is an old version of what is now string.gmatch. Use string.gmatch instead.<br />
;Example<br />
''Need example''<br />
<br />
==string.gmatch, utf8.gmatch==<br />
;string.gmatch(text, pattern) or utf8.gmatch<br />
: Returns an iterator function that, each time it is called, returns the next captures from pattern over string text. If pattern specifies no captures, then the whole match is produced in each call.<br />
As an example, the following loop<br />
<syntaxhighlight lang=lua><br />
s = "hello world from Lua"<br />
for w in string.gmatch(s, "%a+") do<br />
print(w)<br />
end</syntaxhighlight><br />
will iterate over all the words from string s, printing one per line. The next example collects all pairs key=value from the given string into a table:<br />
<syntaxhighlight lang=lua><br />
t = {}<br />
s = "from=world, to=Lua"<br />
for k, v in string.gmatch(s, "(%w+)=(%w+)") do<br />
t[k] = v<br />
end</syntaxhighlight><br />
For this function, a '^' at the start of a pattern does not work as an anchor, as this would prevent the iteration.<br />
: string.gmatch() works with English text only, use utf8.gmatch() for the international version.<br />
;Example<br />
''Need example''<br />
<br />
==string.gsub, utf8.gsub==<br />
;string.gsub(text, pattern, repl [, n]) or utf8.gsub<br />
: Returns a copy of text in which all (or the first n, if given) occurrences of the pattern have been replaced by a replacement string specified by repl, which can be a string, a table, or a function. gsub also returns, as its second value, the total number of matches that occurred.<br />
<br />
:If repl is a string, then its value is used for replacement. The character % works as an escape character: any sequence in repl of the form %n, with n between 1 and 9, stands for the value of the n-th captured substring (see below). The sequence %0 stands for the whole match. The sequence %% stands for a single %.<br />
<br />
:If repl is a table, then the table is queried for every match, using the first capture as the key; if the pattern specifies no captures, then the whole match is used as the key.<br />
<br />
:If repl is a function, then this function is called every time a match occurs, with all captured substrings passed as arguments, in order; if the pattern specifies no captures, then the whole match is passed as a sole argument.<br />
<br />
:If the value returned by the table query or by the function call is a string or a number, then it is used as the replacement string; otherwise, if it is false or nil, then there is no replacement (that is, the original match is kept in the string).<br />
<br />
: string.gsub() works with English text only, use utf8.gsub() for the international version.<br />
;Example<br />
<syntaxhighlight lang=lua><br />
x = string.gsub("hello world", "(%w+)", "%1 %1")<br />
--> x="hello hello world world"<br />
<br />
x = string.gsub("hello world", "%w+", "%0 %0", 1)<br />
--> x="hello hello world"<br />
<br />
x = string.gsub("hello world from Lua", "(%w+)%s*(%w+)", "%2 %1")<br />
--> x="world hello Lua from"<br />
<br />
x = string.gsub("home = $HOME, user = $USER", "%$(%w+)", os.getenv)<br />
--> x="home = /home/roberto, user = roberto"<br />
<br />
x = string.gsub("4+5 = $return 4+5$", "%$(.-)%$", function (s)<br />
return loadstring(s)()<br />
end)<br />
--> x="4+5 = 9"<br />
<br />
local t = {name="lua", version="5.1"}<br />
x = string.gsub("$name-$version.tar.gz", "%$(%w+)", t)<br />
--> x="lua-5.1.tar.gz"</syntaxhighlight><br />
<br />
==string.len, utf8.len==<br />
;string.len(string) or utf8.len(string)<br />
;<nowiki>mystring:len()</nowiki><br />
:Receives a string and returns its length. The empty string "" has length 0. Embedded zeros are counted, so "a\000bc\000" has length 5.<br />
: string.len() works with English text only, use utf8.len() for the international version.<br />
<br />
;Parameters:<br />
* ''string:''<br />
:The string (text) you want to find the length of.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- prints 5 for the 5 letters in our word<br />
print(string.len("hello"))<br />
<br />
-- international version<br />
print(utf8.len("слово"))<br />
</syntaxhighlight><br />
<br />
==string.lower, utf8.lower==<br />
;string.lower(string) or utf8.lower(string)<br />
;<nowiki>mystring:lower()</nowiki><br />
:Receives a string and returns a copy of this string with all uppercase letters changed to lowercase. All other characters are left unchanged. The definition of what an uppercase letter is depends on the current locale.<br />
: string.lower() works with English text only, use utf8.lower() for the international version.<br />
: See also: [[#string.upper.2C_utf8.upper|string.upper]], [[#string.upper.2C_utf8.upper|utf8.upper]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- prints an all-lowercase version<br />
print(string.lower("No way! This is AWESOME!"))<br />
<br />
-- international version<br />
print(utf8.lower("Класс! Ето ОТЛИЧНО!"))<br />
</syntaxhighlight><br />
<br />
==string.match, utf8.match==<br />
;string.match(text, pattern [, init]) or utf8.match()<br />
: Looks for the first match of pattern in the string text. If it finds one, then match returns the captures from the pattern; otherwise it returns nil. If pattern specifies no captures, then the whole match is returned. A third, optional numerical argument init specifies where to start the search; its default value is 1 and can be negative.<br />
: string.match() works with English text only, use utf8.match() for the international version.<br />
;Example<br />
''Need example''<br />
<br />
== string.patternEscape, utf8.patternEscape==<br />
;escapedString = string.patternEscape(str) or escapedString = utf8.patternEscape(str)<br />
<br />
:Returns a version of str with all Lua pattern characters escaped to ensure string.match/find/etc look for the original str.<br />
<br />
;See also:[[Manual:Lua_Functions#string.trim|string.trim()]], [[Manual:Lua_Functions#string.genNocasePattern|string.genNocasePattern()]]<br />
<br />
{{MudletVersion|4.15}}<br />
<br />
;Parameters<br />
*''str:''<br />
:The string to escape lua pattern characters in.<br />
<br />
;Returns<br />
*The string with all special Lua pattern characters escaped.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- searching for a url inside of a string. <br />
local helpString = [[<br />
This feature can be accessed by going to https://some-url.com/athing.html?param=value and<br />
retrieving the result!<br />
]]<br />
local url = "https://some-url.com/"<br />
display(helpString:find(url))<br />
-- nil<br />
display(helpString:find(string.patternEscape(url)))<br />
-- 42<br />
-- 62<br />
display(url:patternEscape())<br />
-- "https://some%-url%.com/"<br />
</syntaxhighlight><br />
<br />
==string.rep==<br />
;string.rep(String, n)<br />
;<nowiki>mystring:rep(n)</nowiki><br />
: Returns a string that is the concatenation of <code>n</code> copies of the string <code>String</code>.<br />
: string.rep() works with both English and non-English text fine.<br />
<br />
;Example<br />
<syntaxhighlight lang=lua><br />
-- repeat * 10 times<br />
display(string.rep("*", 10))<br />
-- results in:<br />
**********<br />
<br />
-- do the same thing, but this time calling from a variable<br />
s = "*"<br />
display(s:rep(10))<br />
-- results in:<br />
**********<br />
</syntaxhighlight><br />
<br />
==string.reverse, utf8.reverse==<br />
;string.reverse(string) or utf8.reverse(string)<br />
;<nowiki>mystring:reverse()</nowiki><br />
<br />
: Returns a string that is the string <code>string</code> reversed.<br />
: string.reverse() works with English text only, use utf8.reverse() for the international version.<br />
<br />
;Parameters:<br />
* ''string:''<br />
:The string to reverse. Passed as a string.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
mystring = "Hello from Lua"<br />
echo(mystring:reverse()) -- displays 'auL morf olleH'<br />
<br />
-- international version.<br />
mystring = "Привет от Луа!"<br />
echo(utf8.reverse(mystring)) -- displays '!ауЛ то тевирП', which probably looks the same to you<br />
</syntaxhighlight><br />
<br />
==string.split==<br />
;string.split(string, delimiter)<br />
;<nowiki>myString:split(delimiter)</nowiki><br />
: Splits a string into a table by the given delimiter. Can be called against a string (or variable holding a string) using the second form above.<br />
: Returns a table containing the split sections of the string.<br />
<br />
;Parameters:<br />
* ''string:''<br />
: The string to split. Parameter is not needed if using second form of the syntax above. Passed as a string.<br />
* ''delimiter:''<br />
: The delimiter to use when splitting the string. Passed as a string, and allows for [http://www.lua.org/pil/20.2.html Lua pattern types]. Use % to escape here (and %% to escape a stand-alone %).<br />
{{ Note }} as of Mudlet 4.7+, delimiter will default to " " if not provided.<br />
<br />
{{ Note }} as of Mudlet 4.7+, using "" (empty string) for the delimiter will return the string as a table of characters. IE string.split("This","") will return as {"T", "h", "i", "s"}. Prior to 4.7 using empty string as the delimiter would error after hanging temporarily.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- This will split the string by ", " delimiter and print the resulting table to the main window.<br />
names = "Alice, Bob, Peter"<br />
name_table = string.split(names, ", ")<br />
display(name_table)<br />
<br />
--The alternate method<br />
names = "Alice, Bob, Peter"<br />
name_table = names:split(", ")<br />
display(name_table)<br />
</syntaxhighlight><br />
<br />
:Either method above will print out:<br />
: table {<br />
:: 1: 'Alice'<br />
:: 2: 'Bob'<br />
:: 3: 'Peter'<br />
: }<br />
<br />
==string.starts==<br />
;string.starts(string, prefix)<br />
: Test if string is starting with specified prefix.<br />
: Returns true or false<br />
: See also: [[#string.ends|string.ends]]<br />
<br />
;Parameters:<br />
* ''string:''<br />
: The string to test. Passed as a string.<br />
* ''prefix:''<br />
: The prefix to test for. Passed as a string.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--The following will see if the line begins with "You" and if so will print a statement at the end of the line<br />
if string.starts(line, "You") then<br />
echo("====oh you====\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==string.sub, utf8.sub==<br />
;string.sub(text, i [, j]) or utf8.sub()<br />
: Returns the substring of text that starts at i and continues until j; i and j can be negative. If j is absent, then it is assumed to be equal to -1 (which is the same as the string length). In particular, the call string.sub(text,1,j) returns a prefix of text with length j, and string.sub(text, -i) returns a suffix of text with length i.<br />
: string.sub() works with English text only, use utf8.sub() for the international version.<br />
;Example<br />
''Need example''<br />
<br />
==string.title==<br />
;string.title(string)<br />
;<nowiki>mystring:title()</nowiki><br />
: Capitalizes the first character in a string.<br />
: Returns the altered string.<br />
<br />
;Parameters:<br />
* ''string:''<br />
: The string to modify. Not needed if you use the second form of the syntax above.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
--Variable testname is now Anna.<br />
testname = string.title("anna")<br />
--Example will set test to "Bob".<br />
test = "bob"<br />
test = test:title()<br />
</syntaxhighlight><br />
<br />
==string.trim==<br />
;string.trim(string)<br />
: Trims string, removing all 'extra' white space at the beginning and end of the text.<br />
: Returns the altered string.<br />
<br />
;Parameters:<br />
* ''string:''<br />
: The string to trim. Passed as a string.<br />
<br />
;Example:<br />
<syntaxhighlight lang="lua"><br />
--This will print 'Troll is here!', without the extra spaces.<br />
local str = string.trim(" Troll is here! ")<br />
echo("'" .. str .. "'")<br />
</syntaxhighlight><br />
<br />
==string.upper, utf8.upper==<br />
;string.upper(string) or utf8.upper(string)<br />
;<nowiki>mystring:upper()</nowiki><br />
: Receives a string and returns a copy of this string with all lowercase letters changed to uppercase. All other characters are left unchanged. The definition of what a lowercase letter is depends on the current locale.<br />
: string.upper() works with English text only, use utf8.upper() for the international version.<br />
<br />
: See also: [[#string.lower.2C_utf8.lower|string.lower]], [[#string.lower.2C_utf8.lower|utf8.lower]]<br />
<br />
;Parameters<br />
* ''string:''<br />
: The string you want to change to uppercase<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- displays 'RUN BOB RUN'<br />
print(string.upper("run bob run"))<br />
<br />
-- displays 'ДАВАЙ ДАВАЙ!'<br />
print(utf8.upper("давай давай!"))<br />
</syntaxhighlight><br />
<br />
==utf8.charpos==<br />
;utf8.charpos(string[[, charpos], offset])<br />
: Converts UTF-8 position to byte offset, returns the character position and code point. If only offset is given, returns byte offset of this UTF-8 char index. If charpos and offset is given, a new charpos will be calculated by adding/subtracting UTF-8 char offset to current charpos. In all cases, it return a new char position, and code point (a number) at this position.<br />
<br />
;Parameters<br />
* ''string:''<br />
: The input string to work on.<br />
* ''charpos:''<br />
: (optional) character position to work on.<br />
* ''offset:''<br />
: (optional) offset (as a number) to work on.<br />
<br />
==utf8.escape==<br />
;utf8.escape(string)<br />
: Escape a string to UTF-8 format string. It support several escape formats:<br />
<br />
%ddd - which ddd is a decimal number at any length:<br />
change Unicode code point to UTF-8 format.<br />
%{ddd} - same as %nnn but has bracket around.<br />
%uddd - same as %ddd, u stands Unicode<br />
%u{ddd} - same as %{ddd}<br />
%xhhh - hexadigit version of %ddd<br />
%x{hhh} same as %xhhh.<br />
%? - '?' stands for any other character: escape this character.<br />
<br />
;Parameters<br />
* ''string:''<br />
: The string you want to escape<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local u = utf8.escape<br />
print(u"%123%u123%{123}%u{123}%xABC%x{ABC}")<br />
print(u"%%123%?%d%%u")<br />
</syntaxhighlight><br />
<br />
==utf8.fold==<br />
;utf8.fold(string)<br />
: Returns the lowercase version of the string for use in case-insensitive comparisons. If string is a number, it's treated as a code point and the converted code point is returned (as a number).<br />
<br />
;Parameters<br />
* ''string:''<br />
: The string to lowercase.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
print(utf8.fold("ПРИВЕТ")) -- 'привет'<br />
print(utf8.fold("Привет")) -- 'привет'<br />
</syntaxhighlight><br />
<br />
==utf8.insert==<br />
;utf8.insert(string[, idx], substring)<br />
: Inserts the substring into the given string. If idx is given, inserts substring before the character at this index, otherwise the substring will append onto the end of string. idx can be negative.<br />
<br />
;Parameters<br />
* ''string:''<br />
: The input string to work on.<br />
* ''idx:''<br />
: (optional) character position to insert the string at.<br />
* ''substring:''<br />
: text to insert into the substring.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- inserts letter я before the 2nd letter and prints 'мясо'<br />
print(utf8.insert("мсо", 2, "я"))<br />
</syntaxhighlight><br />
<br />
==utf8.ncasecmp==<br />
;utf8.ncasecmp(a, b)<br />
: Compares ''a'' and ''b'' without case. Return -1 means a < b, 0 means a == b and 1 means a > b.<br />
<br />
;Parameters<br />
* ''a:''<br />
: String to compare.<br />
* ''b:''<br />
: String to compare against.<br />
<br />
==utf8.next==<br />
;utf8.next(string[, charpos[, offset]])<br />
: Iterates though the UTF-8 string.<br />
<br />
;Parameters<br />
* ''string:''<br />
: The input string to work on.<br />
* ''charpos:''<br />
: (optional) character position to work on.<br />
* ''offset:''<br />
: (optional) offset (as a number) to work on.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- prints location and code point of every letter<br />
for pos, code in utf8.next, "тут есть текст" do<br />
print(pos, code)<br />
end<br />
</syntaxhighlight><br />
<br />
==utf8.remove==<br />
;utf8.remove(string[, start[, stop]])<br />
: Removes characters from the given string. Deletes characters from the given ''start'' to the end of the string. If ''stop'' is given, deletes characters from ''start'' to ''stop'' (including start and stop). ''start'' and ''stop'' can be negative.<br />
<br />
;Parameters<br />
* ''string:''<br />
: The input string to work on.<br />
* ''start:''<br />
: position to start deleting characters from.<br />
* ''stop:''<br />
: (optional) posititon to stop deleting characters at.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- delete everything from the 3rd character including the character itself<br />
print(utf8.remove("мясо", 3)) -- 'мя'<br />
<br />
-- delete the last character, use negative to count backwards<br />
print(utf8.remove("мясо", -1)) -- 'мяс'<br />
<br />
-- delete everything from the 2nd to the 4th character<br />
print(utf8.remove("вкусное", 2,4)) -- 'вное'<br />
</syntaxhighlight><br />
<br />
==utf8.title==<br />
;utf8.title(string)<br />
: Returns the uppercase version of the string for use in case-insensitive comparisons. If string is a number, it's treated as a code point and the converted code point is returned (as a number).<br />
<br />
;Parameters<br />
* ''string:''<br />
: The string to uppercase.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
print(utf8.title("привет")) -- 'ПРИВЕТ'<br />
print(utf8.title("Привет")) -- 'ПРИВЕТ'<br />
</syntaxhighlight><br />
<br />
==utf8.width==<br />
;utf8.width(string[, ambi_is_double[, default_width]])<br />
: Calculate the widths of the given string. If the string is a code point, return the width of this code point.<br />
<br />
;Parameters<br />
* ''string:''<br />
: The input string to work on.<br />
* ''ambi_is_double:''<br />
: (optional) if provided, the ambiguous width character's width is 2, otherwise it's 1.<br />
* ''default_width:''<br />
: (optional) if provided, this will be the width of unprintable character, used display a non-character mark for these characters.<br />
<br />
==utf8.widthindex==<br />
;utf8.widthindex(string, location[, ambi_is_double[, default_width]])<br />
: Returns the character index at the location in the given string as well as the offset and the width. This is a reverse operation of utf8.width().<br />
<br />
;Parameters<br />
* ''string:''<br />
: The input string to work on.<br />
* ''location:''<br />
: location to get the width of.<br />
* ''ambi_is_double:''<br />
: (optional) if provided, the ambiguous width character's width is 2, otherwise it's 1.<br />
* ''default_width:''<br />
: (optional) if provided, this will be the width of unprintable character, used display a non-character mark for these characters.<br />
<br />
[[Category:Mudlet Manual]]<br />
[[Category:Mudlet API]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Basic_Essentials&diff=20305Manual:Basic Essentials2023-02-05T19:16:01Z<p>Kebap: colour -> color</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Mudlet API documentation for basic functions like send, echo, display and debugc.}}<br />
= Basic Essentials =<br />
These functions are generic functions used in normal scripting. These deal with mainly everyday things, like sending stuff and echoing to the screen.<br />
<br />
==debugc==<br />
;debugc(content)<br />
:Again this will not send anything to anywhere. It will however print not to the main window, but only to the errors view. You need to open that window to see the message.<br />
<br />
:See also: [[Manual:Introduction#Runtime_errors_aka_Errors_View|Errors View]]<br />
<br />
{{note}} Do not use this to display information to end-users. It will be hard to find. It is mainly useful for developing/debugging. Does not echo to the debug window<br />
<br />
<syntaxhighlight lang="lua"><br />
debugc(" Trigger successful!")<br />
-- Text will be shown in errors view, not to main window.<br />
</syntaxhighlight><br />
<br />
==display==<br />
;display(content)<br />
:This is much like echo, in that is will show text at your screen, not send anything to anywhere. However, it also works with other objects than just text, like a number, table, function, or even many arguments at once. This function is useful to easily take a look at the values of a lua table, for example. If a value is a string of letters, it'll be in quotes, and if it's a number, it won't be quoted.<br />
<br />
{{note}} Do not use this to display information to end-users. It may be hard to read. It is mainly useful for developing/debugging.<br />
<br />
<syntaxhighlight lang="lua"><br />
myTable = {} -- create an empty lua table<br />
myTable.foo = "Hello there" -- add a text<br />
myTable.bar = 23 -- add a number<br />
myTable.ubar = function () echo("OK") end -- add more stuff<br />
display( myTable ) -- take a look inside the table<br />
</syntaxhighlight><br />
<br />
==echo==<br />
;echo([miniconsoleName or labelName], text)<br />
:This function appends text at the end of the current line.<br />
<br />
;Parameters <br />
* ''miniconsoleName:'' (optional) the miniconsole to echo to, or:<br />
* ''labelName:'' (optional) the label to echo to.<br />
* ''text:'' text you'd like to see printed. You can use \n in an echo to insert a new line. If you're echoing this to a label, you can also use styling to color, center, increase/decrease size of text and various other formatting options [http://doc.qt.io/qt-5/richtext-html-subset.html as listed here].<br />
<br />
See also: [[Manual:Lua_Functions#moveCursor|moveCursor()]], [[Manual:Lua_Functions#insertText|insertText()]], [[Manual:Lua_Functions#cecho|cecho()]], [[Manual:Lua_Functions#decho|decho()]], [[Manual:Lua_Functions#hecho|hecho()]]<br />
<br />
As of Mudlet 4.8+, a single line is capped to 10,000 characters (this is when ~200 at most will fit on one line on your screen).<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- a miniconsole example<br />
<br />
-- first, determine the size of your screen<br />
local windowWidth, windowHeight = getMainWindowSize()<br />
<br />
-- create the miniconsole<br />
createMiniConsole("sys", windowWidth-650,0,650,300)<br />
setBackgroundColor("sys",255,69,0,255)<br />
setMiniConsoleFontSize("sys", 8)<br />
-- wrap lines in window "sys" at 40 characters per line - somewhere halfway, as an example<br />
setWindowWrap("sys", 40)<br />
<br />
echo("sys","Hello world!\n")<br />
cecho("sys", "<:OrangeRed>This is random spam with the same background\n")<br />
cecho("sys", "<blue:OrangeRed>and this is with a blue foreground. ")<br />
cecho("sys", "<bisque:BlueViolet>Lastly, this is with both a foreground and a background.\n")<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- a label example<br />
<br />
-- This example creates a transparent overlay message box to show a big warning message "You are under attack!" in the middle <br />
-- of the screen. Because the background color has a transparency level of 150 (0-255, with 0 being completely transparent <br />
-- and 255 opaque) the background text can still be read through.<br />
local width, height = getMainWindowSize()<br />
createLabel("messageBox",(width/2)-300,(height/2)-100,250,150,1)<br />
resizeWindow("messageBox",500,70)<br />
moveWindow("messageBox", (width/2)-300,(height/2)-100 )<br />
setBackgroundColor("messageBox", 255, 204, 0, 200)<br />
echo("messageBox", [[<p style="font-size:35px"><b><center><font color="red">You are under attack!</font></center></b></p>]])<br />
</syntaxhighlight><br />
<br />
==printDebug==<br />
; printDebug(msg, [showStackTrace])<br />
<br />
:Prints a debug message in green to the error console in the script editor only. Does not echo to the debug window or the main console. Includes stack trace if showStackTrace is included and not nil or false.<br />
<br />
;See also: [[Manual:Lua_Functions#printError|printError]], [[Manual:Lua_Functions#debugc|debugc]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
{{note}} This will not be echoed to the main console even if the option to echo Lua errors to the main console is turned on. Does not echo to the debug window. As such you can use it for debugging information without fear it will be shown unless someone goes looking for errors.<br />
<br />
;Parameters<br />
* ''msg:''<br />
: string to echo to the error console<br />
* ''showStackTrace:''<br />
: (optional) boolean true if you want to include the stack trace, leave off if you do not.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- print a debug message to the error console for troubleshooting purposes, when you don't want to echo the information to the main screen.<br />
-- the only difference between this and debugc is this includes information on the script/alias/trigger/etc and line it was called from, whereas debugc does not.<br />
printDebug("Switching to chaos mode")<br />
<br />
-- Want to record that something occurred, and include stacktrace so you can see what path the code was taking, but you don't want to halt execution or have it show up in main screen or in scary red.<br />
printDebug("Something unexpected occurred but we can recover from it. Still, we want to be able to notice and troubleshoot it with extra information.", true)<br />
</syntaxhighlight><br />
<br />
==printError==<br />
; printError(msg, [showStackTrace], [haltExecution])<br />
<br />
:Prints an error message in red to the error console in the script editor. Can optionally include stacktrace information and halt execution.<br />
<br />
;See also: [[Manual:Lua_Functions#printDebug|printDebug]], [[Manual:Lua_Functions#debugc|debugc]]<br />
<br />
{{MudletVersion|4.14}}<br />
<br />
{{note}} This WILL be echoed to the main console if the option to echo Lua errors to the main console is turned on. You should not use this for idle debugging information, but actual errors that may put big red error lines in the main window.<br />
<br />
;Parameters<br />
* ''msg:''<br />
: string to echo to the error console<br />
* ''showStackTrace:''<br />
: (optional) true if you want to include the stack trace, leave off if you do not.<br />
* ''haltExecution:''<br />
: (optional) true if you want to halt execution. You must pass a value for showStackTrace in order to halt execution.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- print an error message but do not include extra stack information or halt execution.<br />
-- this is similar to debugc except it include more information on the place it was called from<br />
-- and will show up in red and echo to the main console if the option for errors to echo there is selected.<br />
printError("Your maxhp is below your currenthp and our game doesn't allow for that. HAX?!")<br />
<br />
-- Something bad happened, for sure, but your script can recover.<br />
-- Make sure this is something important enough it might make it to the main window as a big red error.<br />
-- but we are not halting execution, since we can carry on in some capacity<br />
printError("gmcp values for this thing went missing, will carry on using defaults but you should tell somebody about this.", true)<br />
<br />
-- print an error message to the error console for troubleshooting purposes. <br />
-- Prints stack trace for troubleshooting and halts execution (because you cannot continue without the configuration, presumably)<br />
-- similar to using error(msg) but includes the stacktrace information.<br />
printError("Our entire configuration seems to have gone missing!", true, true)<br />
<br />
</syntaxhighlight><br />
<br />
==send==<br />
;send(command, showOnScreen)<br />
:This sends "command" directly to the network layer, skipping the alias matching. The optional second argument of type boolean (print) determines if the outgoing command is to be echoed on the screen.<br />
<br />
See also: [[Manual:Lua Functions#sendAll|sendAll()]], [[Manual:Lua_Functions#speedwalk|speedwalk()]]<br />
<br />
{{note}} If you want your command to be checked as if it's an alias, use [[Manual:Miscellaneous Functions#expandAlias|expandAlias()]] instead - send() will ignore them.<br />
<br />
<syntaxhighlight lang="lua"><br />
send("Hello Jane") --echos the command on the screen<br />
send("Hello Jane", true) --echos the command on the screen<br />
send("Hello Jane", false) --does not echo the command on the screen<br />
<br />
-- use a variable in the send:<br />
send("kick "..target)<br />
<br />
-- to send directions:<br />
speedwalk("s;s;w;w;w;w;w;w;w;")<br />
<br />
-- to send many things:<br />
sendAll("hi", "open door e", "e", "get item", "sit")<br />
</syntaxhighlight><br />
<br />
{{note}} The game server can choose not to show commands sent on screen (for example, if you're typing in a password).<br />
<br />
<br />
[[Category:Mudlet API]]<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Area_51/Mapping_script&diff=20304Area 51/Mapping script2023-02-01T21:01:19Z<p>Kebap: Hint on status of Mapping script</p>
<hr />
<div>This was on [[Mapping_script]] and currently the PR for it is not accepted.<br />
<br />
[https://github.com/Mudlet/Mudlet/pull/4347 4347] - PR accidentally accepted on wrong branch<br />
<br />
[https://github.com/Mudlet/Mudlet/pull/5456 5456] - PR to add it to development branch<br />
<br />
Might need to change this if it gets reworked into the mapper script, or uses new functions instead of room user data. Either way, this isn't currently implemented even on the public test build.<br />
<br />
[[User:Atari2600tim|Atari2600tim]] ([[User talk:Atari2600tim|talk]]) 14:00, 6 October 2022 (UTC)<br />
<br />
Meanwhile [[Mapping_script]] was merged into [[Manual:Mapper]] so kindly continue there eventually. --[[User:Kebap|Kebap]] ([[User talk:Kebap|talk]])<br />
<br />
=Draw area exit names=<br />
<br />
When a room connect to another area's room, draw the exit area name on the line end.<br />
<br />
*To not show area names in a room<br />
<syntaxhighlight lang="lua"><br />
-- don't show exit:<br />
setRoomUserData(roomid, "room.ui_dontShowAreaExitName", "yes")<br />
</syntaxhighlight><br />
*To move normal exit name a little bit<br />
<syntaxhighlight lang="lua"><br />
-- move normal exit a little bit<br />
setRoomUserData(roomid, "room.ui_areaExitNameOffset.south", "20")<br />
setRoomUserData(roomid, "room.ui_areaExitNameOffset.south", "20 20")<br />
</syntaxhighlight><br />
*To move special exit a little bit<br />
<syntaxhighlight lang="lua"><br />
-- move special exit a little bit<br />
setRoomUserData(roomid, "room.ui_areaExitNameOffset.northdown", "20")<br />
setRoomUserData(roomid, "room.ui_areaExitNameOffset.northup", "20 20")<br />
</syntaxhighlight></div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Mapper_Functions&diff=20303Manual:Mapper Functions2023-02-01T20:53:50Z<p>Kebap: Redirect outdated links to Manual:Mapper</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Mudlet API documentation for functions that manipulate the mapper and its related features.}}<br />
= Mapper Functions =<br />
These are functions that are to be used with the Mudlet Mapper. The mapper is designed to be generic - it only provides the display and pathway calculations, to be used in Lua scripts that are tailored to the game you're playing. For a collection of pre-made scripts and general mapper talk, visit the [http://forums.mudlet.org/viewforum.php?f=13 mapper section] of the forums.<br />
<br />
To register a script as a mapping one with Mudlet (so Mudlet knows the profile has one and won't bother the user when they open the map), please do this in your script:<br />
<syntaxhighlight lang="lua"><br />
mudlet = mudlet or {}; mudlet.mapper_script = true<br />
</syntaxhighlight><br />
<br />
==addAreaName==<br />
;areaID = addAreaName(areaName)<br />
<br />
:Adds a new area name and returns the new (positive) area ID for the new name. If the name already exists, older versions of Mudlet returned -1 though since 3.0 the code will return ''nil'' and an error message.<br />
: See also: [[#deleteArea|deleteArea()]], [[#addRoom|addRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local newId, err = addAreaName(string.random(10))<br />
<br />
if newId == nil or newId < 1 or err then<br />
echo("That area name could not be added - error is: ".. err.."\n")<br />
else<br />
cecho("<green>Created new area with the ID of "..newId..".\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==addCustomLine==<br />
;addCustomLine(roomID, id_to, direction, style, color, arrow)<br />
: See also: [[#getCustomLines|getCustomLines()]], [[#removeCustomLine|removeCustomLine()]]<br />
<br />
:Adds a new/replaces an existing custom exit line to the 2D mapper for the room with the Id given.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to attach the custom line to.<br />
* ''id_to:''<br />
: EITHER: a room Id number, of a room on same area who's x and y coordinates are used as the other end of a SINGLE segment custom line (it does NOT imply that is what the exit it represent goes to, just the location of the end of the line);<br />
: OR: a table of sets of THREE (x,y and z) coordinates in that order, x and y can be decimals, z is an integer ('''and must be present and be the same for all points on the line''', though it is irrelevant to what is produced as the line is drawn on the same z-coordinate as the room that the line is attached to!)<br />
* ''direction:'' a string to associate the line with a valid exit direction, "n", "ne", "e", "se", "s", "sw", "w", "nw", "up", "down", "in" or "out" or a special exit (before Mudlet 3.17 this was case-sensitive and cardinal directions had to be uppercase).<br />
* ''style:'' a string, one of: "solid line", "dot line", "dash line", "dash dot line" or "dash dot dot line" exactly.<br />
* ''color:'' a table of three integers between 0 and 255 as the custom line color as the red, green and blue components in that order.<br />
* ''arrow:'' a boolean which if true will set the custom line to have an arrow on the end of the last segment.<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- create a line from roomid 1 to roomid 2<br />
addCustomLine(1, 2, "N", "dot line", {0, 255, 255}, true)<br />
<br />
addCustomLine(1, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)<br />
</syntaxhighlight><br />
<br />
A bigger example that'll create a new area and the room in it:<br />
<br />
<syntaxhighlight lang="lua"><br />
local areaid = addAreaName("my first area")<br />
local newroomid = createRoomID()<br />
addRoom(newroomid)<br />
setRoomArea(newroomid, "my first area")<br />
setRoomCoordinates(newroomid, 0, 0, 0)<br />
<br />
local otherroomid = createRoomID()<br />
addRoom(otherroomid)<br />
setRoomArea(otherroomid, "my first area")<br />
setRoomCoordinates(otherroomid, 0, 5, 0)<br />
<br />
addSpecialExit(newroomid, otherroomid, "climb Rope")<br />
addCustomLine(newroomid, {{4.5, 5.5, 3}, {4.5, 9.5, 3}, {6.0, 9.5, 3}}, "climb Rope", "dash dot dot line", {128, 128, 0}, false)<br />
<br />
centerview(newroomid)<br />
</syntaxhighlight><br />
<br />
==addMapEvent==<br />
;addMapEvent(uniquename, event name, parent, display name, arguments)<br />
<br />
:Adds a new entry to an existing mapper right-click entry. You can add one with addMapMenu. If there is no display name, it will default to the unique name (which otherwise isn't shown and is just used to differentiate this entry from others). ''event name'' is the Mudlet event that will be called when this is clicked on, and ''arguments'' will be passed to the handler function.<br />
: See also: [[#addMapMenu|addMapMenu()]], [[#removeMapEvent|removeMapEvent()]], [[#getMapEvents|getMapEvents()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite<br />
<br />
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn") <br />
</syntaxhighlight><br />
The last line will make a label "Special Room!" under the "Favorites" menu that upon clicking will raise an event with all the arguments.<br />
<br />
<syntaxhighlight lang="lua"><br />
addMapMenu("Room type")<br />
addMapEvent("markRoomsAsDeathTrap", "onMapMarkSelectedRooms", "Room type", "Mark selected rooms as Death Trap")<br />
addMapEvent("markRoomsAsOneRoom", "onMapMarkSelectedRooms", "Room type", "Mark selected rooms as single-pass")<br />
<br />
function onMapMarkSelectedRooms(event, markRoomType)<br />
local selectedRooms = getMapSelection()["rooms"]<br />
for i, val in ipairs(selectedRooms) do<br />
if markRoomType == "markRoomsAsDeathTrap" then<br />
local r, g, b = unpack(color_table.black)<br />
--death trap<br />
setRoomEnv(val, 300)<br />
--death traps Env<br />
setCustomEnvColor(300, r, g, b, 255)<br />
setRoomChar(val, "☠️")<br />
lockRoom(val, true)<br />
elseif markRoomType == "markRoomsAsOneRoom" then<br />
local r, g, b = unpack(color_table.LightCoral)<br />
--single-pass<br />
setRoomEnv(val, 301)<br />
--one room Env<br />
setCustomEnvColor(301, r, g, b, 255)<br />
setRoomChar(val, "🚹")<br />
end<br />
end<br />
updateMap()<br />
end<br />
<br />
registerAnonymousEventHandler("onMapMarkSelectedRooms", "onMapMarkSelectedRooms")<br />
</syntaxhighlight><br />
This create menu and two submenu options: "Mark selected rooms as Death Trap" and "Mark selected rooms as single-pass"<br />
<br />
==addMapMenu==<br />
;addMapMenu(uniquename, parent, display name)<br />
<br />
:Adds a new submenu to the right-click menu that opens when you right-click on the mapper. You can then add more submenus to it, or add entries with [[#addMapEvent|addMapEvent()]].<br />
: See also: [[#addMapEvent|addMapEvent()]], [[#removeMapEvent|removeMapEvent()]], [[#getMapEvents|getMapEvents()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- This will create a menu named: Favorites.<br />
addMapMenu("Favorites")<br />
<br />
-- This will create a submenu with the unique id 'Favorites123' under 'Favorites' with the display name of 'More Favorites'.<br />
addMapMenu("Favorites1234343", "Favorites", "More Favorites") <br />
</syntaxhighlight><br />
<br />
==addRoom==<br />
;addRoom(roomID)<br />
<br />
:Creates a new room with the given ID, returns true if the room was successfully created. <br />
<br />
{{note}} If you're not using incremental room IDs but room IDs stitched together from other factors or in-game hashes for room IDs - and your room IDs are starting off at 250+million numbers, you need to look into incrementally creating Mudlets room IDs with [[#createRoomID|createRoomID()]] and associating your room IDs with Mudlets via [[#setRoomIDbyHash|setRoomIDbyHash()]] and [[#getRoomIDbyHash|getRoomIDbyHash()]]. The reason being is that Mudlet's A* pathfinding implementation from boost cannot deal with extremely large room IDs because the resulting matrices it creates for pathfinding are enormously huge.<br />
{{note}} Creating your own mapping script? Check out more [[Manual:Mapper#Making_your_own_mapping_script|information here]].<br />
<br />
: See also: [[#createRoomID|createRoomID()]]<br />
<br />
;Example:<br />
<syntaxhighlight lang="lua"><br />
local newroomid = createRoomID()<br />
addRoom(newroomid)<br />
</syntaxhighlight><br />
<br />
==addSpecialExit==<br />
;addSpecialExit(roomIDFrom, roomIDTo, moveCommand)<br />
<br />
:Creates a one-way from one room to another, that will use the given command for going through them.<br />
<br />
: See also: [[#clearSpecialExits|clearSpecialExits()]], [[#removeSpecialExit|removeSpecialExit()]], [[#setExit|setExit()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- add a one-way special exit going from room 1 to room 2 using the 'pull rope' command<br />
addSpecialExit(1, 2, "pull rope")<br />
</syntaxhighlight><br />
<br />
Example in an alias:<br />
<syntaxhighlight lang="lua"><br />
-- sample alias pattern: ^spe (\d+) (.*?)$<br />
-- currentroom is your current room ID in this example<br />
addSpecialExit(currentroom,tonumber(matches[2]), matches[3])<br />
echo("\n SPECIAL EXIT ADDED TO ROOMID:"..matches[2]..", Command:"..matches[3])<br />
centerview(currentroom)<br />
</syntaxhighlight><br />
<br />
==auditAreas==<br />
;auditAreas()<br />
<br />
: Initiates a consistency check on the whole map: All rooms, areas, and their composition. This is also done automatically whenever you first open your map, so probably seldom necessary to do manually. Will output findings to screen and/or logfile for later review.<br />
<br />
: See also: [[#saveMap|saveMap()]], [[#removeMapEvent|removeMapEvent()]], [[#getMapEvents|getMapEvents()]]<br />
<br />
==centerview==<br />
;centerview (roomID)<br />
<br />
:Centers the map view onto the given room ID. The map must be open to see this take effect. This function can also be used to see the map of an area if you know the number of a room there and the area and room are mapped.<br />
<br />
: See also: [[#getPlayerRoom|getPlayerRoom()]], [[#updateMap|updateMap()]]<br />
<br />
==clearAreaUserData==<br />
;clearAreaUserData(areaID)<br />
<br />
; Parameter<br />
* areaID - ID number for area to clear.<br />
<br />
:Clears all user data from a given area. Note that this will not touch the room user data.<br />
: See also: [[#setAreaUserData|setAreaUserData()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#clearRoomUserData|clearRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearAreaUserData(34))<br />
-- I did have data in that area, so it returns:<br />
true<br />
<br />
display(clearAreaUserData(34))<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.0}}<br />
<br />
==clearAreaUserDataItem==<br />
;clearAreaUserDataItem(areaID, key)<br />
<br />
:Removes the specific key and value from the user data from a given area.<br />
: See also: [[#setAreaUserData|setAreaUserData()]], [[#clearAreaUserData|clearAreaUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllAreaUserData(34))<br />
{<br />
description = [[<area description here>]],<br />
ruler = "Queen Morgase Trakand"<br />
}<br />
<br />
display(clearAreaUserDataItem(34,"ruler"))<br />
true<br />
<br />
display(getAllAreaUserData(34))<br />
{<br />
description = [[<area description here>]],<br />
}<br />
<br />
display(clearAreaUserDataItem(34,"ruler"))<br />
false<br />
</syntaxhighlight><br />
<br />
==clearMapUserData==<br />
;clearMapUserData()<br />
<br />
:Clears all user data stored for the map itself. Note that this will not touch the area or room user data.<br />
<br />
: See also: [[#setMapUserData|setMapUserData()]], [[#clearRoomUserData|clearRoomUserData()]], [[#clearAreaUserData|clearAreaUserData()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearMapUserData())<br />
-- I did have user data stored for the map, so it returns:<br />
true<br />
<br />
display(clearMapUserData())<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
==clearMapUserDataItem==<br />
;clearMapUserDataItem(mapID, key)<br />
<br />
:Removes the specific key and value from the user data from the map user data.<br />
: See also: [[#setMapUserData|setMapUserData()]], [[#clearMapUserData|clearMapUserData()]], [[#clearAreaRoomUserData|clearAreaRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllMapUserData())<br />
{<br />
description = [[<map description here>]],<br />
last_modified = "1483228799"<br />
}<br />
<br />
display(clearMapUserDataItem("last_modified"))<br />
true<br />
<br />
display(getAllMapUserData())<br />
{<br />
description = [[<map description here>]],<br />
}<br />
<br />
display(clearMapUserDataItem("last_modified"))<br />
false<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.0}}<br />
<br />
==clearRoomUserData==<br />
;clearRoomUserData(roomID)<br />
<br />
:Clears all user data from a given room.<br />
: See also: [[#setRoomUserData|setRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]]<br />
<br />
{{note}} Returns a boolean true if any data was removed from the specified room and false if there was nothing to erase since Mudlet 3.0.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(clearRoomUserData(3441))<br />
-- I did have data in that room, so it returns:<br />
true<br />
<br />
display(clearRoomUserData(3441))<br />
-- There is no data NOW, so it returns:<br />
false<br />
</syntaxhighlight><br />
<br />
==clearRoomUserDataItem==<br />
;clearRoomUserDataItem(roomID, key)<br />
<br />
:Removes the specific key and value from the user data from a given room.<br />
:Returns a boolean true if data was found against the give key in the user data for the given room and it is removed, will return false if exact key not present in the data. Returns nil if the room for the roomID not found.<br />
: See also: [[#setRoomUserData|setRoomUserData()]], [[#clearRoomUserData|clearRoomUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllRoomUserData(3441))<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
doorname_up = "trapdoor"<br />
}<br />
<br />
display(clearRoomUserDataItem(3441,"doorname_up"))<br />
true<br />
<br />
display(getAllRoomUserData(3441))<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
}<br />
<br />
display(clearRoomUserDataItem(3441,"doorname_up"))<br />
false<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.0}}<br />
<br />
==clearSpecialExits==<br />
;clearSpecialExits(roomID) <br />
<br />
:Removes all special exits from a room.<br />
: See also: [[#addSpecialExit|addSpecialExit()]], [[#removeSpecialExit|removeSpecialExit()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
clearSpecialExits(1337)<br />
<br />
if #getSpecialExits(1337) == 0 then -- clearSpecialExits will never fail on a valid room ID, this is an example<br />
echo("All special exits successfully cleared from 1337.\n")<br />
end<br />
</syntaxhighlight><br />
<br />
==closeMapWidget==<br />
;closeMapWidget()<br />
:closes (hides) the map window (similar to clicking on the map icon)<br />
<br />
{{MudletVersion|4.7}}<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#moveMapWidget|moveMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
==connectExitStub==<br />
;connectExitStub(fromID, direction) or connectExitStub(fromID, toID, [direction])<br />
<br />
:Connects existing rooms with matching exit stubs. If you only give it a roomID and a direction, it'll work out which room should be linked to it that has an appropriate opposite exit stub and is located in the right direction. You can also just specify from and to room IDs, and it'll smartly use the right direction to link in. Lastly, you can specify all three arguments - fromID, toID and the direction (in that order) if you'd like to be explicit, or use [[#setExit|setExit()]] for the same effect.<br />
<br />
;Parameters<br />
* ''fromID:''<br />
: Room ID to set the exit stub in.<br />
* ''direction:''<br />
: You can either specify the direction to link the room in, and/or a specific room ID (see below). Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
* ''toID:''<br />
: The room ID to link this room to. If you don't specify it, the mapper will work out which room should be logically linked.<br />
<br />
: See also: [[#setExitStub|setExitStub()]], [[#getExitStubs|getExitStubs()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- try and connect all stubs that are in a room<br />
local stubs = getExitStubs(roomID)<br />
if stubs then<br />
for i,v in pairs(stubs) do<br />
connectExitStub(roomID, v)<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==createMapLabel==<br />
;labelID = createMapLabel(areaID, text, posX, posY, posZ, fgRed, fgGreen, fgBlue, bgRed, bgGreen, bgBlue[[[[[[[, zoom, fontSize], showOnTop], noScaling], fontName], foregroundTransparency], backgroundTransparency], temporary])<br />
<br />
:Creates a text label on the map at given coordinates, with the given background and foreground colors. It can go above or below the rooms, scale with zoom or stay a static size. From Mudlet 4.17.0 an additional parameter (assumed to be false if not given from then) makes the label NOT be saved in the map file which, if the image can be regenerated on future loading from a script can reduce the size of the saved map somewhat. It returns a label ID that you can use later for deleting it.<br />
<br />
:The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of [[#getRoomCoordinates|getRoomCoordinates()]] will place the label near that room.<br />
<br />
: See also: [[#getMapLabel|getMapLabel()]], [[#getMapLabels|getMapLabels()]], [[#deleteMapLabel|deleteMapLabel]], [[#createMapUmageLabel|createMapImageLabel()]]<br />
<br />
{{note}} Some changes were done prior to 4.13 (which exactly? function existed before!) - see corresponding PR and update here!<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID where to put the label.<br />
* ''text:''<br />
: The text to put into the label. To get a multiline text label add a '\n' between the lines.<br />
* ''posX, posY, posZ:''<br />
: Position of the label in (floating point numbers) room coordinates.<br />
* ''fgRed, fgGreen, fgBlue:''<br />
: Foreground color or text color of the label.<br />
* ''bgRed, bgGreen, bgBlue:''<br />
: Background color of the label.<br />
* ''zoom:''<br />
: (optional) Zoom factor of the label if noScaling is false. Higher zoom will give higher resolution of the text and smaller size of the label. Default is 30.0.<br />
* ''fontSize:''<br />
: (optional, but needed if zoom is provided) Size of the font of the text. Default is 50.<br />
* ''showOnTop:''<br />
: (optional) If true the label will be drawn on top of the rooms and if it is false the label will be drawn as a background, defaults to true if not given.<br />
* ''noScaling:''<br />
: (optional) If true the label will have the same size when you zoom in and out in the mapper, If it is false the label will scale when you zoom the mapper, defaults to true if not given.<br />
* ''fontName:''<br />
: (optional) font name to use.<br />
* ''foregroundTransparency''<br />
: (optional) transparency of the text on the label, defaults to 255 (in range of 0 to 255) or fully opaque if not given.<br />
* ''backgroundTransparency''<br />
: (optional) transparency of the label background itself, defaults to 50 (in range of 0 to 255) or significantly transparent if not given.<br />
* ''temporary''<br />
: (optional, from Mudlet version 4.17.0) if true does not save the image that the label makes in map save files, defaults to false if not given, or for prior versions of Mudlet.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- the first 50 is some area id, the next three 0,0,0 are coordinates - middle of the area<br />
-- 255,0,0 would be the foreground in RGB, 23,0,0 would be the background RGB<br />
-- zoom is only relevant when when you're using a label of a static size, so we use 0<br />
-- and we use a font size of 20 for our label, which is a small medium compared to the map<br />
local labelid = createMapLabel( 50, "my map label", 0,0,0, 255,0,0, 23,0,0, 0,20)<br />
<br />
-- to create a multi line text label we add '\n' between lines<br />
-- the position is placed somewhat to the northeast of the center of the map<br />
-- this label will be scaled as you zoom the map.<br />
local labelid = createMapLabel( 50, "1. Row One\n2. Row 2", .5,5.5,0, 255,0,0, 23,0,0, 30,50, true, false)<br />
<br />
local x,y,z = getRoomCoordinates(getPlayerRoom())<br />
createMapLabel(getRoomArea(getPlayerRoom()), "my map label", x,y,z, 255,0,0, 23,0,0, 0,20, false, true, "Ubuntu", 255, 100)<br />
</syntaxhighlight><br />
<br />
==createMapImageLabel==<br />
;labelID = createMapImageLabel(areaID, filePath, posx, posy, posz, width, height, zoom, showOnTop[, temporary])<br />
<br />
:Creates an image label on the map at the given coordinates, with the given dimensions and zoom. You might find the default room and image size correlation to be too big - try reducing the width and height of the image then, while also zooming in the same amount. From Mudlet 4.17.0 an additional parameter (assumed to be false if not given from then) makes the label NOT be saved in the map file which, if the image can be regenerated on future loading from a external file available when the map file is loaded, can avoid expanding the size of the saved map considerably.<br />
<br />
:The coordinates 0,0 are in the middle of the map, and are in sync with the room coordinates - so using the x,y values of [[#getRoomCoordinates|getRoomCoordinates()]] will place the label near that room.<br />
: See also: [[#createMapLabel|createMapLabel]], [[#deleteMapLabel|deleteMapLabel]]<br />
<br />
;Example:<br />
<syntaxhighlight lang="lua"><br />
-- 138 is our pretend area ID<br />
-- next, inside [[]]'s, is the exact location of our image<br />
-- 0,0,0 are the x,y,z coordinates - so this will place it in the middle of the map<br />
-- 482 is the width of the image - we divide it by 100 to scale it down, and then we'll zoom it by 100 - making the image take up about 4 rooms in width then<br />
-- 555 is the original height of the image<br />
-- 100 is how much we zoom it by, 1 would be no zoom<br />
-- false to make it go below our rooms<br />
-- (from 4.17.0) true to not save the label's image in the map file afterwards<br />
createMapImageLabel(138, [[/home/vadi/Pictures/You only see what shown.png]], 0,0,0, 482/100, 555/100, 100, false, true)<br />
</syntaxhighlight><br />
<br />
==createMapper==<br />
;createMapper([name of userwindow], x, y, width, height)<br />
<br />
:Creates a miniconsole window for the mapper to render in, the with the given dimensions. You can only create one mapper at a time, and it is not currently possible to have a label on or under the mapper - otherwise, clicks won't register.<br />
<br />
{{note}} ''name of userwindow'' available in Mudlet 4.6.1+<br />
<br />
{{Note}} If this command is ''not'' used then clicking on the Main Toolbar's '''Map''' button will create a dock-able widget (that can be floated free to anywhere on the Desktop, it can be resized and does not have to even reside on the same monitor should there be multiple screens in your system). Further clicks on the '''Map''' button will toggle between showing and hiding the map whether it was created using the ''createMapper'' function or as a dock-able widget.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
createMapper(0,0,300,300) -- creates a 300x300 mapper in the top-left corner of Mudlet<br />
setBorderLeft(305) -- adds a border so text doesn't underlap the mapper display<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- another example:<br />
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})<br />
<br />
local mapper = Geyser.Mapper:new({<br />
name = "mapper",<br />
x = "70%", y = 0, -- edit here if you want to move it<br />
width = "30%", height = "50%"<br />
}, main)<br />
</syntaxhighlight><br />
<br />
==createRoomID==<br />
;usableId = createRoomID([minimumStartingRoomId])<br />
<br />
:Returns the lowest possible room ID you can use for creating a new room. If there are gaps in room IDs your map uses it, this function will go through the gaps first before creating higher IDs. <br />
<br />
;Parameters<br />
* ''minimumStartingRoomId'' (optional, available in Mudlet 3.0+):<br />
: If provided, specifies a roomID to start searching for an empty one at, instead of 1. Useful if you'd like to ensure certain areas have specific room number ranges, for example. If you you're working with a huge map, provide the last used room ID to this function for an available roomID to be found a lot quicker.<br />
<br />
: See also: [[#addRoom|addRoom()]]<br />
<br />
==deleteArea==<br />
;deleteArea(areaID or areaName)<br />
<br />
:Deletes the given area and all rooms in it. Returns ''true'' on success or ''nil'' + ''error message'' otherwise.<br />
: See also: [[#addAreaName|addAreaName()]]<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID to delete, or:<br />
* ''areaName'' (available in Mudlet 3.0+):<br />
: Area name to delete.<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- delete by areaID<br />
deleteArea(23)<br />
-- or since Mudlet 3.0, by area name<br />
deleteArea("Big city")<br />
</syntaxhighlight><br />
<br />
==deleteMap==<br />
;deleteMap()<br />
<br />
Deletes the entire map. This may be useful whilst initially setting up a mapper package for a new Game to clear faulty map data generated up to this point.<br />
: See also: [[#loadMap|loadMap()]]<br />
<br />
{{MudletVersion|4.14.0}}<br />
<br />
;Returns<br />
:''true'' on success or ''nil'' and an error message on failure, if successful it will also refresh the map display to show the result - which will be the "blank" screen with a warning message of the form ''"No rooms in the map - load another one, or start mapping from scratch to begin."''<br />
<br />
{{note}} Prior to the introduction of this function, the recommended method to achieve the same result was to use [[#loadMap|loadMap()]] with a non-existent file-name, such as ''"_"'' however that would also cause an ''"[ ERROR ]"'' type message to appear on the profile's main console.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteMap()<br />
</syntaxhighlight><br />
<br />
==deleteMapLabel==<br />
;deleteMapLabel(areaID, labelID)<br />
<br />
:Deletes a map label from a specific area.<br />
: See also: [[#createMapLabel|createMapLabel()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteMapLabel(50, 1)<br />
</syntaxhighlight><br />
<br />
==deleteRoom==<br />
;deleteRoom(roomID)<br />
<br />
:Deletes an individual room, and unlinks all exits leading to and from it.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
deleteRoom(335)<br />
</syntaxhighlight><br />
<br />
==disableMapInfo==<br />
;disableMapInfo(label)<br />
<br />
Disable the particular map info - same as toggling off checkbox from select box under mapper.<br />
<br />
;Parameters<br />
* ''label:''<br />
: Name under which map info to be disabled was registered.<br />
<br />
: See also: [[#registerMapInfo|registerMapInfo()]], [[#enableMapInfo|enableMapInfo()]], [[#killMapInfo|killMapInfo()]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
==enableMapInfo==<br />
;enableMapInfo(label)<br />
<br />
Enable the particular map info - same as toggling on checkbox from select box under mapper.<br />
<br />
;Parameters<br />
* ''label:''<br />
: Name under which map info to be enabled was registered.<br />
<br />
: See also: [[#registerMapInfo|registerMapInfo()]], [[#disableMapInfo|disableMapInfo()]], [[#killMapInfo|killMapInfo()]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
==getAllAreaUserData==<br />
;dataTable = getAllAreaUserData(areaID)<br />
<br />
:Returns all the user data items stored in the given area ID; will return an empty table if there is no data stored or nil if there is no such area with that ID.<br />
<br />
: See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#searchAreaUserData|searchAreaUserData()]], [[#setAreaUserData|setAreaUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllAreaUserData(34))<br />
--might result in:--<br />
{<br />
country = "Andor",<br />
ruler = "Queen Morgase Trakand"<br />
}<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.0}}<br />
<br />
==getAllMapUserData==<br />
;dataTable = getAllMapUserData()<br />
<br />
:Returns all the user data items stored at the map level; will return an empty table if there is no data stored.<br />
<br />
: See also: [[#getMapUserData|getMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllMapUserData())<br />
--might result in:--<br />
{<br />
description = [[This map is about so and so game]],<br />
author = "Bob",<br />
["last updated"] = "December 5, 2020"<br />
}<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.0}}<br />
<br />
==getAllRoomEntrances==<br />
;exitsTable = getAllRoomEntrances(roomID)<br />
<br />
:Returns an indexed list of normal and special exits leading into this room. In case of two-way exits, this'll report exactly the same rooms as [[#getRoomExits|getRoomExits()]], but this function has the ability to pick up one-way exits coming into the room as well.<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- print the list of rooms that have exits leading into room 512<br />
for _, roomid in ipairs(getAllRoomEntrances(512)) do <br />
print(roomid)<br />
end<br />
</syntaxhighlight><br />
<br />
: See also: [[#getRoomExits|getRoomExits()]]<br />
<br />
==getAllRoomUserData==<br />
;dataTable = getAllRoomUserData(roomID)<br />
<br />
:Returns all the user data items stored in the given room ID; will return an empty table if there is no data stored or nil if there is no such room with that ID. ''Can be useful if the user was not the one who put the data in the map in the first place!''<br />
<br />
;See also: [[#getRoomUserDataKeys|getRoomUserDataKeys()]] - for a related command that only returns the data keys.<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAllRoomUserData(3441))<br />
--might result in:--<br />
{<br />
description = [[<br />
From this ledge you can see out across a large cavern to the southwest. The<br />
east side of the cavern is full of stalactites and stalagmites and other<br />
weird rock formations. The west side has a path through it and an exit to the<br />
south. The sound of falling water pervades the cavern seeming to come from<br />
every side. There is a small tunnel to your east and a stalactite within arms<br />
reach to the south. It appears to have grown till it connects with the<br />
stalagmite below it. Something smells... Yuck you are standing in bat guano!]],<br />
doorname_up = "trapdoor"<br />
}<br />
</syntaxhighlight><br />
<br />
==getAreaExits==<br />
;roomTable = getAreaExits(areaID, showExits)<br />
<br />
: Returns a table (indexed or key-value) of the rooms in the given area that have exits leading out to other areas - that is, border rooms.<br />
<br />
;See also: [[#setExit|setExit()]], [[#getRoomExits|getRoomExits()]]<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID to list the exits for.<br />
* ''showExits:''<br />
: Boolean argument, if true then the exits that lead out to another area will be listed for each room.<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- list all border rooms for area 44:<br />
getAreaExits(44)<br />
<br />
-- returns:<br />
--[[<br />
{<br />
7091,<br />
10659,<br />
11112,<br />
11122,<br />
11133,<br />
11400,<br />
12483,<br />
24012<br />
}<br />
]]<br />
<br />
-- list all border rooms for area 44, and the exits within them that go out to other areas:<br />
getAreaExits(44, true)<br />
--[[<br />
{<br />
[12483] = {<br />
north = 27278<br />
},<br />
[11122] = {<br />
["enter grate"] = 14551<br />
},<br />
[11112] = {<br />
["enter grate"] = 14829<br />
},<br />
[24012] = {<br />
north = 22413<br />
},<br />
[11400] = {<br />
south = 10577<br />
},<br />
[11133] = {<br />
["enter grate"] = 15610<br />
},<br />
[7091] = {<br />
down = 4411<br />
},<br />
[10659] = {<br />
["enter grate"] = 15510<br />
}<br />
}<br />
]]<br />
</syntaxhighlight><br />
<br />
==getAreaRooms==<br />
;getAreaRooms(area id)<br />
<br />
:Returns an indexed table with all rooms IDs for a given area ID (room IDs are values), or ''nil'' if no such area exists. <br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- using the sample findAreaID() function defined in the getAreaTable() example, <br />
-- we'll define a function that echo's us a nice list of all rooms in an area with their ID<br />
function echoRoomList(areaname)<br />
local id, msg = findAreaID(areaname)<br />
if id then<br />
local roomlist, endresult = getAreaRooms(id), {}<br />
<br />
-- obtain a room list for each of the room IDs we got<br />
for _, id in pairs(roomlist) do<br />
endresult[id] = getRoomName(id)<br />
end<br />
<br />
-- now display something half-decent looking<br />
cecho(string.format(<br />
"List of all rooms in %s (%d):\n", msg, table.size(endresult)))<br />
<br />
for roomid, roomname in pairs(endresult) do<br />
cecho(string.format(<br />
"%6s: %s\n", roomid, roomname))<br />
end<br />
elseif not id and msg then<br />
echo("ID not found; " .. msg)<br />
else<br />
echo("No areas matched the query.")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==getAreaTable==<br />
;areaTable = getAreaTable()<br />
<br />
:Returns a key(area name)-value(area id) table with all known areas and their IDs. <br />
{{Note}} Some older versions of Mudlet return an area with an empty name and an ID of 0 included in it, you should ignore that.<br />
<br />
;See also: [[#getAreaTableSwap|getAreaTableSwap()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example function that returns the area ID for a given area<br />
<br />
function findAreaID(areaname)<br />
local list = getAreaTable()<br />
<br />
-- iterate over the list of areas, matching them with substring match. <br />
-- if we get match a single area, then return it's ID, otherwise return<br />
-- 'false' and a message that there are than one are matches<br />
local returnid, fullareaname<br />
for area, id in pairs(list) do<br />
if area:find(areaname, 1, true) then<br />
if returnid then return false, "more than one area matches" end<br />
returnid = id; fullareaname = area<br />
end<br />
end<br />
<br />
return returnid, fullareaname<br />
end<br />
<br />
-- sample use:<br />
local id, msg = findAreaID("blahblah")<br />
if id then<br />
echo("Found a matching ID: " .. id)<br />
elseif not id and msg then<br />
echo("ID not found: " .. msg)<br />
else<br />
echo("No areas matched the query.")<br />
end<br />
</syntaxhighlight><br />
<br />
==getAreaTableSwap==<br />
;areaTable = getAreaTableSwap()<br />
<br />
:Returns a key(area id)-value(area name) table with all known areas and their IDs. Unlike getAreaTable which won't show you all areas with the same name by different IDs, this function will. <br />
{{Note}} Some older versions of Mudlet return an area with an empty name and an ID of 0 included in it, you should ignore that.<br />
<br />
==getAreaUserData==<br />
;dataValue = getAreaUserData(areaID, key)<br />
<br />
:Returns a specific data item stored against the given key for the given area ID number. This is very like the corresponding Room User Data command but intended for per area rather than for per room data (for storage of data relating to the whole map see the corresponding Map User Data commands.) <br />
<br />
:Returns the user data value (string) stored at a given room with a given key (string), or a Lua ''nil'' and an error message if the key is not present in the Area User Data for the given Area ID. Use [[#setAreaUserData|setAreaUserData()]] function for storing the user data.<br />
<br />
;See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#searchAreaUserData|searchAreaUserData()]], [[#setAreaUserData|setAreaUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getAreaUserData(34, "country"))<br />
-- might produce --<br />
"Andor"<br />
</syntaxhighlight><br />
<br />
==getCustomEnvColorTable==<br />
;envcolors = getCustomEnvColorTable()<br />
<br />
:Returns a table with customized environments, where the key is the environment ID and the value is a indexed table of rgb values.<br />
: See also: [[#setCustomEnvColor|setCustomEnvColor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
{<br />
envid1 = {r, g, b, alpha},<br />
envid2 = {r, g, b, alpha}<br />
}<br />
</syntaxhighlight><br />
<br />
==getCustomLines==<br />
;lineTable = getCustomLines(roomID)<br />
: See also: [[#addCustomLine|addCustomLine()]], [[#removeCustomLine|removeCustomLine()]]<br />
<br />
:Returns a table including all the details of the custom exit lines, if any, for the room with the id given.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to return the custom line details of.<br />
<br />
{{MudletVersion|3.0.}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display getCustomLines(1)<br />
{<br />
["climb Rope"] = {<br />
attributes = {<br />
color = {<br />
b = 0,<br />
g = 128,<br />
r = 128<br />
},<br />
style = "dash dot dot line",<br />
arrow = false<br />
},<br />
points = {<br />
{<br />
y = 9.5,<br />
x = 4.5<br />
},<br />
{<br />
y = 9.5,<br />
x = 6<br />
},<br />
[0] = {<br />
y = 5.5,<br />
x = 4.5<br />
}<br />
}<br />
},<br />
N = {<br />
attributes = {<br />
color = {<br />
b = 255,<br />
g = 255,<br />
r = 0<br />
},<br />
style = "dot line",<br />
arrow = true<br />
},<br />
points = {<br />
[0] = {<br />
y = 27,<br />
x = -3<br />
}<br />
}<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
==getCustomLines1==<br />
;lineTable = getCustomLines1(roomID)<br />
This is a replacement for ''getCustomLines(...)'' that outputs the tables for the coordinates for the points on the custom line in an order and format that can be fed straight back into an ''addCustomLine(...)'' call; similarly the color parameters are also reported in the correct format to also be reused in the same manner. This function is intended to make it simpler for scripts to manipulate such lines.<br />
:See also: [[Manual:Mapper_Functions#addCustomLine|addCustomLine()]], [[Manual:Mapper_Functions#removeCustomLine|removeCustomLine()]], [[Manual:Mapper_Functions#getCustomLines|getCustomLines()]]<br />
{{MudletVersion| 4.16}}<br />
<br />
;Parameters<br />
* ''roomID:''<br />
:Room ID to return the custom line details of.<br />
<br />
;Returns<br />
:a table including all the details of the custom exit lines, if any, for the room with the id given.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display getCustomLines1(1)<br />
{<br />
["climb Rope"] = {<br />
attributes = {<br />
color = { 128, 128, 0 },<br />
style = "dash dot dot line",<br />
arrow = false<br />
},<br />
points = { { 4.5, 5.5, 3 }, { 4.5, 9.5, 3 }, { 6, 9.5, 3 } } <br />
},<br />
N = {<br />
attributes = {<br />
color = { 0, 255, 255 },<br />
style = "dot line",<br />
arrow = true<br />
},<br />
points = { { -3, 27, 3 } }<br />
}<br />
}<br />
</syntaxhighlight><br />
<br />
==getDoors==<br />
;doors = getDoors(roomID)<br />
<br />
:Returns a key-value table with the cardinal direction as the key and the door value as a number. If there are no doors in a room, it returns an empty table.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to check for doors in.<br />
<br />
: See also: [[#setDoor|setDoor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- an example that displays possible doors in room 2334<br />
local doors = getDoors(2334)<br />
<br />
if not next(doors) then cecho("\nThere aren't any doors in room 2334.") return end<br />
<br />
local door_status = {"open", "closed", "locked"}<br />
<br />
for direction, door in pairs(doors) do<br />
cecho("\nThere's a door leading in "..direction.." that is "..door_status[door]..".")<br />
end<br />
</syntaxhighlight><br />
<br />
==getExitStubs==<br />
;stubs = getExitStubs(roomid)<br />
<br />
:Returns an indexed table (starting at 0) of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping.<br />
<br />
: See also: [[#setExitStub|setExitStub()]], [[#connectExitStub|connectExitStub()]], [[#getExitStubs1|getExitStubs1()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- show the exit stubs in room 6 as numbers<br />
local stubs = getExitStubs(6)<br />
for i = 0, #stubs do print(stubs[i]) end<br />
</syntaxhighlight><br />
<br />
{{note}} Previously would throw a lua error on non-existent room - now returns nil plus error message (as does other run-time errors) - previously would return just a nil on NO exit stubs but now returns a notification error message as well, to aide disambiguation of the nil value.<br />
<br />
==getExitStubs1==<br />
;stubs = getExitStubs1(roomid)<br />
<br />
:Returns an indexed table (starting at 1) of the direction #'s that have an exit stub marked in them. You can use this information to connect earlier-made exit stubs between rooms when mapping. As this function starts indexing from 1 as it is default in Lua, you can use ipairs() to iterate over the results.<br />
<br />
; See also: [[#getExitStubs|getExitStubs()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- show the exit stubs in room 6 as numbers<br />
for k,v in ipairs(getExitStubs1(6)) do print(k,v) end<br />
</syntaxhighlight><br />
<br />
==getExitWeights==<br />
;weights = getExitWeights(roomid)<br />
<br />
:Returns a key-value table of the exit weights that a room has, with the direction or special exit as a key and the value as the exit weight. If a weight for a direction wasn't yet set, it won't be listed.<br />
<br />
;Parameters<br />
* ''roomid:''<br />
: Room ID to view the exit weights in.<br />
<br />
: See also: [[#setExitWeight|setExitWeight()]]<br />
<br />
==getGridMode==<br />
;TrueOrFalse = getGridMode(areaID)<br />
<br />
:Use this to see, if a specific area has grid/wilderness view mode set. This way, you can also calculate from a script, how many grid areas a map has got in total.<br />
<br />
{{MudletVersion|3.11}}<br />
<br />
;Parameters<br />
* ''areaID:''<br />
: Area ID (number) to view the grid mode of.<br />
<br />
: See also: [[#setGridMode|setGridMode()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
getGridMode(55)<br />
-- will return: false<br />
setGridMode(55, true) -- set area with ID 55 to be in grid mode<br />
getGridMode(55)<br />
-- will return: true<br />
</syntaxhighlight><br />
<br />
==getMapEvents==<br />
; mapevents = getMapEvents()<br />
<br />
: Returns a list of map events currently registered. Each event is a dictionary with the keys ''uniquename'', ''parent'', ''event name'', ''display name'', and ''arguments'', which correspond to the arguments of ''addMapEvent()''.<br />
: See also: [[#addMapMenu|addMapMenu()]], [[#removeMapEvent|removeMapEvent()]], [[#addMapEvent|addMapEvent()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- will make a label "room a" on the map menu's right click that calls onFavorite<br />
<br />
addMapEvent("room b", "onFavorite", "Favorites", "Special Room!", 12345, "arg1", "arg2", "argn")<br />
<br />
local mapEvents = getMapEvents()<br />
for _, event in ipairs(mapEvents) do<br />
echo(string.format("MapEvent '%s' is bound to event '%s' with these args: '%s'", event["uniquename"], event["event name"], table.concat(event["arguments"], ",")))<br />
end<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.3}}<br />
<br />
==getMapLabel==<br />
;labelinfo = getMapLabel(areaID, labelID or labelText)<br />
<br />
:Returns a key-value table describing that particular label in an area. Keys it contains are the ''X'', ''Y'', ''Z'' coordinates, ''Height'' and ''Width'', ''BgColor'', ''FgColor'', ''Pixmap'', and the ''Text'' it contains. If the label is an image label, then ''Text'' will be set to the ''no text'' string.<br />
<br />
:''BgColor'' and ''FgColor'' are tables with ''r'',''g'',''b'' keys, each holding ''0-255'' color component value.<br />
<br />
:''Pixmap'' is base64 encoded image of label.<br />
<br />
{{note}} ''BgColor'', ''FgColor'', ''Pixmap'' are available in Mudlet 4.11+<br />
<br />
;Parameters <br />
* ''areaID:'' areaID from which to retrieve label<br />
* ''labelID:'' labelID (''getMapLabels'' return table key) or labelText (exact match)<br />
<br />
See also: [[#createMapLabel|createMapLabel()]], [[#getMapLabels|getMapLabels()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lua getMapLabels(52)<br />
{<br />
"no text",<br />
[0] = "test"<br />
}<br />
<br />
lua getMapLabel(52, 0)<br />
{<br />
Y = -2,<br />
X = -8,<br />
Z = 11,<br />
Height = 3.9669418334961,<br />
Text = "test",<br />
Width = 8.6776866912842,<br />
BgColor = {<br />
b = 0,<br />
g = 0,<br />
r = 0<br />
},<br />
FgColor = {<br />
b = 50,<br />
g = 255,<br />
r = 255<br />
},<br />
Pixmap = "iVBORw0KG(...)lFTkSuQmCC" -- base64 encoded png image (shortened for brevity)<br />
}<br />
<br />
lua getMapLabel(52, "no text")<br />
{<br />
Y = 8,<br />
X = -15,<br />
Z = 11,<br />
Height = 7.2520666122437,<br />
Text = "no text"<br />
Width = 11.21900844574,<br />
BgColor = {<br />
b = 0,<br />
g = 0,<br />
r = 0<br />
},<br />
FgColor = {<br />
b = 50,<br />
g = 255,<br />
r = 255<br />
},<br />
Pixmap = "iVBORw0KG(...)lFTkSuQmCC" -- base64 encoded png image (shortened for brevity)<br />
}<br />
</syntaxhighlight><br />
<br />
==getMapLabels==<br />
;arealabels = getMapLabels(areaID)<br />
<br />
:Returns an indexed table (that starts indexing from 0) of all of the labels in the area, plus their label text. You can use the label id to [[#deleteMapLabel|deleteMapLabel()]] it.<br />
:If there are no labels in the area at all, it will return an empty table.<br />
<br />
: See also: [[#createMapLabel|createMapLabel()]], [[#getMapLabel|getMapLabel()]], [[#deleteMapLabel|deleteMapLabel()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getMapLabels(43))<br />
table {<br />
0: ''<br />
1: 'Waterways'<br />
}<br />
<br />
deleteMapLabel(43, 0)<br />
display(getMapLabels(43))<br />
table {<br />
1: 'Waterways'<br />
}<br />
</syntaxhighlight><br />
<br />
==getMapMenus==<br />
;getMapMenus()<br />
<br />
:Returns a table with the available map menus as key-value in the format of <code>map menu - parent item</code>. If an item is positioned at the menu's top-level, the value will say <code>top-level</code>.<br />
:If you haven't opened a map yet, getMapMenus() will return nil+error message. If you don't have any map labels yet, an empty table <code>{}</code> is returned.<br />
<br />
: See also: [[#addMapMenu|addMapMenu()]], [[#addMapEvent|addMapEvent()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- given the following menu structure:<br />
top-level<br />
menu1<br />
menu1.1<br />
action1.1.1<br />
menu1.2<br />
action1.2.1<br />
menu2<br />
<br />
getMapMenus() -- will return:<br />
{<br />
menu2 = "top-level",<br />
menu1.2 = "menu1",<br />
menu1.1 = "menu1",<br />
menu1 = "top-level"<br />
}<br />
</syntaxhighlight><br />
<br />
==getMapSelection==<br />
; getMapSelection()<br />
<br />
:Returns a table containing details of the current mouse selection in the 2D mapper.<br />
<br />
:Reports on one or more rooms being selected (i.e. they are highlighted in orange).<br />
<br />
:The contents of the table will vary depending on what is currently selected. If the selection is of map rooms then there will be keys of ''center'' and ''rooms'': the former will indicates the center room (the one with the yellow cross-hairs) if there is more than one room selected or the only room if there is only one selected (there will not be cross-hairs in that case); the latter will contain a list of the one or more rooms.<br />
<br />
; Example - several rooms selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
center = 5013,<br />
rooms = {<br />
5011,<br />
5012,<br />
5013,<br />
5014,<br />
5018,<br />
5019,<br />
5020<br />
}<br />
}<br />
</syntaxhighlight><br />
; Example - one room selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
center = 5013,<br />
rooms = {<br />
5013<br />
}<br />
}<br />
</syntaxhighlight><br />
; Example - no or something other than a room selected<br />
<syntaxhighlight lang="lua"><br />
display(getMapSelection())<br />
{<br />
}<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.17}}<br />
<br />
==getMapUserData==<br />
;getMapUserData( key )<br />
<br />
;Parameters<br />
* ''key:''<br />
: string used as a key to select the data stored in the map as a whole.<br />
<br />
:Returns the user data item (string); will return a nil+error message if there is no data with such a key in the map data.<br />
<br />
: See also: [[#getAllMapUserData|getAllMapUserData()]], [[#setMapUserData|setMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getMapUserData("last updated"))<br />
--might result in:--<br />
"December 5, 2020"<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.0}}<br />
<br />
==getPath==<br />
;getPath(roomID from, roomID to)<br />
<br />
:Returns a boolean true/false if a path between two room IDs is possible. If it is, the global ''speedWalkDir'' table is set to all of the directions that have to be taken to get there, and the global ''speedWalkPath'' table is set to all of the roomIDs you'll encounter on the way, and as of 3.0, ''speedWalkWeight'' will return all of the room weights. Additionally returns the total cost (all weights added up) of the path after the boolean argument in 3.0.<br />
<br />
<br />
: See also: [[Manual:Lua_Functions#translateTable|translateTable()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- check if we can go to room 155 from room 34 - if yes, go to it<br />
if getPath(34,155) then<br />
gotoRoom(155)<br />
else<br />
echo("\nCan't go there!")<br />
end<br />
</syntaxhighlight><br />
<br />
==getPlayerRoom==<br />
;getPlayerRoom()<br />
<br />
:Returns the current player location as set by [[#centerview|centerview()]].<br />
<br />
: See also: [[#centerview|centerview]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("We're currently in " .. getRoomName(getPlayerRoom()))<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.14}}<br />
<br />
==getRoomArea==<br />
;getRoomArea(roomID)<br />
<br />
:Returns the area ID of a given room ID. To get the area name, you can check the area ID against the data given by [[#getAreaTable | getAreaTable()]] function, or use the [[#getRoomAreaName |getRoomAreaName()]] function.<br />
<br />
{{note}} If the room ID does not exist, this function will raise an error.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("Area ID of room #100 is: "..getRoomArea(100))<br />
<br />
display("Area name for room #100 is: "..getRoomAreaName(getRoomArea(100)))<br />
</syntaxhighlight><br />
<br />
==getRoomAreaName==<br />
;getRoomAreaName(areaID or areaName)<br />
<br />
:Returns the area name for a given area id; or the area id for a given area name.<br />
<br />
{{note}} Despite the name, this function will not return the area name for a given ''room'' id (or room name) directly. However, renaming or revising it would break existing scripts.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("room id #455 is in %s.", getRoomAreaName(getRoomArea(455))))<br />
</syntaxhighlight><br />
<br />
<br />
==getRoomChar==<br />
;getRoomChar(roomID)<br />
<br />
:Returns the single ASCII character that forms the ''symbol'' for the given room id.<br />
<br />
: '''Since Mudlet version 3.8 :''' this facility has been extended:<br />
: Returns the string (UTF-8) that forms the ''symbol'' for the given room id; this may have been set with either [[#setRoomChar|setRoomChar()]] or with the ''symbol'' (was ''letter'' in prior versions) context menu item for rooms in the 2D Map.<br />
<br />
==getRoomCoordinates==<br />
;x,y,z = getRoomCoordinates(roomID)<br />
<br />
:Returns the room coordinates of the given room ID.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local x,y,z = getRoomCoordinates(roomID)<br />
echo("Room Coordinates for "..roomID..":")<br />
echo("\n X:"..x)<br />
echo("\n Y:"..y)<br />
echo("\n Z:"..z)<br />
</syntaxhighlight><br />
<br />
<syntaxhighlight lang="lua"><br />
-- A quick function that will find all rooms on the same z-position in an area; this is useful if, say, you want to know what all the same rooms on the same "level" of an area is.<br />
function sortByZ(areaID, zval)<br />
local area = getAreaRooms(areaID)<br />
local t = {}<br />
for _, id in ipairs(area) do<br />
local _, _, z = getRoomCoordinates(id)<br />
if z == zval then<br />
table.insert(t, id)<br />
end<br />
end<br />
return t<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomEnv==<br />
;envID = getRoomEnv(roomID)<br />
<br />
:Returns the environment ID of a room. The mapper does not store environment names, so you'd need to keep track of which ID is what name yourself.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
funtion checkID(id)<br />
echo(string.format("The env ID of room #%d is %d.\n", id, getRoomEnv(id)))<br />
end<br />
</syntaxhighlight><br />
<br />
== getRoomExits ==<br />
;getRoomExits (roomID)<br />
:Returns the currently known non-special exits for a room in an key-index form: ''exit = exitroomid''.<br />
<br />
: See also: [[#getSpecialExits|getSpecialExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
table {<br />
'northwest': 80<br />
'east': 78<br />
}<br />
</syntaxhighlight><br />
<br />
Here's a practical example that queries the rooms around you and searched for one of the water environments (the number would depend on how it was mapped):<br />
<br />
<syntaxhighlight lang="lua"><br />
local exits = getRoomExits(mycurrentroomid)<br />
for direction,num in pairs(exits) do<br />
local env_num = getRoomEnv(num)<br />
if env_num == 22 or env_num == 20 or env_num == 30 then<br />
print("There's water to the "..direction.."!")<br />
end<br />
end</syntaxhighlight><br />
<br />
==getRoomHashByID==<br />
;getRoomHashByID(roomID)<br />
<br />
:Returns a room hash that is associated with a given room ID in the mapper. This is primarily for games that make use of hashes instead of room IDs. It may be used to share map data while not sharing map itself. ''nil'' is returned if no room is not found.<br />
<br />
: See also: [[#getRoomIDbyHash|getRoomIDbyHash()]]<br />
{{MudletVersion|3.13.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
for id,name in pairs(getRooms()) do<br />
local h = getRoomUserData(id, "herbs")<br />
if h ~= "" then<br />
echo(string.format([[["%s"] = "%s",]], getRoomHashByID(id), h))<br />
echo("\n")<br />
end<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomIDbyHash==<br />
;roomID = getRoomIDbyHash(hash)<br />
<br />
:Returns a room ID that is associated with a given hash in the mapper. This is primarily for games that make use of hashes instead of room IDs (like [http://avalon.mud.de/index.php?enter=1 Avalon.de]). ''-1'' is returned if no room ID matches the hash.<br />
<br />
: See also: [[#getRoomHashByID|getRoomHashByID()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- example taken from http://forums.mudlet.org/viewtopic.php?f=13&t=2177<br />
local id = getRoomIDbyHash("5dfe55b0c8d769e865fd85ba63127fbc")<br />
if id == -1 then <br />
id = createRoomID()<br />
setRoomIDbyHash(id, "5dfe55b0c8d769e865fd85ba63127fbc")<br />
addRoom(id)<br />
setRoomCoordinates(id, 0, 0, -1)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomName==<br />
;getRoomName(roomID)<br />
<br />
:Returns the room name for a given room id.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("The name of the room id #455 is %s.", getRoomName(455))<br />
</syntaxhighlight><br />
<br />
==getRooms==<br />
;rooms = getRooms()<br />
<br />
:Returns the list of '''all''' rooms in the map in the whole map in roomid - room name format.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- simple, raw viewer for rooms in the world<br />
display(getRooms())<br />
<br />
-- iterate over all rooms in code<br />
for id,name in pairs(getRooms()) do<br />
print(id, name)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomsByPosition==<br />
;roomTable = getRoomsByPosition(areaID, x,y,z)<br />
<br />
:Returns an indexed table of all rooms at the given coordinates in the given area, or an empty one if there are none. This function can be useful for checking if a room exists at certain coordinates, or whenever you have rooms overlapping.<br />
<br />
{{note}} The returned table starts indexing from '''0''' and not the usual lua index of '''1''', which means that using '''#''' to count the size of the returned table will produce erroneous results - use [[Manual:Table_Functions#table.size|table.size()]] instead.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- sample alias to determine a room nearby, given a relative direction from the current room<br />
<br />
local otherroom<br />
if matches[2] == "" then<br />
local w = matches[3]<br />
local ox, oy, oz, x,y,z = getRoomCoordinates(mmp.currentroom)<br />
local has = table.contains<br />
if has({"west", "left", "w", "l"}, w) then<br />
x = (x or ox) - 1; y = (y or oy); z = (z or oz)<br />
elseif has({"east", "right", "e", "r"}, w) then<br />
x = (x or ox) + 1; y = (y or oy); z = (z or oz)<br />
elseif has({"north", "top", "n", "t"}, w) then<br />
x = (x or ox); y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"south", "bottom", "s", "b"}, w) then<br />
x = (x or ox); y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"northwest", "topleft", "nw", "tl"}, w) then<br />
x = (x or ox) - 1; y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"northeast", "topright", "ne", "tr"}, w) then<br />
x = (x or ox) + 1; y = (y or oy) + 1; z = (z or oz)<br />
elseif has({"southeast", "bottomright", "se", "br"}, w) then<br />
x = (x or ox) + 1; y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"southwest", "bottomleft", "sw", "bl"}, w) then<br />
x = (x or ox) - 1; y = (y or oy) - 1; z = (z or oz)<br />
elseif has({"up", "u"}, w) then<br />
x = (x or ox); y = (y or oy); z = (z or oz) + 1<br />
elseif has({"down", "d"}, w) then<br />
x = (x or ox); y = (y or oy); z = (z or oz) - 1<br />
end<br />
<br />
local carea = getRoomArea(mmp.currentroom)<br />
if not carea then mmp.echo("Don't know what area are we in.") return end<br />
<br />
otherroom = select(2, next(getRoomsByPosition(carea,x,y,z)))<br />
<br />
if not otherroom then<br />
mmp.echo("There isn't a room to the "..w.." that I see - try with an exact room id.") return<br />
else<br />
mmp.echo("The room "..w.." of us has an ID of "..otherroom)<br />
end<br />
</syntaxhighlight><br />
<br />
==getRoomUserData==<br />
;getRoomUserData(roomID, key)<br />
<br />
:Returns the user data value (string) stored at a given room with a given key (string), or "" if none is stored. Use [[#setRoomUserData|setRoomUserData()]] function for setting the user data.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getRoomUserData(341, "visitcount"))<br />
</syntaxhighlight><br />
<br />
:;getRoomUserData(roomID, key, enableFullErrorReporting)<br />
<br />
::Returns the user data value (string) stored at a given room with a given key (string), or, if the boolean value ''enableFullErrorReporting'' is true, ''nil'' and an error message if the key is not present or the room does not exist; if ''enableFullErrorReporting'' is false an empty string is returned but then it is not possible to tell if that particular value is actually stored or not against the given key.<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserDataKeys|getRoomUserDataKeys()]], [[#searchRoomUserData|searchRoomUserData()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;Example<br />
<!-- I would like this block to be indented to match the Example header but the mark-up system seems to be broken and only includes the first line<br />
if the start of the code line begins: ":<lua>..."--><br />
<syntaxhighlight lang="lua">local vNum = 341<br />
result, errMsg = getRoomUserData(vNum, "visitcount", true)<br />
if result ~= nil then<br />
display(result)<br />
else<br />
echo("\nNo visitcount data for room: "..vNum.."; reason: "..errMsg.."\n")<br />
end</syntaxhighlight><br />
<br />
==getRoomUserDataKeys==<br />
;getRoomUserDataKeys(roomID)<br />
<br />
:Returns all the keys for user data items stored in the given room ID; will return an empty table if there is no data stored or nil if there is no such room with that ID. ''Can be useful if the user was not the one who put the data in the map in the first place!''<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#searchRoomUserData|searchRoomUserData()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display(getRoomUserDataKeys(3441))<br />
--might result in:--<br />
{<br />
"description",<br />
"doorname_up",<br />
}<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|3.0}}<br />
<br />
==getRoomWeight==<br />
;getRoomWeight(roomID)<br />
<br />
:Returns the weight of a room. By default, all new rooms have a weight of 1.<br />
: See also: [[#setRoomWeight|setRoomWeight()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
display("Original weight of room 541: "..getRoomWeight(541))<br />
setRoomWeight(541, 3)<br />
display("New weight of room 541: "..getRoomWeight(541))<br />
</syntaxhighlight><br />
<br />
==getSpecialExits==<br />
;exits = getSpecialExits(roomID[, listAllExits])<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to return the special exits of.<br />
* ''listAllExits:''<br />
: (Since ''TBA'') In the case where there is more than one special exit to the same room ID list all of them.<br />
<br />
:Returns a roomid table of sub-tables containingg name/command and exit lock status, of the special exits in the room. If there are no special exits in the room, the table returned will be empty.<br />
:Before ''TBA'' (likely to be Mudlet version '''4.11.0'''), if more than one special exit goes to the ''same'' exit room id then one of those exits is returned at random. Since ''TBA'' this will be the best (i.e. lowest-weight) exit that is '''not''' locked; should none be unlocked then the lowest locked one will be listed. In case of a tie, one of the tying exits will be picked at random.<br />
<br />
: See also: [[#getRoomExits|getRoomExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- There are three special exits from 1337 to the room 42:<br />
-- "climb down ladder" which is locked and has an exit weight of 10<br />
-- "step out window" which is unlocked and has an exit weight of 20<br />
-- "jump out window" which is unlocked and has an exit weight of 990<br />
getSpecialExits(1337)<br />
<br />
-- In 4.10.1 and before this could results in:<br />
table {<br />
42 = {"jump out window" = "0"},<br />
666 = {"dive into pit" = "1"}<br />
}<br />
-- OR<br />
table {<br />
42 = {"climb down ladder" = "1"},<br />
666 = {"dive into pit" = "1"}<br />
}<br />
-- OR<br />
table {<br />
42 = {"step out window" = "0"},<br />
666 = {"dive into pit" = "1"}<br />
}<br />
<br />
-- From TBA this will return:<br />
table {<br />
42 = {"step out window" = "0"},<br />
666 = {"dive into pit" = "1"}<br />
}<br />
<br />
-- From TBA, with the second argument as true, this gives:<br />
getSpecialExits(1337, true)<br />
table {<br />
42 = {"step out window" = "0",<br />
"climb down ladder" = "1",<br />
"jump out window" = "0"},<br />
666 = {"dive into pit" = "1"}<br />
}<br />
</syntaxhighlight><br />
<br />
==getSpecialExitsSwap==<br />
;getSpecialExitsSwap(roomID)<br />
<br />
:Very similar to [[#getSpecialExits|getSpecialExits()]] function, but returns the rooms in the command - roomid style.<br />
<br />
==gotoRoom==<br />
;gotoRoom (roomID)<br />
:Speedwalks you to the given room from your current room if it is able and knows the way. You must turn the map on for this to work, else it will return "(mapper): Don't know how to get there from here :(".<br />
<br />
In case this isn't working, and you are coding your own mapping script, [[Manual:Mapper#Making_your_own_mapping_script|see here]] how to implement additional functionality necessary.<br />
<br />
==hasExitLock==<br />
;status = hasExitLock(roomID, direction)<br />
<br />
:Returns ''true'' or ''false'' depending on whenever a given exit leading out from a room is locked. Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
<br />
; Example<br />
<syntaxhighlight lang="lua"><br />
-- check if the east exit of room 1201 is locked<br />
display(hasExitLock(1201, 4))<br />
display(hasExitLock(1201, "e"))<br />
display(hasExitLock(1201, "east"))<br />
</syntaxhighlight><br />
<br />
: See also: [[#lockExit|lockExit()]]<br />
<br />
==hasSpecialExitLock==<br />
;hasSpecialExitLock(from roomID, to roomID, moveCommand)<br />
<br />
:Returns ''true'' or ''false'' depending on whenever a given exit leading out from a room is locked. ''moveCommand'' is the action to take to get through the gate.<br />
<br />
See also: [[#lockSpecialExit|lockSpecialExit()]]<br />
<br />
<syntaxhighlight lang="lua"><br />
-- lock a special exit from 17463 to 7814 that uses the 'enter feather' command<br />
lockSpecialExit(17463, 7814, 'enter feather', true)<br />
<br />
-- see if it is locked: it will say 'true', it is<br />
display(hasSpecialExitLock(17463, 7814, 'enter feather'))<br />
</syntaxhighlight><br />
<br />
==highlightRoom==<br />
;highlightRoom( roomID, color1Red, color1Green, color1Blue, color2Red, color2Green, color2Blue, highlightRadius, color1Alpha, color2Alpha)<br />
<br />
:Highlights a room with the given color, which will override its environment color. If you use two different colors, then there'll be a shading from the center going outwards that changes into the other color. <br />
<br />
;Parameters<br />
* ''roomID''<br />
: ID of the room to be colored.<br />
* ''color1Red, color1Green, color1Blue''<br />
: RGB values of the first color.<br />
* ''color2Red, color2Green, color2Blue''<br />
: RGB values of the second color.<br />
* ''highlightRadius'' <br />
: The radius for the highlight circle - if you don't want rooms beside each other to overlap, use ''1'' as the radius. <br />
* ''color1Alpha'' and ''color2Alpha'' <br />
: Transparency values from 0 (completely transparent) to 255 (not transparent at all).<br />
<br />
: See also: [[#unHighlightRoom|unHighlightRoom()]]<br />
<br />
<syntaxhighlight lang="lua"><br />
-- color room #351 red to blue<br />
local r,g,b = unpack(color_table.red)<br />
local br,bg,bb = unpack(color_table.blue)<br />
highlightRoom(351, r,g,b,br,bg,bb, 1, 255, 255)<br />
</syntaxhighlight><br />
<br />
==killMapInfo==<br />
;killMapInfo(label)<br />
<br />
Delete a map info contributor entirely - it will be not available anymore.<br />
<br />
;Parameters<br />
* ''label:''<br />
: Name under which map info to be removed was registered.<br />
<br />
: See also: [[#registerMapInfo|registerMapInfo()]], [[#enableMapInfo|enableMapInfo()]], [[#disableMapInfo|disableMapInfo()]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
==loadJsonMap==<br />
; loadJsonMap(pathFileName)<br />
<br />
; Parameters:<br />
<br />
* ''pathFileName'' a string that is an absolute path and file name to read the data from.<br />
<br />
Load the Mudlet map in text (JSON) format. It does take longer than loading usual map file (''.dat'' in binary) so it will show a progress dialog.<br />
<br />
: See also: [[#saveJsonMap|saveJsonMap()]]<br />
<br />
Returns:<br />
* ''true'' on success<br />
* ''nil'' and an error message on failure.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
loadJsonMap(getMudletHomeDir() .. "/map.json")<br />
<br />
true<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.11.0}}<br />
<br />
==loadMap==<br />
;loadMap(file location)<br />
<br />
:Loads the map file from a given location. The map file must be in Mudlet's format - saved with [[#saveMap|saveMap()]] or, as of the Mudlet 3.0 may be a MMP XML map conforming to the structure used by I.R.E. for their downloadable maps for their MUD games. <br />
<br />
:Returns a boolean for whenever the loading succeeded. Note that the mapper must be open, or this will fail.<br />
<br />
:Using no arguments will load the last saved map.<br />
<br />
<syntaxhighlight lang="lua"><br />
loadMap("/home/user/Desktop/Mudlet Map.dat")<br />
</syntaxhighlight><br />
<br />
{{Note}} A file name ending with <code>.xml</code> will indicate the XML format.<br />
<br />
==lockExit==<br />
;lockExit(roomID, direction, lockIfTrue)<br />
<br />
:Locks a given exit from a room (which means that unless all exits in the incoming room are locked, it'll still be accessible). Direction can be specified as a number, short direction name ("nw") or long direction name ("northwest").<br />
<br />
: See also: [[#hasExitLock|hasExitLock()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- lock the east exit of room 1201 so we never path through it<br />
lockExit(1201, 4, true)<br />
</syntaxhighlight><br />
<br />
==lockRoom==<br />
;lockRoom (roomID, lockIfTrue)<br />
<br />
:Locks a given room id from future speed walks (thus the mapper will never path through that room).<br />
: See also: [[#roomLocked | roomLocked()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lockRoom(1, true) -- locks a room if from being walked through when speedwalking.<br />
lockRoom(1, false) -- unlocks the room, adding it back to possible rooms that can be walked through.<br />
</syntaxhighlight><br />
<br />
==lockSpecialExit==<br />
;lockSpecialExit (from roomID, to roomID, special exit command, lockIfTrue)<br />
<br />
:Locks a given special exit, leading from one specific room to another that uses a certain command from future speed walks (thus the mapper will never path through that special exit).<br />
: See also: [[#hasSpecialExitLock | hasSpecialExitLock()]], [[#lockExit | lockExit()]], [[#lockRoom | lockRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
lockSpecialExit(1,2,'enter gate', true) -- locks the special exit that does 'enter gate' to get from room 1 to room 2<br />
lockSpecialExit(1,2,'enter gate', false) -- unlocks the said exit<br />
</syntaxhighlight><br />
<br />
==moveMapWidget==<br />
;moveMapWidget(Xpos, Ypos)<br />
:moves the map window to the given position.<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#closeMapWidget|closeMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
;Parameters<br />
* ''Xpos:''<br />
: X position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''Ypos:''<br />
: Y position of the map window. Measured in pixels, with 0 being the very top. Passed as an integer number.<br />
<br />
{{MudletVersion|4.7}}<br />
<br />
==openMapWidget==<br />
;openMapWidget([dockingArea | Xpos, Ypos, width, height])<br />
means either of these are fine:<br />
;openMapWidget()<br />
;openMapWidget(dockingArea)<br />
;openMapWidget(Xpos, Ypos, width, height)<br />
<br />
:opens a map window with given options.<br />
<br />
: See also: [[#closeMapWidget|closeMapWidget()]], [[#moveMapWidget|moveMapWidget()]], [[#resizeMapWidget|resizeMapWidget()]]<br />
<br />
{{MudletVersion|4.7}}<br />
<br />
;Parameters<br />
{{note}} If no parameter is given the map window will be opened with the saved layout or at the right docking position (similar to clicking the icon)<br />
* ''dockingArea:''<br />
: If only one parameter is given this parameter will be a string that contains one of the possible docking areas the map window will be created in (f" floating "t" top "b" bottom "r" right and "l" left)<br />
{{note}} If 4 parameters are given the map window will be created in floating state <br />
* ''Xpos:''<br />
: X position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''Ypos:''<br />
: Y position of the map window. Measured in pixels, with 0 being the very left. Passed as an integer number.<br />
* ''width:''<br />
: The width map window, in pixels. Passed as an integer number.<br />
* ''height:''<br />
: The height map window, in pixels. Passed as an integer number.<br />
<br />
==pauseSpeedwalk==<br />
;pauseSpeedwalk()<br />
<br />
:Pauses a speedwalk started using [[#speedwalk|speedwalk()]]<br />
<br />
: See also: [[#speedwalk|speedwalk()]], [[#stopSpeedwalk|stopSpeedwalk()]], [[#resumeSpeedwalk|resumeSpeedwalk()]]<br />
<br />
{{MudletVersion|4.13}}<br />
<br />
<syntaxhighlight lang="lua"><br />
local ok, err = pauseSpeedwalk()<br />
if not ok then<br />
debugc(f"Error: unable to pause speedwalk because {err}\n")<br />
return<br />
end<br />
</syntaxhighlight><br />
<br />
==registerMapInfo==<br />
;registerMapInfo(label, function)<br />
<br />
Adds an extra 'map info' to the mapper widget which can be used to display custom information.<br />
<br />
: See also: [[#killMapInfo|killMapInfo()]], [[#enableMapInfo|enableMapInfo()]], [[#disableMapInfo|disableMapInfo()]]<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
{{note}}<br />
You can register multiple map infos - just give them unique names and toggle whichever ones you need.<br />
<br />
;Parameters<br />
* ''label:''<br />
: Name under which map info will be registered and visible in select box under mapper. You can use it later to kill map info, enable it, disable it or overwrite using [[#registerMapInfo|registerMapInfo()]] again.<br />
* ''function:''<br />
: Callback function that will be responsible for returning information how to draw map info fragment.<br />
<br />
Callback function is called with following arguments:<br />
* ''roomId'' - current roomId or currently selected room (when multiple selection is made this is center room)<br />
* ''selectionSize'' - how many rooms are selected<br />
* ''areaId'' - roomId's areaId<br />
* ''displayedAreaId'' - areaId that is currently displayed<br />
<br />
Callback needs to return following:<br />
* ''text'' - text that will be displayed (when empty, nothing will be displayed, if you want to "reserve" line or lines use not empty value " " or add line breaks "\n")<br />
* ''isBold'' (optional) - true/false - determines whether text will be bold <br />
* ''isItalic'' (optional) - true/false - determines whether text will be italic<br />
* ''color r'' (optional) - color of text red component (0-255)<br />
* ''color g'' (optional) - color of text green component (0-255)<br />
* ''color b'' (optional) - color of text blue component (0-255)<br />
<br />
{{note}}<br />
Map info is registered in disabled state, you need to enable it through script or by selecting checkbox under mapper.<br />
<br />
<syntaxhighlight lang="lua"><br />
registerMapInfo("My very own handler!", function(roomId, selectionSize, areaId, displayedArea) <br />
return string.format("RoomId: %d\nNumbers of room selected: %d\nAreaId: %d\nDisplaying area: %d", roomId, selectionSize, areaId, displayedArea),<br />
true, true, 0, 255, 0<br />
end)<br />
enableMapInfo("My very own handler!")<br />
</syntaxhighlight><br />
<br />
Example will display something like that:<br />
<br />
[[File:Map-info-example.png]]<br />
<br />
Using function arguments is completely optional and you can determine whether and how to display map info completely externally.<br />
<syntaxhighlight lang="lua"><br />
registerMapInfo("Alert", function() <br />
if character.hp < 20 then<br />
return "Look out! Your HP is getting low", true, false, unpack(color_table.red) -- will display red, bolded warning whne character.hp is below 20<br />
else<br />
return "" -- will not return anything<br />
end<br />
end)<br />
enableMapInfo("Alert")<br />
</syntaxhighlight><br />
<br />
==resumeSpeedwalk==<br />
;resumeSpeedwalk()<br />
<br />
:Continues a speedwalk paused using [[#pauseSpeedwalk|pauseSpeedwalk()]]<br />
: See also: [[#speedwalk|speedwalk()]], [[#pauseSpeedwalk|pauseSpeedwalk()]], [[#stopSpeedwalk|stopSpeedwalk()]]<br />
<br />
{{MudletVersion|4.13}}<br />
<br />
<syntaxhighlight lang="lua"><br />
local ok, err = resumeSpeedwalk()<br />
if not ok then<br />
cecho(f"\n<red>Error:<reset> Problem resuming speedwalk: {err}\n")<br />
return<br />
end<br />
cecho("\n<green>Successfully resumed speedwalk!\n")<br />
</syntaxhighlight><br />
<br />
==removeCustomLine==<br />
;removeCustomLine(roomID, direction) <br />
<br />
:Removes the custom exit line that's associated with a specific exit of a room.<br />
:See also: [[#addCustomLine|addCustomLine()]], [[#getCustomLines|getCustomLines()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- remove custom exit line that starts in room 315 going north<br />
removeCustomLine(315, "n")<br />
</syntaxhighlight><br />
<br />
==removeMapEvent==<br />
;removeMapEvent(event name)<br />
<br />
:Removes the given menu entry from a mappers right-click menu. You can add custom ones with [[#addMapEvent | addMapEvent()]].<br />
: See also: [[#addMapEvent | addMapEvent()]], [[#getMapEvents | getMapEvents()]], [[#removeMapMenu | removeMapMenu()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapEvent("room a", "onFavorite") -- add one to the general menu<br />
removeMapEvent("room a") -- removes the said menu<br />
</syntaxhighlight><br />
<br />
==removeMapMenu==<br />
;removeMapMenu(menu name)<br />
<br />
:Removes the given submenu from a mappers right-click menu. You can add custom ones with [[#addMapMenu | addMapMenu()]].<br />
: See also: [[#addMapMenu | addMapMenu()]], [[#getMapMenus | getMapMenus()]], [[#removeMapEvent | removeMapEvent()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addMapMenu("Test") -- add submenu to the general menu<br />
removeMapMenu("Test") -- removes that same menu again<br />
</syntaxhighlight><br />
<br />
==removeSpecialExit==<br />
;removeSpecialExit(roomID, command) <br />
<br />
:Removes the special exit which is accessed by ''command'' from the room with the given ''roomID''.<br />
:See also: [[#addSpecialExit|addSpecialExit()]], [[#clearSpecialExits|clearSpecialExits()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
addSpecialExit(1, 2, "pull rope") -- add a special exit from room 1 to room 2<br />
removeSpecialExit(1, "pull rope") -- removes the exit again<br />
</syntaxhighlight><br />
<br />
==resetRoomArea==<br />
;resetRoomArea (roomID)<br />
<br />
: Unassigns the room from its given area. While not assigned, its area ID will be -1. Note that since Mudlet 3.0 the "default area" which has the id of -1 may be selectable in the area selection widget on the mapper - although there is also an option to conceal this in the settings.<br />
<br />
: See also: [[#setRoomArea | setRoomArea()]], [[#getRoomArea | getRoomArea()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
resetRoomArea(3143)<br />
</syntaxhighlight><br />
<br />
==resizeMapWidget==<br />
;resizeMapWidget(width, height)<br />
:resizes a map window with given width, height.<br />
: See also: [[#openMapWidget|openMapWidget()]], [[#closeMapWidget|closeMapWidget()]], [[#moveMapWidget|moveMapWidget()]]<br />
<br />
{{MudletVersion|4.7}}<br />
<br />
;Parameters<br />
* ''width:''<br />
: The width of the map window, in pixels. Passed as an integer number.<br />
* ''height:''<br />
: The height of the map window, in pixels. Passed as an integer number.<br />
<br />
==roomExists==<br />
;roomExists(roomID)<br />
<br />
:Returns a boolean true/false depending if the room with that ID exists (is created) or not.<br />
<br />
==roomLocked==<br />
;locked = roomLocked(roomID)<br />
<br />
:Returns true or false whenever a given room is locked.<br />
: See also: [[#lockRoom|lockRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
echo(string.format("Is room #4545 locked? %s.", roomLocked(4545) and "Yep" or "Nope"))<br />
</syntaxhighlight><br />
<br />
==saveJsonMap==<br />
; saveJsonMap([pathFileName])<br />
Saves all the data that is normally held in the Mudlet map (''.dat'' as a binary format) in text (JSON) format. It does take longer to do this, so a progress dialog will be shown indicating the status. <br />
<br />
: See also: [[#loadJsonMap|loadJsonMap()]]<br />
{{MudletVersion|4.11.0}}<br />
<br />
; Parameters:<br />
* ''pathFileName'' (optional in Mudlet 4.12+): a string that is an absolute path and file name to save the data into.<br />
<br />
; Returns:<br />
* ''true'' on success<br />
* ''nil'' and an error message on failure.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
saveJsonMap(getMudletHomeDir() .. "/map.json")<br />
<br />
true<br />
</syntaxhighlight><br />
<br />
==saveMap==<br />
;saveMap([location], [version])<br />
<br />
:Saves the map to a given location, and returns true on success. The location folder needs to be already created for save to work. You can also save the map in the Mapper settings tab.<br />
<br />
;Parameters<br />
* ''location''<br />
: (optional) save the map to the given location if provided, or the default one otherwise.<br />
* ''version''<br />
: (optional) map version as a number to use when saving (Mudlet 3.17+)<br />
<br />
: See also: [[#loadMap|loadMap()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
local savedok = saveMap(getMudletHomeDir().."/my fancy map.dat")<br />
if not savedok then<br />
echo("Couldn't save :(\n")<br />
else<br />
echo("Saved fine!\n")<br />
end<br />
<br />
-- save with a particular map version<br />
saveMap(20)<br />
</syntaxhighlight><br />
<br />
==searchAreaUserData==<br />
;searchAreaUserData(area number | area name[, case-sensitive [, exact-match]])<br />
:Searches Areas' User Data in a manner exactly the same as [[#searchRoomUserData|searchRoomUserData()]] does in all Rooms' User Data, refer to that command for the specific details except to replace references to rooms and room ID numbers there with areas and areas ID numbers.<br />
<br />
==searchRoom== <br />
;searchRoom (room number | room name[, case-sensitive [, exact-match]])<br />
:Searches for rooms that match (by case-insensitive, substring match) the given room name. It returns a key-value table in form of ''roomid = roomname'', the optional second and third boolean parameters have been available since Mudlet 3.0;<br />
<br />
::If no rooms are found, then an empty table is returned.<br />
<br />
:If you pass it a '''number''' instead of a '''string''' as just one argument, it'll act like [[#getRoomName|getRoomName()]] and return the room name.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- show the behavior when given a room number:<br />
display(searchRoom(3088))<br />
"The North Road South of Taren Ferry"<br />
<br />
-- show the behavior when given a string:<br />
-- shows all rooms containing the text in any case:<br />
display(searchRoom("North road"))<br />
{<br />
[3114] = "Bend in North road",<br />
[3115] = "North road",<br />
[3116] = "North Road",<br />
[3117] = "North road",<br />
[3146] = "Bend in the North Road",<br />
[3088] = "The North Road South of Taren Ferry",<br />
[6229] = "Grassy Field By North Road"<br />
}<br />
-- or:<br />
-- display(searchRoom("North road",false))<br />
-- display(searchRoom("North road",false,false))<br />
-- would both also produce those results.<br />
<br />
-- shows all rooms containing the text in ONLY the letter-case provided:<br />
display(searchRoom("North road",true,false))<br />
{<br />
[3114] = "Bend in North road",<br />
[3115] = "North road",<br />
[3117] = "North road",<br />
}<br />
<br />
-- shows all rooms containing ONLY that text in either letter-case:<br />
lua searchRoom("North road",false,true)<br />
{<br />
[3115] = "North road",<br />
[3116] = "North Road",<br />
[3117] = "North road"<br />
}<br />
<br />
-- shows all rooms containing only and exactly the given text:<br />
lua searchRoom("North road",true,true)<br />
{<br />
[3115] = "North road",<br />
[3117] = "North road"<br />
}<br />
</syntaxhighlight><br />
{{note}} Technically, with both options (case-sensitive and exact-match) set to true, one could just return a list of numbers as we know precisely what the string will be, but it was kept the same for maximum flexibility in user scripts.<br />
<br />
==searchRoomUserData== <br />
;searchRoomUserData([key, [value]])<br />
:A command with three variants that search though all the rooms in sequence (so '''not as fast as a user built/maintained ''index'' system''') and find/reports on the room user data stored:<br />
<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#getRoomUserDataKeys|getRoomUserDataKeys()]], [[#setRoomUserData|setRoomUserData()]]<br />
<br />
;searchRoomUserData(key, value)<br />
<br />
:Reports a (sorted) list of all room ids with user data with the given "value" for the given (case sensitive) "key". <br />
<br />
;searchRoomUserData(key)<br />
<br />
:Reports a (sorted) list of the unique values from all rooms with user data with the given (case sensitive) "key". <br />
<br />
;searchRoomUserData()<br />
<br />
:Reports a (sorted) list of the unique keys from all rooms with user data with any (case sensitive) "key", available since Mudlet 3.0. It is possible (though not recommended) to have a room user data item with an empty string "" as a key, this is handled correctly.<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- if I had stored the details of "named doors" as part of the room user data --<br />
display(searchRoomUserData("doorname_up"))<br />
<br />
--[[ could result in a list:<br />
{<br />
"Eastgate",<br />
"Northgate",<br />
"boulderdoor",<br />
"chamberdoor",<br />
"dirt",<br />
"floorboards",<br />
"floortrap",<br />
"grate",<br />
"irongrate",<br />
"rockwall",<br />
"tomb",<br />
"trap",<br />
"trapdoor"<br />
}]]<br />
<br />
-- then taking one of these keys --<br />
display(searchRoomUserData("doorname_up","trapdoor"))<br />
<br />
--[[ might result in a list:<br />
{<br />
3441,<br />
6113,<br />
6115,<br />
8890<br />
}<br />
]]</syntaxhighlight><br />
<br />
==setAreaName==<br />
;setAreaName(areaID or areaName, newName)<br />
<br />
:Names, or renames an existing area to the new name. The area must be created first with [[#addAreaName|addAreaName()]] and it must be unique.<br />
<br />
{{note}} parameter areaName is available since Mudlet 3.0.<br />
<br />
:See also: [[#deleteArea|deleteArea()]], [[#addAreaName|addAreaName()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setAreaName(2, "My city")<br />
<br />
-- available since Mudlet 3.0<br />
setAreaName("My old city name", "My new city name")<br />
</syntaxhighlight><br />
<br />
==setAreaUserData==<br />
;setAreaUserData(areaID, key (as a string), value (as a string))<br />
<br />
:Stores information about an area under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. Returns a lua ''true'' value on success. You can have as many keys as you'd like, however a blank key will not be accepted and will produce a lua ''nil'' and an error message instead.<br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearAreaUserData|clearAreaUserData()]], [[#clearAreaUserDataItem|clearAreaUserDataItem()]], [[#getAllAreaUserData|getAllAreaUserData()]], [[#getAreaUserData|getAreaUserData()]], [[#searchAreaUserData|searchAreaUserData()]]<br />
<br />
{{MudletVersion|3.0}}<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- can use it to store extra area details...<br />
setAreaUserData(34, "country", "Andor.")<br />
<br />
-- or a sound file to play in the background (with a script that checks a room's area when entered)...<br />
setAreaUserData(34, "backgroundSound", "/home/user/mudlet-data/soundFiles/birdsong.mp4")<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setAreaUserData(101, "some table", yajl.to_string({ruler = "Queen Morgase Trakand", clan = "Lion Warden"}))<br />
display("The ruler's name is: "..yajl.to_value(getRoomUserData(101, "some table")).ruler)<br />
</syntaxhighlight><br />
<br />
==setCustomEnvColor==<br />
;setCustomEnvColor(environmentID, r,g,b,a)<br />
<br />
:Creates, or overrides an already created custom color definition for a given environment ID. Note that this will not work on the default environment colors - those are adjustable by the user in the preferences. You can however create your own environment and use a custom color definition for it.<br />
: See also: [[#getCustomEnvColorTable|getCustomEnvColorTable()]], [[#setRoomEnv|setRoomEnv()]]<br />
<br />
{{note}} Numbers 1-16 and 257-272 are reserved by Mudlet. 257-272 are the default colors the user can adjust in mapper settings, so feel free to use them if you'd like - but don't overwrite them with this function.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomEnv(571, 200) -- change the room's environment ID to something arbitrary, like 200<br />
local r,g,b = unpack(color_table.blue)<br />
setCustomEnvColor(200, r,g,b, 255) -- set the color of environmentID 200 to blue<br />
</syntaxhighlight><br />
<br />
==setDoor==<br />
;setDoor(roomID, exitCommand, doorStatus)<br />
<br />
:Creates or deletes a door in a room. Doors are purely visual - they don't affect pathfinding. You can use the information to adjust your speedwalking path based on the door information in a room, though.<br />
<br />
:Doors CAN be set on stub exits ''- so that map makers can note if there is an obvious door to somewhere even if they do not (yet) know where it goes, perhaps because they do not yet have the key to open it!''<br />
<br />
:Returns ''true'' if the change could be made, ''false'' if the input was valid but ineffective (door status was not changed), and ''nil'' with a message string on invalid input (value type errors).<br />
<br />
: See also: [[#getDoors|getDoors()]]<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to to create the door in.<br />
* ''exitCommand:''<br />
: The cardinal direction for the door is in - it can be one of the following: '''n''', '''e''', '''s''', '''w''', '''ne''', '''se''', '''sw''', '''ne'''. ''{Plans are afoot to add support for doors on the other normal exits: '''up''', '''down''', '''in''' and '''out''', and also on special exits - though more work will be needed for them to be shown in the mapper.}'' It is important to ONLY use these direction codes as others e.g. "UP" will be accepted - because a special exit could have ANY name/lua script - but it will not be associated with the particular normal exit - recent map auditing code about to go into the code base will REMOVE door and other room exit items for which the appropriate exit (or stub) itself is not present, so in this case, in the absence of a special exit called "UP" that example door will not persist and not show on the normal "up" exit when that is possible later on.<br />
<br />
* ''doorStatus:''<br />
: The door status as a number - '''0''' means no (or remove) door, '''1''' means open door (will draw a green square on exit), '''2''' means closed door (yellow square) and '''3''' means locked door (red square). <br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- make a door on the east exit of room 4234 that is currently open<br />
setDoor(4234, 'e', 1)<br />
<br />
-- remove a door from room 923 that points north<br />
setDoor(923, 'n', 0)<br />
</syntaxhighlight><br />
<br />
==setExit==<br />
;setExit(from roomID, to roomID, direction)<br />
<br />
:Creates a one-way exit from one room to another using a standard direction - which can be either one of ''n, ne, nw, e, w, s, se, sw, u, d, in, out'', the long version of a direction, or a number which represents a direction. If there was an exit stub in that direction already, then it will be automatically deleted for you.<br />
<br />
:Returns ''false'' if the exit creation didn't work.<br />
<br />
: See also: [[#addSpecialExit|addSpecialExit()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^exit (\d+) (\d+) (\w+)$<br />
-- so exit 1 2 5 will make an exit from room 1 to room 2 via north<br />
<br />
if setExit(tonumber(matches[2]), tonumber(matches[3]), matches[4]) then<br />
echo("\nExit set to room:"..matches[3].." from "..matches[2]..", direction:"..string.upper(matches[3]))<br />
else<br />
echo("Failed to set the exit.\n")<br />
end<br />
</syntaxhighlight><br />
<br />
This function can also delete exits from a room if you use it like so:<br />
<br />
<syntaxhighlight lang="lua">setExit(from roomID, -1, direction)</syntaxhighlight><br />
<br />
- which will delete an outgoing exit in the specified direction from a room.<br />
<br />
==setExitStub==<br />
;setExitStub(roomID, direction, set/unset)<br />
<br />
Creates or removes an exit stub from a room in a given directions. You can use exit stubs later on to connect rooms that you're sure of are together. Exit stubs are also shown visually on the map, so the mapper can easily tell which rooms need finishing.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: The room to place an exit stub in, as a number.<br />
* ''direction:''<br />
: The direction the exit stub should lead in - as a short direction name ("nw"), long direction name ("northwest") or a number.<br />
* ''set/unset:''<br />
: A boolean to create or delete the exit stub.<br />
<br />
: See also: [[#getExitStubs|getExitStubs()]], [[#connectExitStub|connectExitStub()]]<br />
<br />
;Example<br />
Create an exit stub to the south from room 8:<br />
<syntaxhighlight lang="lua"><br />
setExitStub(8, "s", true)<br />
</syntaxhighlight><br />
<br />
How to delete all exit stubs in a room:<br />
<syntaxhighlight lang="lua"><br />
for i,v in pairs(getExitStubs(roomID)) do<br />
setExitStub(roomID, v,false)<br />
end<br />
</syntaxhighlight><br />
<br />
==setExitWeight==<br />
;setExitWeight(roomID, exitCommand, weight)<br />
<br />
:Gives an exit a weight, which makes it less likely to be chosen for pathfinding. All exits have a weight of 0 by default, which you can increase. Exit weights are set one-way on an exit - if you'd like the weight to be applied both ways, set it from the reverse room and direction as well.<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to to set the weight in.<br />
* ''exitCommand:''<br />
: The direction for the exit is in - it can be one of the following: '''n''', '''ne''', '''e''', '''se''', '''s''', '''sw''', '''w''', '''nw''', '''up''', '''down''', '''in''', '''out''', or, if it's a special exit, the special exit command - note that the strings for normal exits are case-sensitive and must currently be exactly as given here.<br />
* ''weight:''<br />
: Exit weight - by default, all exits have a weight of 0 meaning that the weight of the ''destination room'' is use when the route finding code is considering whether to use that exit; setting a value for an exit can increase or decrease the chance of that exit/destination room being used for a route by the route-finding code. For example, if the destination room has very high weight compared to it's neighbors but the exit has a low value then that exit and thus the room is more likely to be used than if the exit was not weighted.<br />
<br />
: See also: [[#getExitWeights|getExitWeights()]]<br />
<br />
==setGridMode==<br />
;setGridMode(areaID, true/false)<br />
<br />
:Enables grid/wilderness view mode for an area - this will cause the rooms to lose their visible exit connections, like you'd see on compressed ASCII maps, both in 2D and 3D view mode; for the 2D map the custom exit lines will also not be shown if this mode is enabled. <br />
:Returns true if the area exists, otherwise false.<br />
:[[File:Mapper-regular-mode.png|none|thumb|640x640px|regular mode]][[File:Mapper-grid-mode.png|none|thumb|631x631px|grid mode]]<br />
<br />
: See also: [[#getGridMode|getGridMode()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setGridMode(55, true) -- set area with ID 55 to be in grid mode<br />
</syntaxhighlight><br />
<br />
==setMapUserData==<br />
;setMapUserData(key (as a string), value (as a string))<br />
<br />
:Stores information about the map under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like. <br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearMapUserData|clearMapUserData()]], [[#clearMapUserDataItem|clearMapUserDataItem()]], [[#getAllMapUserData|getAllMapUserData()]], [[#getMapUserData|getMapUserData()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- store general meta information about the map...<br />
setMapUserData("game_name", "Achaea Mudlet map")<br />
<br />
-- or who the author was<br />
setMapUserData("author", "Bob")<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setMapUserData("some table", yajl.to_string({game = "mud.com", port = 23}))<br />
display("Available game info in the map: ")<br />
display(yajl.to_value(getMapUserData("some table")))<br />
</syntaxhighlight><br />
<br />
==setMapZoom==<br />
;setMapZoom(zoom)<br />
<br />
:Zooms the map in to a given zoom level. '''1''' is the closest you can get, and anything higher than that zooms the map out.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setMapZoom(10) -- zoom to a somewhat acceptable level, a bit big but easily visible connections<br />
</syntaxhighlight><br />
<br />
==setRoomArea==<br />
;setRoomArea(roomID, newAreaID or newAreaName)<br />
<br />
:Assigns the given room to a new or different area. If the area is displayed in the mapper this will have the room be visually moved into the area as well.<br />
<br />
: See also: [[#resetRoomArea|resetRoomArea()]]<br />
<br />
==setRoomChar==<br />
;setRoomChar(roomID, character)<br />
<br />
:Originally designed for an area in grid mode, takes a single ASCII character and draws it on the rectangular background of the room in the 2D map. In versions prior to Mudlet 3.8, the symbol can be cleared by using "_" as the character. In Mudlet version 3.8 and higher, the symbol may be cleared with either a space <code>" "</code> or an empty string <code>""</code>.<br />
<br />
;Game-related symbols for your map<br />
* [https://github.com/toddfast/game-icons-net-font toddfast's font] - 3000+ scalable vector RPG icons from [https://game-icons.net game-icons.net], as well as a script to download the latest icons and generate a new font.<br />
* Pixel Kitchen's [https://www.fontspace.com/donjonikons-font-f30607 Donjonikon Font] - 10x10 fantasy and RPG-related icons.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomChar(431, "#")<br />
<br />
setRoomChar(123, "$")<br />
<br />
-- emoji's work fine too, and if you'd like it coloured, set the font to Nojo Emoji in settings<br />
setRoomChar(666, "👿")<br />
</syntaxhighlight><br />
<br />
:'''Since Mudlet version 3.8 :''' this facility has been extended:<br />
:* This function will now take a short string of any printable characters as a room ''symbol'', and they will be shrunk to fit them all in horizontally but if they become too small that ''symbol'' may not be shown if the zoom is such that the room symbol is too small to be legible.<br />
:* As "_" is now a valid character an existing symbol may be erased with either a space " " or an empty string "" although neither may be effective in some previous versions of Mudlet.<br />
:* Should the rooms be set to be drawn as circles this is now accommodated and the symbol will be resized to fit the reduce drawing area this will cause.<br />
:* The range of characters that are available are now dependent on the '''fonts''' present in the system and a setting on the "Mapper" tab in the preferences that control whether a specific font is to be used for all symbols (which is best if a font is included as part of a game server package, but has the issue that it may not be displayable if the user does not have that font or chooses a different one) or any font in the user's system may be used (which is the default, but may not display the ''glyph'' {the particular representation of a ''grapheme'' in a particular font} that the original map creator expected). Should it not be possible to display the wanted symbol in the map because one or more of the required glyphs are not available in either the specified or any font depending on the setting then the ''replacement character'' (Unicode ''code-point'' U+FFFD '�') will be shown instead. To allow such missing symbols to be handled the "Mapper" tab on the preferences dialogue has an option to display:<br />
::* an indicator to show whether the symbol can be made just from the selected font (green tick), from the fonts available in the system (yellow warning triangle) or not at all (red cross)<br />
::* all the symbols used on the map and how they will be displayed both only using the selected font and all fonts<br />
::* the sequence of code-points used to create the symbol which will be useful when used in conjunction with character selection utilities such as ''charmap.exe'' on Windows and ''gucharmap'' on unix-like system<br />
::* a count of the rooms using the particular symbol<br />
::* a list, limited in entries of the first rooms using that symbol<br />
:* The font that is chosen to be used as the primary (or only) one for the room symbols is stored in the Mudlet map data so that setting will be included if a binary map is shared to other Mudlet users or profiles on the same system.<br />
<br />
: See also: [[#getRoomChar|getRoomChar()]]<br />
<br />
==setRoomCharColor==<br />
;setRoomCharColor(roomId, r, g, b)<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to to set char color to.<br />
* ''r:''<br />
: Red component of room char color (0-255)<br />
* ''g:''<br />
: Green component of room char color (0-255)<br />
* ''b:''<br />
: Blue component of room char color (0-255)<br />
<br />
Sets color for room symbol.<br />
<br />
<syntaxhighlight lang="lua"><br />
setRoomCharColor(2402, 255, 0, 0)<br />
setRoomCharColor(2403, 0, 255, 0)<br />
setRoomCharColor(2404, 0, 0, 255)<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.11}}<br />
<br />
: See also: [[#unsetRoomCharColor|unsetRoomCharColor()]]<br />
<br />
==setRoomCoordinates==<br />
;setRoomCoordinates(roomID, x, y, z)<br />
<br />
:Sets the given room ID to be at the following coordinates visually on the map, where ''z'' is the up/down level. These coordinates are define the location of the room within a particular area (so not globally on the overall map).<br />
<br />
{{note}} 0,0,0 is the center of the map.<br />
<br />
;Examples<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^set rc (-?\d+) (-?\d+) (-?\d+)$<br />
-- this sets the current room to the supplied coordinates<br />
setRoomCoordinates(roomID,x,y,z)<br />
centerview(roomID)<br />
</syntaxhighlight><br />
<br />
:You can make them relative asa well:<br />
<br />
<syntaxhighlight lang="lua"><br />
-- alias pattern: ^src (\w+)$<br />
<br />
local x,y,z = getRoomCoordinates(previousRoomID)<br />
local dir = matches[2]<br />
<br />
if dir == "n" then<br />
y = y+1<br />
elseif dir == "ne" then<br />
y = y+1<br />
x = x+1<br />
elseif dir == "e" then<br />
x = x+1<br />
elseif dir == "se" then<br />
y = y-1<br />
x = x+1<br />
elseif dir == "s" then<br />
y = y-1<br />
elseif dir == "sw" then<br />
y = y-1<br />
x = x-1<br />
elseif dir == "w" then<br />
x = x-1<br />
elseif dir == "nw" then<br />
y = y+1<br />
x = x-1<br />
elseif dir == "u" or dir == "up" then<br />
z = z+1<br />
elseif dir == "down" then<br />
z = z-1<br />
end<br />
setRoomCoordinates(roomID,x,y,z)<br />
centerview(roomID)<br />
</syntaxhighlight><br />
<br />
==setRoomEnv==<br />
;setRoomEnv(roomID, newEnvID)<br />
<br />
:Sets the given room to a new environment ID. You don't have to use any functions to create it - can just set it right away.<br />
: See also: [[#setCustomEnvColor|setCustomEnvColor()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomEnv(551, 34) -- set room with the ID of 551 to the environment ID 34<br />
</syntaxhighlight><br />
<br />
==setRoomIDbyHash==<br />
;setRoomIDbyHash(roomID, hash)<br />
<br />
:Sets the hash to be associated with the given roomID. See also [[#getRoomIDbyHash|getRoomIDbyHash()]].<br />
<br />
:If the room was associated with a different hash, or vice versa, that association will be superseded.<br />
<br />
==setRoomName==<br />
;setRoomName(roomID, newName)<br />
<br />
:Renames an existing room to a new name.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomName(534, "That evil room I shouldn't visit again.")<br />
lockRoom(534, true) -- and lock it just to be safe<br />
</syntaxhighlight><br />
<br />
==setRoomUserData==<br />
;setRoomUserData(roomID, key (as a string), value (as a string))<br />
<br />
:Stores information about a room under a given key. Similar to Lua's key-value tables, except only strings may be used here. One advantage of using userdata is that it's stored within the map file itself - so sharing the map with someone else will pass on the user data. You can have as many keys as you'd like. <br />
<br />
:Returns true if successfully set.<br />
: See also: [[#clearRoomUserData|clearRoomUserData()]], [[#clearRoomUserDataItem|clearRoomUserDataItem()]], [[#getAllRoomUserData|getAllRoomUserData()]], [[#getRoomUserData|getRoomUserData()]], [[#searchRoomUserData|searchRoomUserData()]]<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- can use it to store room descriptions...<br />
setRoomUserData(341, "description", "This is a plain-looking room.")<br />
<br />
-- or whenever it's outdoors or not...<br />
setRoomUserData(341, "outdoors", "true")<br />
<br />
-- how how many times we visited that room<br />
local visited = getRoomUserData(341, "visitcount")<br />
visited = (tonumber(visited) or 0) + 1<br />
setRoomUserData(341, "visitcount", tostring(visited))<br />
<br />
-- can even store tables in it, using the built-in yajl.to_string function<br />
setRoomUserData(341, "some table", yajl.to_string({name = "bub", age = 23}))<br />
display("The denizens name is: "..yajl.to_value(getRoomUserData(341, "some table")).name)<br />
</syntaxhighlight><br />
<br />
==setRoomWeight==<br />
;setRoomWeight(roomID, weight)<br />
<br />
:Sets a weight to the given roomID. By default, all rooms have a weight of 1 - the higher the weight is, the more likely the room is to be avoided for pathfinding. For example, if travelling across water rooms takes more time than land ones - then you'd want to assign a weight to all water rooms, so they'd be avoided if there are possible land pathways.<br />
<br />
{{note}} The minimum allowed room weight is 1. <br />
<br />
:To completely avoid a room, make use of [[#lockRoom|lockRoom()]].<br />
<br />
: See also: [[#getRoomWeight|getRoomWeight()]]<br />
<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
setRoomWeight(1532, 3) -- avoid using this room if possible, but don't completely ignore it<br />
</syntaxhighlight><br />
<br />
<br />
==speedwalk==<br />
;speedwalk(dirString, backwards, delay, show)<br />
<br />
:A speedwalking function will work on cardinal+ordinal directions (n, ne, e, etc.) as well as u (for up), d (for down), in and out. It can be called to execute all directions directly after each other, without delay, or with a custom delay, depending on how fast your game allows you to walk. It can also be called with a switch to make the function reverse the whole path and lead you backwards.<br />
<br />
:Call the function by doing: <code>speedwalk("YourDirectionsString", true/false, delaytime, true/false)</code><br />
<br />
:The delaytime parameter will set a delay between each move (set it to 0.5 if you want the script to move every half second, for instance). It is optional: If you don't indicate it, the script will send all direction commands right after each other. (If you want to indicate a delay, you -have- to explicitly indicate true or false for the reverse flag.)<br />
<br />
:The show parameter will determine if the commands sent by this function are shown or hidden. It is optional: If you don't give a value, the script will show all commands sent. (If you want to use this option, you -have- to explicitly indicate true or false for the reverse flag, as well as either some number for the delay or nil if you do not want a delay.)<br />
<br />
:The "YourDirectionsString" contains your list of directions and steps (e.g.: "2n, 3w, u, 5ne"). Numbers indicate the number of steps you want it to walk in the direction specified after it. The directions must be separated by anything other than a letter that can appear in a direction itself. (I.e. you can separate with a comma, spaces, the letter x, etc. and any such combinations, but you cannot separate by the letter "e", or write two directions right next to each other with nothing in-between, such as "wn". If you write a number before every direction, you don't need any further separator. E.g. it's perfectly acceptable to write "3w1ne2e".) The function is not case-sensitive.<br />
<br />
:If your game only has cardinal directions (n,e,s,w and possibly u,d) and you wish to be able to write directions right next to each other like "enu2s3wdu", you'll have to change the pattern slightly. Likewise, if your game has any other directions than n, ne, e, se, s, sw, w, nw, u, d, in, out, the function must be adapted to that.<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
speedwalk("16d1se1u")<br />
-- Will walk 16 times down, once southeast, once up. All in immediate succession.<br />
<br />
speedwalk("2ne,3e,2n,e")<br />
-- Will walk twice northeast, thrice east, twice north, once east. All in immediate succession.<br />
<br />
speedwalk("IN N 3W 2U W", false, 0.5)<br />
-- Will walk in, north, thrice west, twice up, west, with half a second delay between every move.<br />
<br />
speedwalk("5sw - 3s - 2n - w", true)<br />
-- Will walk backwards: east, twice south, thrice, north, five times northeast. All in immediate succession.<br />
<br />
speedwalk("3w, 2ne, w, u", true, 1.25)<br />
-- Will walk backwards: down, east, twice southwest, thrice east, with 1.25 seconds delay between every move.<br />
</syntaxhighlight><br />
<br />
{{note}} The probably most logical usage of this would be to put it in an alias. For example, have the pattern ''^/(.+)$'' execute: <code>speedwalk(matches[2], false, 0.7)</code><br />
And have ''^//(.+)$'' execute: <code>speedwalk(matches[2], true, 0.7)</code><br />
Or make aliases like: ''^banktohome$'' to execute <syntaxhighlight lang="lua" inline>speedwalk("2ne,e,ne,e,3u,in", true, 0.5)</syntaxhighlight><br />
<br />
{{note}} The show parameter for this function is available in Mudlet 3.12+<br />
<br />
==stopSpeedwalk==<br />
;stopSpeedwalk()<br />
<br />
:Stops a speedwalk started using [[#speedwalk|speedwalk()]]<br />
: See also: [[#pauseSpeedwalk|pauseSpeedwalk()]], [[#resumeSpeedwalk|resumeSpeedwalk()]], [[#speedwalk|speedwalk()]]<br />
<br />
{{MudletVersion|4.13}}<br />
<br />
<syntaxhighlight lang="lua"><br />
local ok, err = stopSpeedwalk()<br />
if not ok then<br />
cecho(f"\n<red>Error:<reset> {err}")<br />
return<br />
end<br />
cecho(f"\n<green>Success:<reset> speedwalk stopped")<br />
</syntaxhighlight><br />
<br />
==unHighlightRoom==<br />
;unHighlightRoom(roomID)<br />
<br />
:Unhighlights a room if it was previously highlighted and restores the rooms original environment color.<br />
: See also: [[#highlightRoom|highlightRoom()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
unHighlightRoom(4534)<br />
</syntaxhighlight><br />
<br />
==unsetRoomCharColor==<br />
;unsetRoomCharColor(roomId)<br />
<br />
;Parameters<br />
* ''roomID:''<br />
: Room ID to to unset char color to.<br />
<br />
Removes char color setting from room, back to automatic determination based on room background lightness.<br />
<br />
<syntaxhighlight lang="lua"><br />
unsetRoomCharColor(2031)<br />
</syntaxhighlight><br />
<br />
{{MudletVersion|4.11}}<br />
<br />
==updateMap==<br />
;updateMap()<br />
<br />
:Updates the mapper display (redraws it). Use this function if you've edited the map via script and would like the changes to show.<br />
<br />
: See also: [[#centerview|centerview()]]<br />
<br />
;Example<br />
<syntaxhighlight lang="lua"><br />
-- delete a some room<br />
deleteRoom(500)<br />
-- now make the map show that it's gone<br />
updateMap()<br />
</syntaxhighlight><br />
<br />
[[Category:Mudlet Manual]]<br />
[[Category:Mudlet API]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Mapping_script&diff=20302Mapping script2023-02-01T20:46:27Z<p>Kebap: All content was moved to Manual:Mapper so turn this page into a mere redirect</p>
<hr />
<div>#redirect [[Manual:Mapper]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Mapper&diff=20301Manual:Mapper2023-02-01T20:43:17Z<p>Kebap: Move section on Visual Editor to the front, to not scare newbies with a wall of text about Autowalking</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Manual on creating maps, areas, rooms, and advanced features like autowalking, creating lables, custom exit lines, etc.}}<br />
<br />
= Mapper =<br />
Mudlet's mapper is split into two parts for the best compatibility on all games: <br />
# The display of the map itself and functions to modify the map in Mudlet, and <br />
# A very game-specific Lua script to track where you are, and provide aliases for using the mapper, automatic mapping, etc.<br />
<br />
If your game does not provide a mapping script for you, then you may not see a map at first. <br />
<br />
Fear not! Pre-made mapping scripts for many games are available from [https://forums.mudlet.org/search.php?keywords=mapping+script&terms=all&author=&sc=1&sf=titleonly&sr=topics&sk=t&sd=d&st=0&ch=400&t=0&submit=Search Mudlet forums] - all topics that have the "mapping script"-prefix on them. <br />
<br />
If you still don't find any, or if you want to create your own mapping script, see [[#Making your own mapping script]] further down below. Remember, you can always find help in Mudlet forums or Discord, etc. <br />
<br />
==Visual Map Editor==<br />
Maps can be comfortably edited by using the visual map editor or by scripts. The editor behaves like the usual WYSIWYG editors. Select objects with a left click and then right click to open a context menus and do actions on the selected objects.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
The mapper starts in "view-only" mode to prevent accidental edits. The editing mode can be toggled in the map's right-click menu.<br />
<br />
===Object selection===<br />
<br />
* left click = select element<br />
* left click + drag = sizing group selection box choosing all rooms in the box on the current z-level<br />
* left click + shift + drag = sizing group selection box choosing all rooms in the box on all z-levels<br />
* left click + alt (or the mapper menu move map buttons) = move map<br />
* left click + control = add a room to current group selection or remove it<br />
<br />
If multiple rooms are being selected, a room id selection list box is being shown where you can fine tune the current room selection via the usual ''left click + control'' or ''left click + shift''. The box disappears if the number of rooms in group selection is zero.<br />
<br />
===Moving Objects===<br />
Move selected objects either by right click and select "move" or with following handy short cut:<br />
<br />
* left button down on custom line point + drag = move custom line point<br />
* left button down + drag usually moves the item directly (as a handy shortcut) if only one element has been selected<br />
* '''or''' hold left button down + control + drag if multiple rooms have been selected<br />
<br />
== Maps and Autowalking ==<br />
Maps are implemented as directed graphs of connected nodes (rooms). Nodes are connected by edges (exits). Nodes are referenced by unique integer IDs. Edges fall into 2 categories: Standard exits with a visual representation on the map (e. g. north, south) and "special exits" without a calculated visual representation on the map e. g. the command "jump cliff" is a special exit that connects to a room without a clear spatial orientation. However, special exits can be visually represented if the user provides custom exit line strips. Standard exits are referenced by their respective node and a directional integer value. Special exits are referenced by their respective nodes and strings that hold the exit commands. Both nodes and individual exits can seperately be locked and thus excluded from speed walk path finding graphs. Path finding uses the fast A* search algorithm. Mudlet choses a path with the fastest travel time (-> room weights) as opposed to the shortest path.<br />
<br />
Maps are divided into areas or zones where the area/room relationship is unique, i. e. rooms cannot be in more than 1 area. <br />
<br />
{{note}}Areas help make do with the typical geographical irregularities of game maps where an entire city with hundrets of rooms makes up a single room on a wilderness map. In other words, if you can't make a place look geographically correctly, create (sub) areas to deal with the problem.<br />
<br />
There are 2 forms of visual representations of maps. Standard mode shows exits and custom exit lines whereas "grid mode" hides exit details and sizes rooms to form a perfect grid without any empty space in between rooms. Grid maps can be made to look exactly like ASCII color text maps with character symbols to keep the look and feel of the game. Technically, grid maps are a special optimized representation of the typically very large LPC MUD style wilderness maps where every room has 8 direct neighbors in a n*m grid of rooms with relatively few holes. The grid map implementation uses pre image caching and fast gfx hardware render support and can thus render very large grid maps in less than 1ms that would take much longer if the map were to be displayed in regular mode. Changing the zoom level of maps in grid mode can take a significant amount of time if the maps are very large, because the pre cached images of the map need to be recreated at the new zoom level. Areas remember their particular zoom level so this is no hindering issue in actual gameplay.<br />
<br />
Any map can be displayed in both modes, though the visual map editor only works in regular mode. To enable area mode, use the [[Manual:Lua Functions#setGridMode|setGridMode()]] function.<br />
<br />
Regular mode:<br />
<br />
[[File:Mapper-regular-mode.png|frameless|716x716px]]<br />
<br />
Grid mode:<br />
<br />
[[File:Mapper-grid-mode.png|frameless|713x713px]]<br />
=== Areas ===<br />
Areas are defined by a unique integer number ID and a unique area name. Mudlet builds an internal numerical area ID table on the basis of the rooms that belong to the respective areas. Mudlet keeps a seperate lookup table to retrieve the area name on the basis of the area IDs. This name lookup table is not guaranteed to be correct because it may be imported invalid information if the map has been downloaded by the game server as an xml map description file on the basis of the MMP protocol. <ref>MMP allows for an area ID/area names table to be defined, but Mudlet has no means to verify which definition is the correct one if 2 different area names relate to the same area ID.</ref> However, if the map has been created with Mudlet directly, there will be no such problems as the area name lookup table API is made to enforce uniqueness.<br />
<br />
==== Area Properties ====<br />
* area map display mode (-> regular map display mode or grid mode)<br />
* area name<br />
<br />
=== Rooms ===<br />
Rooms are invisible on the map unless the required properties have been set.<br />
==== Room Properties ====<br />
*Room object need following required properties in order to be shown on the respective area map:<br />
** unique room ID in form of an integer value <br />
** area ID in form of an integer value (To which area does this room belong - or in other words, which area map displays this room)<br />
** x, y and z coordinates as integer values which relate to its paricular area map coordinate system<br />
<br />
*Optional room properties:<br />
** regular exits with or without respective exit locks<br />
** special exits with or without respecitve special exit locks<br />
** room lock<br />
** exit stubs (draw exit directions even though the exit rooms have not yet been defined)<br />
** custom exit lines (user defined line strips of various formats to visualize special exits or redefine regular exit lines)<br />
** searchable room name that can be used for bookmarks, annotations etc. <br />
** room weight (How long does it travel through this node. A high room weight makes it less likely that this room will be chosen for pathfinding e. g. a safe road should have a low weight, whereas a dangerous place should have a high weight<br />
** room color<br />
** room character e. g. the symbol $ to symbolize a bank or H for a hotel.<br />
<br />
== Advanced map features ==<br />
=== Map labels ===<br />
Maps can be embellished with images and text labels. Map labels can be either used as background (default) or as the top most foreground e. g. for player name location scripts. Labels are defined by position and size according to the map coordinate system and keep their position and size relative to the rest of the map when the map is zoomed or moved.<br />
Contrary to rooms which work on the basis of integer (natural numbers) coordinates, labels are described (with respect to both position & size) by real numbers in order to allow for more advanced placement and label sizes within the map coordinate system. Map labels are stored in form of png images directly in the map file and are thus a direct part of the map. As these images are being scaled to fit the label creation size, the image quality will depend on the initial size of the label (the large the better the quality, but the more memory will be used).<br />
<br />
[[File:MapTextLabelDemo.PNG|250px|frameless|misc label types]]<br />
[[File:MalLabelsScaled.PNG|250px|frameless|zoomed]]<br />
[[File:MapBackgroundImageLabel.PNG|250px|frameless|label as background image]]<br />
<br />
(The desert and dragon images used in this example are licensed under the Creative Commons Attribution 2.0 Generic license and can be found here: http://en.wikipedia.org/wiki/File:Ninedragonwallpic1.jpg and http://en.wikipedia.org/wiki/File:Siwa_sand_dunes2009a.jpg)<br />
<br />
=== Custom exit line definitions ===<br />
The mapper supports user defined visual exit lines on the basis of a sequence of line points in the map coordinate system. Custom lines as well as labels work on real numbers to allow for fine grained placement. User defined lines can be solid, dotted, dashed etc. line types with or without ending arrows. The line color can be freely selected. By default the regular exit color is being used.<br />
<br />
[[File:CustomExitSelection.PNG|400px|frameless|custom exit line demo]] [[File:DifficultGeography.PNG|500px|frameless|custom exit line demo]]<br />
<br />
The above example shows 3 different types of user defined exit lines, where the orange one on the left has been selected by the user in order to be edited.<br />
<br />
Custom exit lines are purely visual tools and have no effect on the pathfinding, but each custom line must be linked to a valid room exit - either standard or special exit.<br />
<br />
=== Map formats ===<br />
Whenever a mapping feature is added to Mudlet that requires storing something in the map, the map format version needs to be increased - so older Mudlets can know that a map is too new and they can't load it. To this end, every map has a version number embedded inside it, which you can see by going to mapper settings:<br />
<br />
[[File:Map formats setting.png]]<br />
<br />
You'll also notice that you have the ability to downgrade a map's version for compatibility with older Mudlets. Be careful when you do so though - features available in the new map won't be available in the older map when you downgrade. Here's a table of all the versions and features:<br />
<br />
{| class="wikitable"<br />
! style="font-weight: bold;" | version<br />
! style="font-weight: bold;" | Mudlet version<br />
! style="font-weight: bold;" | features<br />
|-<br />
| 20<br />
| 3.16.0<br />
| - Improved way that custom exit line data was held internally, to make coding Mudlet mapper's easier and safer ([https://github.com/Mudlet/Mudlet/pull/2999 details]). Code is in place to support a workaround to work within map formats back to include version 17.<br />
|- <br />
| 19<br />
| 3.8.0<br />
| - added support for more than one of any grapheme (symbol) for the 2D map room symbol. Code is in place to support a workaround to work within map formats back to including version 17.<br />
|-<br />
| 18<br />
| 3.0.0<br />
| - keeps player's position when copying to a new profile<br />
- faster map loading<br />
|-<br />
| 17<br />
| 3.0.0<br />
| - allows use of setAreaUserData(), setMapUserData(), and related functions<br />
|-<br />
| 16<br />
| 2.1<br />
| - doors (visual effect on the mapper that a locked/closed/open door is there)<br />
- exit weights (in addition to existing room weights)<br />
|}<br />
<br />
== Mapper tips ==<br />
<br />
=== General ===<br />
<br />
* Don't move the room you're currently in, you'll go haywire<br />
* The number when spreading/shrinking room selections it the ''multiplication'' factor - 2 is a good number to try<br />
<br />
=== Merging areas ===<br />
<br />
To merge two areas together, see [https://forums.mudlet.org/viewtopic.php?f=8&t=2273&view=unread#unread this how-to by Heiko]. In short:<br />
<br />
# Zoom out ''really'' far away on the area you'd like to move, and select everything (the selection affects all z-levels as well). <br />
# Right-click, select ''move to area'', and move them to another area. Your selection will still be selected - do '''not''' unselect <br />
# Right-click again, select ''move to position'', and move all of your still selected rooms in the new area so it fits.<br />
<br />
=== Zooming the mapper ===<br />
<br />
You can zoom in/out in the mapper using your (vertical) mousewheel. If you'd like to zoom quicker, hold down <code>Ctrl</code> while doing so!<br />
<br />
To set the zoom level via script, use [[Manual:Mapper_Functions#setMapZoom|setMapZoom()]].<br />
<br />
<br />
=== Add a right-click menu to your mapper ===<br />
<br />
It is easy to add your own options to the menu you see when you right-click on your map. To do so, use [[Manual:Mapper_Functions#addMapMenu|addMapMenu]], [[Manual:Mapper_Functions#addMapEvent|addMapEvent]], etc.<br />
<br />
==== Mapper favorites ====<br />
<br />
[http://forums.mudlet.org/viewtopic.php?f=6&t=2739 This post here] describes how to add a right click menu to your mapper filled with rooms to speedwalk to.<br />
<br />
=== Placing the mapper ===<br />
<br />
==== Placing the mapper into a corner ====<br />
<br />
Here's a snippet you can use to place the mapper window into a corner and have it automatically come up whenever you open Mudlet. To use this, create a new script (you can make it anywhere) and copy/paste the code into it.<br />
<br />
<syntaxhighlight lang="lua" highlight="5" line><br />
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})<br />
<br />
local mapper = Geyser.Mapper:new({<br />
name = "mapper",<br />
x = "70%", y = 0, -- edit here if you want to move it<br />
width = "30%", height = "50%"<br />
}, main)<br />
</syntaxhighlight><br />
==== Placing the mapper into its own window ====<br />
<br />
{{MudletVersion|4.7+}}<br />
<br />
It's possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded=false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation, use:<br />
<syntaxhighlight lang="lua"> -- this will create a map window docked at the left corner<br />
myMapWidget = Geyser.Mapper:new({embedded=false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are: left "l", right "r", top "t", bottom "b" and floating "f"<br />
<br />
To change the dockPosition after creation, use:<br />
<syntaxhighlight lang="lua"> -- this will change myMapWidget dockPosition to "f" floating <br />
myMapWidget:setDockPosition("f")<br />
</syntaxhighlight><br />
<br />
== Making your own mapping script ==<br />
<br />
If you'd like to code your own mapping script, see the [[Manual:Lua_Functions#Mapper_Functions|Mapper API]] and read on for a short tutorial.<br />
<br />
To start off, create a new script that'll be included with your mapping script (can even place it into the script folder for your mapping script), and have it do:<br />
<br />
<syntaxhighlight lang="lua"><br />
mudlet = mudlet or {}; mudlet.mapper_script = true<br />
</syntaxhighlight><br />
<br />
This'll let Mudlet know that a mapping script is installed, so it won't bother you or whoever else installs your script with a warning that one is necessary.<br />
<br />
Next, you want to hook into Mudlet's gotoRoom(id) function and the user clicking on a room in the visual map - for that, define your own ''doSpeedWalk()'' function. Mudlet will store the directions / special exits commands your script will need to take in the ''speedWalkDir'' table, and the room IDs you'll pass through in the ''speedWalkPath'' table:<br />
<br />
<syntaxhighlight lang="lua"><br />
function doSpeedWalk()<br />
echo("Path we need to take: " .. table.concat(speedWalkDir, ", ") .. "\n")<br />
echo("Rooms we'll pass through: " .. table.concat(speedWalkPath, ", ") .. "\n")<br />
end<br />
</syntaxhighlight><br />
<br />
''speedWalkPath'' is especially useful for making sure you're still on the path. Most Mudlet mapping scripts keep track of how many rooms along the path they have visited so far and check upon arrival into a new room to make sure it's still on the path.<br />
<br />
That's it! (But see below if you want more.)<br />
<br />
From here, you'd want to build a walking script that'll send the commands to walk you along the path, along with aliases for the user to use - see the [[Manual:Lua_Functions#Mapper_Functions|Mapper API functions]] and [[Manual:Event_Engine#Mudlet-raised_events|Mudlet mapper events]].<br />
<br />
=== Adding rooms ===<br />
To make your first room, do the following steps:<br />
<br />
* create an area with setAreaName(areaID, areaname). You can choose any areaID - if you'd like to use the IDs incrementally, see which is the latest from getAreaTable()<br />
* if you want the Mudlet mapper to generate roomIDs for you, get one with createRoomID(). This is an optional step<br />
* create your room with addRoom(roomID)<br />
* give the room coordinates with setRoomCoordinates(roomID, x, y, z). If you're just starting out, put it at 0,0,0 so the room is at the center of the map<br />
* assign your room to an area with setRoomArea(roomID, areaID)<br />
* and finally, call centerview(roomID) to make the map view refresh and show your new room!<br />
<br />
==== Labelling rooms ====<br />
<br />
Rooms have three attributes which you can show on the map:<br />
* an ID. You can't change it; the ID is shown in the room's box when you check "IDs" in the dialog below the map and you're zoomed in far enough.<br />
* a symbol, also displayed in the room's box. You set it with the [https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomChar ''setRoomChar''] Lua function, or via the map's context menu.<br />
* a name, typically sent via GMCP. You add it to the map with [https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomName ''setRoomName''].<br />
<br />
The room name can be displayed along with a room's box. Its position defaults to "centered below the room". It is not visible by default because many maps have rooms that are quite close to each other; showing the names by default would create an ugly visual mess.<br />
<br />
If you want to enable room names in your mapper, you need to<br />
* stagger rooms. Four or five units' distance instead of one works best if you want to show every label; less is OK if you only show labels when the user asks you to.<br />
* call ''setMapUserData("room.ui_showName","1")''. The existence of this entry controls whether the "Names" checkbox is shown next to "IDs", below the map. This value is zero if the user has unchecked the "Names" checkbox.<br />
* optionally call ''setMapUserData("room.ui_nameFont","FontName")'' to change the names' font. The default is the same monospaced font used for the room IDs and symbols.<br />
* call ''setRoomUserData(room_id, "room.ui_showName","1")'' to show a room's label. You might want to add an entry to the map's pop-up menu which toggles this.<br />
<br />
If the name is misplaced (collision with another room, label, or whatever), you can modify the room's "room.ui_nameOffset" attribute to move it around. The value of this attribute consists of two floating-point values, separated by a space, which offset the room's label (in units of the room box's size). You might want to bind functions that increase or decrease these values to keys like Shift-Control-Arrow and/or Control-Numpad-2468. A hotkey to toggle a room's label display from "on" to "off" and back (e.g. Control-Numpad-5?) is also a good idea.<br />
<br />
You also might default to staggering room names. One possible algorithm: '''if''' a new room's X coordinate, divided by your default room distance, is an odd number '''then''' position its label with an offset like "0 -1.6", which would place it above the room in question. The optimal value for the Y offset depends on the font.<br />
<br />
Changes are displayed only when the map is next redrawn.<br />
<br />
Font options are global. Overriding them for a single room can be be implemented if requested.<br />
<br />
=== Working with the mapper API ===<br />
Whenever working with mapper API, keep in mind of the following things:<br />
<br />
* You'll want to call centerview after you do some modifications, to get to have the map render your new changes<br />
<br />
=== Translating directions ===<br />
Several functions in the mapper API take and return #'s for directions - and to make it easier to work with them, you can define a table that maps directions to those numbers in a script with the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
exitmap = {<br />
n = 1,<br />
north = 1,<br />
ne = 2,<br />
northeast = 2,<br />
nw = 3,<br />
northwest = 3,<br />
e = 4,<br />
east = 4,<br />
w = 5,<br />
west = 5,<br />
s = 6,<br />
south = 6,<br />
se = 7,<br />
southeast = 7,<br />
sw = 8,<br />
southwest = 8,<br />
u = 9,<br />
up = 9,<br />
d = 10,<br />
down = 10,<br />
["in"] = 11,<br />
out = 12,<br />
[1] = "north",<br />
[2] = "northeast",<br />
[3] = "northwest",<br />
[4] = "east",<br />
[5] = "west",<br />
[6] = "south",<br />
[7] = "southeast",<br />
[8] = "southwest",<br />
[9] = "up",<br />
[10] = "down",<br />
[11] = "in",<br />
[12] = "out",<br />
}<br />
</syntaxhighlight><br />
<br />
Then, using exitmap[input], you'll get a direction number or a direction name. Here's an example that uses it to work out in which directions are the exit stubs available in room 6:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local stubs = getExitStubs(6)<br />
for i = 0, #stubs do print(exitmap[stubs[i]]) end<br />
</syntaxhighlight><br />
<br />
=== Custom speedwalking and pathfinding ===<br />
<br />
{{MudletVersion|4.10}}<br />
If you'd like to use a custom pathfinding algorithm instead of the built-in one, you can do that:<br />
<br />
* Set ''mudlet.custom_speedwalk = true''.<br />
* Your ''doSpeedwalk'' script will now see different parameters:<br />
<br />
<syntaxhighlight lang="lua"><br />
function doSpeedWalk()<br />
echo("Room we're coming from: " .. speedWalkFrom .. "\n")<br />
echo("Room you're going to: " .. speedWalkTo .. "\n")<br />
end<br />
</syntaxhighlight><br />
<br />
The forum topic [https://forums.mudlet.org/viewtopic.php?f=6&t=22930&p=45930#p45930 Wayfinder] contains an example package that implements a shortest-path-first algorithm.<br />
<br />
=== Custom room name search function in the generic_mapper ===<br />
<br />
{{MudletVersion|4.11}}<br />
Sometimes the generic_mapper script is not flexible enough to find the room name in your favorite game. You can create a custom function that handle that search instead of the standard one included in the mapper:<br />
<br />
* Type in the input area ''map config custom_name_search true'' to enable the usage of the custom function.<br />
* Write your own function called ''mudlet.custom_name_search''. The script call it for your:<br />
<br />
<syntaxhighlight lang="lua"><br />
mudlet.custom_name_search = function (lines)<br />
-- ...<br />
local line_count = #lines + 1<br />
if string.match(cur_line, " ") then<br />
line_count = line_count - 1<br />
room_name = lines[line_count]<br />
-- map.echo("Name Search: room_nameome:" ..room_name) <br />
elseif string.find(cur_line,prompt_pattern) then<br />
-- ...<br />
return room_name<br />
end<br />
</syntaxhighlight><br />
<br />
I suggest to start from original name_search function in generic_mapper to avoid common problem.<br />
<br />
<br />
== Screenshots ==<br />
Just a few example maps from different players and games:<br />
<gallery><br />
File:Mapper 562.png<br />
File:Mudlet 563.png<br />
File:TK6fS.png<br />
File:Stary kontynent-min-scaled.png|Here is the [https://i.imgur.com/IaV6lDc.png full image] (17160 x 10120 pixel)<br />
File:MG Port Vain.png<br />
</gallery><br />
<br />
== Notes ==<br />
<references /><br />
<br />
[[Category:Mudlet Manual]]</div>Kebaphttps://wiki.mudlet.org/index.php?title=Manual:Mapper&diff=20300Manual:Mapper2023-02-01T20:40:52Z<p>Kebap: Standardize Mudlet version hints</p>
<hr />
<div>{{TOC right}}<br />
{{#description2:Manual on creating maps, areas, rooms, and advanced features like autowalking, creating lables, custom exit lines, etc.}}<br />
<br />
= Mapper =<br />
Mudlet's mapper is split into two parts for the best compatibility on all games: <br />
# The display of the map itself and functions to modify the map in Mudlet, and <br />
# A very game-specific Lua script to track where you are, and provide aliases for using the mapper, automatic mapping, etc.<br />
<br />
If your game does not provide a mapping script for you, then you may not see a map at first. <br />
<br />
Fear not! Pre-made mapping scripts for many games are available from [https://forums.mudlet.org/search.php?keywords=mapping+script&terms=all&author=&sc=1&sf=titleonly&sr=topics&sk=t&sd=d&st=0&ch=400&t=0&submit=Search Mudlet forums] - all topics that have the "mapping script"-prefix on them. <br />
<br />
If you still don't find any, or if you want to create your own mapping script, see [[#Making your own mapping script]] further down below. Remember, you can always find help in Mudlet forums or Discord, etc. <br />
<br />
== Maps and Autowalking ==<br />
Maps are implemented as directed graphs of connected nodes (rooms). Nodes are connected by edges (exits). Nodes are referenced by unique integer IDs. Edges fall into 2 categories: Standard exits with a visual representation on the map (e. g. north, south) and "special exits" without a calculated visual representation on the map e. g. the command "jump cliff" is a special exit that connects to a room without a clear spatial orientation. However, special exits can be visually represented if the user provides custom exit line strips. Standard exits are referenced by their respective node and a directional integer value. Special exits are referenced by their respective nodes and strings that hold the exit commands. Both nodes and individual exits can seperately be locked and thus excluded from speed walk path finding graphs. Path finding uses the fast A* search algorithm. Mudlet choses a path with the fastest travel time (-> room weights) as opposed to the shortest path.<br />
<br />
Maps are divided into areas or zones where the area/room relationship is unique, i. e. rooms cannot be in more than 1 area. <br />
<br />
{{note}}Areas help make do with the typical geographical irregularities of game maps where an entire city with hundrets of rooms makes up a single room on a wilderness map. In other words, if you can't make a place look geographically correctly, create (sub) areas to deal with the problem.<br />
<br />
There are 2 forms of visual representations of maps. Standard mode shows exits and custom exit lines whereas "grid mode" hides exit details and sizes rooms to form a perfect grid without any empty space in between rooms. Grid maps can be made to look exactly like ASCII color text maps with character symbols to keep the look and feel of the game. Technically, grid maps are a special optimized representation of the typically very large LPC MUD style wilderness maps where every room has 8 direct neighbors in a n*m grid of rooms with relatively few holes. The grid map implementation uses pre image caching and fast gfx hardware render support and can thus render very large grid maps in less than 1ms that would take much longer if the map were to be displayed in regular mode. Changing the zoom level of maps in grid mode can take a significant amount of time if the maps are very large, because the pre cached images of the map need to be recreated at the new zoom level. Areas remember their particular zoom level so this is no hindering issue in actual gameplay.<br />
<br />
Any map can be displayed in both modes, though the visual map editor only works in regular mode. To enable area mode, use the [[Manual:Lua Functions#setGridMode|setGridMode()]] function.<br />
<br />
Regular mode:<br />
<br />
[[File:Mapper-regular-mode.png|frameless|716x716px]]<br />
<br />
Grid mode:<br />
<br />
[[File:Mapper-grid-mode.png|frameless|713x713px]]<br />
=== Areas ===<br />
Areas are defined by a unique integer number ID and a unique area name. Mudlet builds an internal numerical area ID table on the basis of the rooms that belong to the respective areas. Mudlet keeps a seperate lookup table to retrieve the area name on the basis of the area IDs. This name lookup table is not guaranteed to be correct because it may be imported invalid information if the map has been downloaded by the game server as an xml map description file on the basis of the MMP protocol. <ref>MMP allows for an area ID/area names table to be defined, but Mudlet has no means to verify which definition is the correct one if 2 different area names relate to the same area ID.</ref> However, if the map has been created with Mudlet directly, there will be no such problems as the area name lookup table API is made to enforce uniqueness.<br />
<br />
==== Area Properties ====<br />
* area map display mode (-> regular map display mode or grid mode)<br />
* area name<br />
<br />
=== Rooms ===<br />
Rooms are invisible on the map unless the required properties have been set.<br />
==== Room Properties ====<br />
*Room object need following required properties in order to be shown on the respective area map:<br />
** unique room ID in form of an integer value <br />
** area ID in form of an integer value (To which area does this room belong - or in other words, which area map displays this room)<br />
** x, y and z coordinates as integer values which relate to its paricular area map coordinate system<br />
<br />
*Optional room properties:<br />
** regular exits with or without respective exit locks<br />
** special exits with or without respecitve special exit locks<br />
** room lock<br />
** exit stubs (draw exit directions even though the exit rooms have not yet been defined)<br />
** custom exit lines (user defined line strips of various formats to visualize special exits or redefine regular exit lines)<br />
** searchable room name that can be used for bookmarks, annotations etc. <br />
** room weight (How long does it travel through this node. A high room weight makes it less likely that this room will be chosen for pathfinding e. g. a safe road should have a low weight, whereas a dangerous place should have a high weight<br />
** room color<br />
** room character e. g. the symbol $ to symbolize a bank or H for a hotel.<br />
<br />
== Advanced map features ==<br />
=== Map labels ===<br />
Maps can be embellished with images and text labels. Map labels can be either used as background (default) or as the top most foreground e. g. for player name location scripts. Labels are defined by position and size according to the map coordinate system and keep their position and size relative to the rest of the map when the map is zoomed or moved.<br />
Contrary to rooms which work on the basis of integer (natural numbers) coordinates, labels are described (with respect to both position & size) by real numbers in order to allow for more advanced placement and label sizes within the map coordinate system. Map labels are stored in form of png images directly in the map file and are thus a direct part of the map. As these images are being scaled to fit the label creation size, the image quality will depend on the initial size of the label (the large the better the quality, but the more memory will be used).<br />
<br />
[[File:MapTextLabelDemo.PNG|250px|frameless|misc label types]]<br />
[[File:MalLabelsScaled.PNG|250px|frameless|zoomed]]<br />
[[File:MapBackgroundImageLabel.PNG|250px|frameless|label as background image]]<br />
<br />
(The desert and dragon images used in this example are licensed under the Creative Commons Attribution 2.0 Generic license and can be found here: http://en.wikipedia.org/wiki/File:Ninedragonwallpic1.jpg and http://en.wikipedia.org/wiki/File:Siwa_sand_dunes2009a.jpg)<br />
<br />
=== Custom exit line definitions ===<br />
The mapper supports user defined visual exit lines on the basis of a sequence of line points in the map coordinate system. Custom lines as well as labels work on real numbers to allow for fine grained placement. User defined lines can be solid, dotted, dashed etc. line types with or without ending arrows. The line color can be freely selected. By default the regular exit color is being used.<br />
<br />
[[File:CustomExitSelection.PNG|400px|frameless|custom exit line demo]] [[File:DifficultGeography.PNG|500px|frameless|custom exit line demo]]<br />
<br />
The above example shows 3 different types of user defined exit lines, where the orange one on the left has been selected by the user in order to be edited.<br />
<br />
Custom exit lines are purely visual tools and have no effect on the pathfinding, but each custom line must be linked to a valid room exit - either standard or special exit.<br />
<br />
=== Map formats ===<br />
Whenever a mapping feature is added to Mudlet that requires storing something in the map, the map format version needs to be increased - so older Mudlets can know that a map is too new and they can't load it. To this end, every map has a version number embedded inside it, which you can see by going to mapper settings:<br />
<br />
[[File:Map formats setting.png]]<br />
<br />
You'll also notice that you have the ability to downgrade a map's version for compatibility with older Mudlets. Be careful when you do so though - features available in the new map won't be available in the older map when you downgrade. Here's a table of all the versions and features:<br />
<br />
{| class="wikitable"<br />
! style="font-weight: bold;" | version<br />
! style="font-weight: bold;" | Mudlet version<br />
! style="font-weight: bold;" | features<br />
|-<br />
| 20<br />
| 3.16.0<br />
| - Improved way that custom exit line data was held internally, to make coding Mudlet mapper's easier and safer ([https://github.com/Mudlet/Mudlet/pull/2999 details]). Code is in place to support a workaround to work within map formats back to include version 17.<br />
|- <br />
| 19<br />
| 3.8.0<br />
| - added support for more than one of any grapheme (symbol) for the 2D map room symbol. Code is in place to support a workaround to work within map formats back to including version 17.<br />
|-<br />
| 18<br />
| 3.0.0<br />
| - keeps player's position when copying to a new profile<br />
- faster map loading<br />
|-<br />
| 17<br />
| 3.0.0<br />
| - allows use of setAreaUserData(), setMapUserData(), and related functions<br />
|-<br />
| 16<br />
| 2.1<br />
| - doors (visual effect on the mapper that a locked/closed/open door is there)<br />
- exit weights (in addition to existing room weights)<br />
|}<br />
<br />
==Visual Map Editor==<br />
Maps can be comfortably edited by using the visual map editor or by scripts. The editor behaves like the usual WYSIWYG editors. Select objects with a left click and then right click to open a context menus and do actions on the selected objects.<br />
<br />
{{MudletVersion|4.11}}<br />
<br />
The mapper starts in "view-only" mode to prevent accidental edits. The editing mode can be toggled in the map's right-click menu.<br />
<br />
===Object selection===<br />
<br />
* left click = select element<br />
* left click + drag = sizing group selection box choosing all rooms in the box on the current z-level<br />
* left click + shift + drag = sizing group selection box choosing all rooms in the box on all z-levels<br />
* left click + alt (or the mapper menu move map buttons) = move map<br />
* left click + control = add a room to current group selection or remove it<br />
<br />
If multiple rooms are being selected, a room id selection list box is being shown where you can fine tune the current room selection via the usual ''left click + control'' or ''left click + shift''. The box disappears if the number of rooms in group selection is zero.<br />
<br />
===Moving Objects===<br />
Move selected objects either by right click and select "move" or with following handy short cut:<br />
<br />
* left button down on custom line point + drag = move custom line point<br />
* left button down + drag usually moves the item directly (as a handy shortcut) if only one element has been selected<br />
* '''or''' hold left button down + control + drag if multiple rooms have been selected<br />
<br />
== Mapper tips ==<br />
<br />
=== General ===<br />
<br />
* Don't move the room you're currently in, you'll go haywire<br />
* The number when spreading/shrinking room selections it the ''multiplication'' factor - 2 is a good number to try<br />
<br />
=== Merging areas ===<br />
<br />
To merge two areas together, see [https://forums.mudlet.org/viewtopic.php?f=8&t=2273&view=unread#unread this how-to by Heiko]. In short:<br />
<br />
# Zoom out ''really'' far away on the area you'd like to move, and select everything (the selection affects all z-levels as well). <br />
# Right-click, select ''move to area'', and move them to another area. Your selection will still be selected - do '''not''' unselect <br />
# Right-click again, select ''move to position'', and move all of your still selected rooms in the new area so it fits.<br />
<br />
=== Zooming the mapper ===<br />
<br />
You can zoom in/out in the mapper using your (vertical) mousewheel. If you'd like to zoom quicker, hold down <code>Ctrl</code> while doing so!<br />
<br />
To set the zoom level via script, use [[Manual:Mapper_Functions#setMapZoom|setMapZoom()]].<br />
<br />
<br />
=== Add a right-click menu to your mapper ===<br />
<br />
It is easy to add your own options to the menu you see when you right-click on your map. To do so, use [[Manual:Mapper_Functions#addMapMenu|addMapMenu]], [[Manual:Mapper_Functions#addMapEvent|addMapEvent]], etc.<br />
<br />
==== Mapper favorites ====<br />
<br />
[http://forums.mudlet.org/viewtopic.php?f=6&t=2739 This post here] describes how to add a right click menu to your mapper filled with rooms to speedwalk to.<br />
<br />
=== Placing the mapper ===<br />
<br />
==== Placing the mapper into a corner ====<br />
<br />
Here's a snippet you can use to place the mapper window into a corner and have it automatically come up whenever you open Mudlet. To use this, create a new script (you can make it anywhere) and copy/paste the code into it.<br />
<br />
<syntaxhighlight lang="lua" highlight="5" line><br />
local main = Geyser.Container:new({x=0,y=0,width="100%",height="100%",name="mapper container"})<br />
<br />
local mapper = Geyser.Mapper:new({<br />
name = "mapper",<br />
x = "70%", y = 0, -- edit here if you want to move it<br />
width = "30%", height = "50%"<br />
}, main)<br />
</syntaxhighlight><br />
==== Placing the mapper into its own window ====<br />
<br />
{{MudletVersion|4.7+}}<br />
<br />
It's possible to create the mapper as a map window (similar to clicking the icon) like this:<br />
<syntaxhighlight lang="lua"><br />
myMapWidget = Geyser.Mapper:new({embedded=false})<br />
</syntaxhighlight><br />
<br />
This will open a map window with your saved layout (if there is one, otherwise it will dock at the right corner)<br />
<br />
To choose the position of the DockWindow at creation, use:<br />
<syntaxhighlight lang="lua"> -- this will create a map window docked at the left corner<br />
myMapWidget = Geyser.Mapper:new({embedded=false, dockPosition="left"})<br />
</syntaxhighlight><br />
<br />
Possible dockPositions are: left "l", right "r", top "t", bottom "b" and floating "f"<br />
<br />
To change the dockPosition after creation, use:<br />
<syntaxhighlight lang="lua"> -- this will change myMapWidget dockPosition to "f" floating <br />
myMapWidget:setDockPosition("f")<br />
</syntaxhighlight><br />
<br />
== Making your own mapping script ==<br />
<br />
If you'd like to code your own mapping script, see the [[Manual:Lua_Functions#Mapper_Functions|Mapper API]] and read on for a short tutorial.<br />
<br />
To start off, create a new script that'll be included with your mapping script (can even place it into the script folder for your mapping script), and have it do:<br />
<br />
<syntaxhighlight lang="lua"><br />
mudlet = mudlet or {}; mudlet.mapper_script = true<br />
</syntaxhighlight><br />
<br />
This'll let Mudlet know that a mapping script is installed, so it won't bother you or whoever else installs your script with a warning that one is necessary.<br />
<br />
Next, you want to hook into Mudlet's gotoRoom(id) function and the user clicking on a room in the visual map - for that, define your own ''doSpeedWalk()'' function. Mudlet will store the directions / special exits commands your script will need to take in the ''speedWalkDir'' table, and the room IDs you'll pass through in the ''speedWalkPath'' table:<br />
<br />
<syntaxhighlight lang="lua"><br />
function doSpeedWalk()<br />
echo("Path we need to take: " .. table.concat(speedWalkDir, ", ") .. "\n")<br />
echo("Rooms we'll pass through: " .. table.concat(speedWalkPath, ", ") .. "\n")<br />
end<br />
</syntaxhighlight><br />
<br />
''speedWalkPath'' is especially useful for making sure you're still on the path. Most Mudlet mapping scripts keep track of how many rooms along the path they have visited so far and check upon arrival into a new room to make sure it's still on the path.<br />
<br />
That's it! (But see below if you want more.)<br />
<br />
From here, you'd want to build a walking script that'll send the commands to walk you along the path, along with aliases for the user to use - see the [[Manual:Lua_Functions#Mapper_Functions|Mapper API functions]] and [[Manual:Event_Engine#Mudlet-raised_events|Mudlet mapper events]].<br />
<br />
=== Adding rooms ===<br />
To make your first room, do the following steps:<br />
<br />
* create an area with setAreaName(areaID, areaname). You can choose any areaID - if you'd like to use the IDs incrementally, see which is the latest from getAreaTable()<br />
* if you want the Mudlet mapper to generate roomIDs for you, get one with createRoomID(). This is an optional step<br />
* create your room with addRoom(roomID)<br />
* give the room coordinates with setRoomCoordinates(roomID, x, y, z). If you're just starting out, put it at 0,0,0 so the room is at the center of the map<br />
* assign your room to an area with setRoomArea(roomID, areaID)<br />
* and finally, call centerview(roomID) to make the map view refresh and show your new room!<br />
<br />
==== Labelling rooms ====<br />
<br />
Rooms have three attributes which you can show on the map:<br />
* an ID. You can't change it; the ID is shown in the room's box when you check "IDs" in the dialog below the map and you're zoomed in far enough.<br />
* a symbol, also displayed in the room's box. You set it with the [https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomChar ''setRoomChar''] Lua function, or via the map's context menu.<br />
* a name, typically sent via GMCP. You add it to the map with [https://wiki.mudlet.org/w/Manual:Lua_Functions#setRoomName ''setRoomName''].<br />
<br />
The room name can be displayed along with a room's box. Its position defaults to "centered below the room". It is not visible by default because many maps have rooms that are quite close to each other; showing the names by default would create an ugly visual mess.<br />
<br />
If you want to enable room names in your mapper, you need to<br />
* stagger rooms. Four or five units' distance instead of one works best if you want to show every label; less is OK if you only show labels when the user asks you to.<br />
* call ''setMapUserData("room.ui_showName","1")''. The existence of this entry controls whether the "Names" checkbox is shown next to "IDs", below the map. This value is zero if the user has unchecked the "Names" checkbox.<br />
* optionally call ''setMapUserData("room.ui_nameFont","FontName")'' to change the names' font. The default is the same monospaced font used for the room IDs and symbols.<br />
* call ''setRoomUserData(room_id, "room.ui_showName","1")'' to show a room's label. You might want to add an entry to the map's pop-up menu which toggles this.<br />
<br />
If the name is misplaced (collision with another room, label, or whatever), you can modify the room's "room.ui_nameOffset" attribute to move it around. The value of this attribute consists of two floating-point values, separated by a space, which offset the room's label (in units of the room box's size). You might want to bind functions that increase or decrease these values to keys like Shift-Control-Arrow and/or Control-Numpad-2468. A hotkey to toggle a room's label display from "on" to "off" and back (e.g. Control-Numpad-5?) is also a good idea.<br />
<br />
You also might default to staggering room names. One possible algorithm: '''if''' a new room's X coordinate, divided by your default room distance, is an odd number '''then''' position its label with an offset like "0 -1.6", which would place it above the room in question. The optimal value for the Y offset depends on the font.<br />
<br />
Changes are displayed only when the map is next redrawn.<br />
<br />
Font options are global. Overriding them for a single room can be be implemented if requested.<br />
<br />
=== Working with the mapper API ===<br />
Whenever working with mapper API, keep in mind of the following things:<br />
<br />
* You'll want to call centerview after you do some modifications, to get to have the map render your new changes<br />
<br />
=== Translating directions ===<br />
Several functions in the mapper API take and return #'s for directions - and to make it easier to work with them, you can define a table that maps directions to those numbers in a script with the following:<br />
<br />
<syntaxhighlight lang="lua"><br />
exitmap = {<br />
n = 1,<br />
north = 1,<br />
ne = 2,<br />
northeast = 2,<br />
nw = 3,<br />
northwest = 3,<br />
e = 4,<br />
east = 4,<br />
w = 5,<br />
west = 5,<br />
s = 6,<br />
south = 6,<br />
se = 7,<br />
southeast = 7,<br />
sw = 8,<br />
southwest = 8,<br />
u = 9,<br />
up = 9,<br />
d = 10,<br />
down = 10,<br />
["in"] = 11,<br />
out = 12,<br />
[1] = "north",<br />
[2] = "northeast",<br />
[3] = "northwest",<br />
[4] = "east",<br />
[5] = "west",<br />
[6] = "south",<br />
[7] = "southeast",<br />
[8] = "southwest",<br />
[9] = "up",<br />
[10] = "down",<br />
[11] = "in",<br />
[12] = "out",<br />
}<br />
</syntaxhighlight><br />
<br />
Then, using exitmap[input], you'll get a direction number or a direction name. Here's an example that uses it to work out in which directions are the exit stubs available in room 6:<br />
<br />
<syntaxhighlight lang="lua"><br />
lua local stubs = getExitStubs(6)<br />
for i = 0, #stubs do print(exitmap[stubs[i]]) end<br />
</syntaxhighlight><br />
<br />
=== Custom speedwalking and pathfinding ===<br />
<br />
{{MudletVersion|4.10}}<br />
If you'd like to use a custom pathfinding algorithm instead of the built-in one, you can do that:<br />
<br />
* Set ''mudlet.custom_speedwalk = true''.<br />
* Your ''doSpeedwalk'' script will now see different parameters:<br />
<br />
<syntaxhighlight lang="lua"><br />
function doSpeedWalk()<br />
echo("Room we're coming from: " .. speedWalkFrom .. "\n")<br />
echo("Room you're going to: " .. speedWalkTo .. "\n")<br />
end<br />
</syntaxhighlight><br />
<br />
The forum topic [https://forums.mudlet.org/viewtopic.php?f=6&t=22930&p=45930#p45930 Wayfinder] contains an example package that implements a shortest-path-first algorithm.<br />
<br />
=== Custom room name search function in the generic_mapper ===<br />
<br />
{{MudletVersion|4.11}}<br />
Sometimes the generic_mapper script is not flexible enough to find the room name in your favorite game. You can create a custom function that handle that search instead of the standard one included in the mapper:<br />
<br />
* Type in the input area ''map config custom_name_search true'' to enable the usage of the custom function.<br />
* Write your own function called ''mudlet.custom_name_search''. The script call it for your:<br />
<br />
<syntaxhighlight lang="lua"><br />
mudlet.custom_name_search = function (lines)<br />
-- ...<br />
local line_count = #lines + 1<br />
if string.match(cur_line, " ") then<br />
line_count = line_count - 1<br />
room_name = lines[line_count]<br />
-- map.echo("Name Search: room_nameome:" ..room_name) <br />
elseif string.find(cur_line,prompt_pattern) then<br />
-- ...<br />
return room_name<br />
end<br />
</syntaxhighlight><br />
<br />
I suggest to start from original name_search function in generic_mapper to avoid common problem.<br />
<br />
<br />
== Screenshots ==<br />
Just a few example maps from different players and games:<br />
<gallery><br />
File:Mapper 562.png<br />
File:Mudlet 563.png<br />
File:TK6fS.png<br />
File:Stary kontynent-min-scaled.png|Here is the [https://i.imgur.com/IaV6lDc.png full image] (17160 x 10120 pixel)<br />
File:MG Port Vain.png<br />
</gallery><br />
<br />
== Notes ==<br />
<references /><br />
<br />
[[Category:Mudlet Manual]]</div>Kebap