Jump to content

Recommended Posts


I've read a article about lua functions here: https://debian-administration.org/article/264/Embedding_a_scripting_language_inside_your_C/C_code

There are two ways of include lua scripts to your AutoIt code.

1. Run lua functions by Autoit.

2. Register Autoit function and run as lua.

It's even possible to apply second way to AutoIt?

As we can see on example there a few functions to make it possible.

It's a lua file save as average.lua

avg, sum = average(10, 20, 30, 40,  50)

print("The average is ", avg)
print("The sum is ", sum)

This is a C functions to run lua. Can be convert to AutoIt ofc.

There is a problem with func lua_register(L, "average", average)

this function is not even detected in Lua51.dll

We can use lua_pushcclosure instead.

#include <stdio.h> 

#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

/* the Lua interpreter */
lua_State* L;

/* The function we'll call from the lua script */
static int average(lua_State *L)
        /* get number of arguments */
        int n = lua_gettop(L);
        double sum = 0;
        int i;

        /* loop through each argument */
        for (i = 1; i <= n; i++)
                if (!lua_isnumber(L, i)) 
                      lua_pushstring(L, "Incorrect argument to 'average'");

                /* total the arguments */
                sum += lua_tonumber(L, i);

        /* push the average */
        lua_pushnumber(L, sum / n);

        /* push the sum */
        lua_pushnumber(L, sum);

        /* return the number of results */
        return 2;

int main ( int argc, char *argv[] )
        /* initialize Lua */
        L = lua_open();

        /* load Lua base libraries */

        /* register our function */
        lua_register(L, "average", average);

        /* run the script */
        lua_dofile(L, "average.lua");

        /* cleanup Lua */

        return 0;




Link to post
Share on other sites
  • Developers
2 minutes ago, Earthshine said:

Is there a question? This is the gelp forum

Yes... Gelp? ;)

14 minutes ago, Ascer said:

It's even possible to apply second way to AutoIt?


Edited by Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
Live for the present,
Dream of the future,
Learn from the past.

Link to post
Share on other sites

This is an another example from autoit site.


As an example, the following function receives a variable number of numerical arguments and returns their average and sum:

       static int foo (lua_State *L) {
         int n = lua_gettop(L);    /* number of arguments */
         lua_Number sum = 0;
         int i;
         for (i = 1; i <= n; i++) {
           if (!lua_isnumber(L, i)) {
             lua_pushstring(L, "incorrect argument to function `average'");
           sum += lua_tonumber(L, i);
         lua_pushnumber(L, sum/n);        /* first result */
         lua_pushnumber(L, sum);         /* second result */
         return 2;                   /* number of results */

To register a C function to Lua, there is the following convenience macro:

       #define lua_register(L,n,f) \
               (lua_pushstring(L, n), \
                lua_pushcfunction(L, f), \
                lua_settable(L, LUA_GLOBALSINDEX))
     /* lua_State *L;    */
     /* const char *n;   */
     /* lua_CFunction f; */

which receives the name the function will have in Lua and a pointer to the function. Thus, the C function foo above may be registered in Lua as average by calling

       lua_register(L, "average", foo);

Im guess that problem is in pushing parameter $lua_CFunction into DLLCALL func see below.

Func lua_pushcclosure($lua_CFunction, $index = 0, $p_state = 0)

    If Not _Lua_Initiate() Then Return SetError(-1, 0, 0)

    If $p_state = 0 Then $p_state = $__g_pluanewstate

    Local $aRet = DllCall($__g_hluadll, "none:cdecl", "lua_pushcclosure", "ptr", $p_state, "str", $lua_CFunction, "int", Int($index))
    If @error Then Return @error

    Return 1


How to push param such as function ?

We have a function:

Func Jos()
    Return 1

When i push like this no error but also nothing happen.


I've check var for Jos.

ConsoleWrite("jos: " & VarGetType(Jos) & @CRLF)
;==> return UserFunction

So.. how to pas UserFunction in dll

"str" ? UserFunction
Edited by Ascer
Link to post
Share on other sites


[-0, +1, m]

void lua_pushcfunction (lua_State *L, lua_CFunction f);

Pushes a C function onto the stack. This function receives a pointer to a C function and pushes onto the stack a Lua value of type function that, when called, invokes the corresponding C function.

Any function to be registered in Lua must follow the correct protocol to receive its parameters and return its results (see lua_CFunction).

lua_pushcfunction is defined as a macro:

     #define lua_pushcfunction(L,f)  lua_pushcclosure(L,f,0)



not sure why you are pushing string onto stack with pushstring.

Edited by Earthshine

My resources are limited. You must ask the right questions


Link to post
Share on other sites


Thanks for answer.

As autoit in lua documentation: https://www.autoitscript.com/autoit3/scite/docs/SciTE4AutoIt3/Lua/manual.html

   #define lua_register(L,n,f) \
               (lua_pushstring(L, n), \
                lua_pushcfunction(L, f), \
                lua_settable(L, LUA_GLOBALSINDEX))
     /* lua_State *L;    */
     /* const char *n;   */
     /* lua_CFunction f; */

I replaced it to autoIt code:

Tried many times..

This examples looks good but not working

lua_pushstring("Jos") ; push string to stack
lua_pushcclosure(Jos, 0) ; push function index default index 0
lua_setglobal("Jos") ; set global function

lua_pushstring("Jos") ; push string to stack
lua_pushcclosure(Jos, 0) ; push function index default index 0
lua_settable($LUA_GLOBALSINDEX) ; set global table index

Func Jos()
    Return 0


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By argumentum
      In the console under the editor in SciTE: 
      if I add @@ Debug(line,column) then it goes there.
      if I add "script.au3" (line,column) then it goes there if loaded.
      if I add "c:\path\script.au3" (line,column) then it loads the file and goes there.
      ...so far so good.
      Since I don't know LUA, nor where that is at, my question is ... where is it at ?
      A silly question because once there I would not know what to do, since I don't know LUA.
      What I want to achieve is, that since there is something delimiting the script and editor position (li,co), a way to have, let's say:
      +I like this color and the text that I care for on the left ["c:\path\script.au3" (line,column)]
      and by having this ["" ()] format ( or anything else, it don't have to be this exact format ), the console would know to jump there.
      If DClick to jump/goto Line,Column can trigger an external EXE or script, I'd take it from there. If it all can be done from LUA then, I'd do it there.
      So I don't mind or know how. I just would like that functionality. In a way that don't require a recompile of SciTE.
    • By matwachich
      AutoIt3 Lua Wrapper
      This is an AutoIt3 wrapper for the Lua scripting language. Consider it beta software, but since I will be using it in commercial product, expect it to evolve.
      It has been developped with Lua 5.3.5. Updates will come for new Lua version.
      Everything works just fine, except one (big) limitation: Anything that throws a Lua error (using C setjmp/longjmp functionality) will crash your AutoIt program. That means that it is impossible to use throw errors from an AutoIt function called by Lua (luaL_check*, lua_error...).
      It is hosted in Github: https://github.com/matwachich/au3lua
      Simple example
      #include <lua.au3> #include <lua_dlls.au3> ; Initialize library _lua_Startup(_lua_ExtractDll()) OnAutoItExitRegister(_lua_Shutdown) ; create new execution state $pState = _luaL_newState() _luaopen_base($pState) ; needed for the lua's print function $iRet = _luaL_doString($pState, 'print("Hello, world!")') If $iRet <> $LUA_OK Then ; read the error description on top of the stack ConsoleWrite("!> Error: " & _lua_toString($pState, -1) & @CRLF) Exit EndIf ; close the state to free memory (you MUST call this function, this is not AutoIt's automatic memory management, it's a C library) _lua_close($pState)
    • By youtuber
      Win32 API GetOpenFileName using the function with lua.
      Can I open a file dialog box in the folder I am in with lua. FileOpenDialog ('Open a Text File', @ScriptDir ...
      and such.
      $FileOpenDialog = FileOpenDialog('Open a Text File', @ScriptDir, 'Text Files (*.txt)')
      I'm looking for a command like this
      FileOpenDialog = GetOpenFileName("Open a Text File", "txt\n*.txt", @ScriptDir)
    • By BugFix
      This lua script gives you the ability, to search for selected text or word from cursor in an search engine or on an search site of your choice.You can select the engine/site from a list, that you have defined in your user properties.
      To get the right call for your search engine, open the engine and search for one word. You need the url without the searched word. Write to your properties an display name for this engine and, separated by a comma, the url. See my example in the script header.
      For the list with  search sites, you need display name and site address (without http://).
      It will searched for the full selected text or, if none selection exists, for the word touched by the cursor. You can allow in the properties, that also will recognized words with dots (like objVar.Property).
      The script uses the shell.dll. But if you don't have installed it, the browser will opened with an command line call. Thats why the command window will pop up for a short moment.
      You'll find details for installation and key bindings inside the script. Look for free command numbers in SciTE. By default installation, the numbers must be greater than 35 (max. 49).
      -- TIME_STAMP 2018-09-02 09:22:03 --[[ This script publicates two functions - InetSearch.Engine() You can search for the selected/touched text in SciTE and can select a search engine of your choice. - InetSearch.Site() You can search for the selected/touched text in SciTE with a defined search engine and can select a search site of your choice. Copy this script in your Lua scripts folder. Load this file in the Lua startup: dofile("Full\\Path\\InetSearch.lua") Add in "SciTEUser.properties" the following properties with search engines and search sites of your choice: #~ Inet Search Settings #~ List of engines. "display-name,search-url" (if not set: google.com will used) #~ If only one entry exists, the selection box will not shown. Inet.Search.Engines= \ Google,https://www.google.de/search?q=| \ MetaGer,https://metager.de/meta/meta.ger3?focus=web&eingabe=| \ Bing,https://www.bing.com/search?q=| \ Ask,https://de.ask.com/web?q=| \ Yandex,https://www.yandex.com/search/?text= #~ Engine for site based search #~ Use display name from engines list (if not set: google.com will used) Inet.Search.SearchOnSite.Engine=Google #~ List of sites for site based search. "display-name,site-url" #~ If not set, it searches without a special site. #~ If only one entry exists, the selection box will not shown. Inet.Search.SearchOnSite.Sites= \ AutoIt DE,autoit.de| \ AutoIt EN,autoitscript.com| \ MSDN,msdn.microsoft.com #~ By default, words will detected without dots. (0) #~ You can allow dots, to detect object variables with properties or methods too. Inet.Search.Allow.Punctuation=1 #~ Search commands #~ Search word from cursor with engine selection command.name.9.*=Search with engine selection command.9.*=dostring InetSearch.Engine() command.mode.9.*=subsystem:lua,savebefore:no command.shortcut.9.*=Ctrl+Shift+F8 #~ Search word from cursor with search site selection command.name.5.*=Search with site selection command.5.*=dostring InetSearch.Site() command.mode.5.*=subsystem:lua,savebefore:no command.shortcut.5.*=Ctrl+Shift+F9 --]] InetSearch = {} InetSearch.Handler = EventClass:new(Common) do ------------------------------------------------------------------------------------------------ local engineFallback = "Google,https://www.google.com/search?q=" -- default search engine: "display-name,search-url" local search_type = nil local engine_url = nil local search_item = nil local search_site = nil local tableSelection = nil local list_type = 16 ------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------- Load library protected local require_protected = function(_lib) local loaded_lib if pcall(function() loaded_lib = require(_lib) end) then return loaded_lib else return nil end end --> require_protected ------------------------------------------------------------------------------------------------ local shell = require_protected("shell") -- loads the shell library if exists ------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Starts the search local RunSearch = function(_item, _url, _site) local sSite = '' if _site ~= nil then sSite = "%20site:".._site end local sCmd = _url.._item..sSite if shell then shell.exec(sCmd) else os.execute('start "" "'..sCmd..'"') end end --> RunSearch ------------------------------------------------------------------------------------------------ ----------------------------------------------------------------------------- Show the user list local ShowSelectionList = function() -- create the selection list (display names from engines or sites) local sep, list = '_', tableSelection[1][1] for i = 2, #tableSelection do list = list..sep..tableSelection[i][1] end local sep_tmp = editor.AutoCSeparator editor.AutoCSeparator = string.byte(sep) editor:UserListShow(list_type, list) editor.AutoCSeparator = sep_tmp end --> ShowSelectionList ------------------------------------------------------------------------------------------------ --------------------------------------------------------------------------- Select the user list function InetSearch.Handler:OnUserListSelection(_tp, _sel) if _tp == list_type then local url for i = 1, #tableSelection do if tableSelection[i][1] == _sel then url = tableSelection[i][2] break end end if search_type == 'site' then search_site = url else search_site = nil engine_url = url end RunSearch(search_item, engine_url, search_site) end end ------------------------------------------------------------------------------------------------ --------------------------------------------------------- List of search engines from properties local GetEngines = function() local sEngines = props['Inet.Search.Engines'] -- without settings, the default search engine will used if sEngines == '' then sEngines = engineFallback end local tEngines = {} for entry in sEngines:gmatch('([^|]+)|-') do for name, url in entry:gmatch('([^,]+),(.+)') do table.insert(tEngines, {name, url}) end end return tEngines end --> GetEngines ------------------------------------------------------------------------------------------------ ----------------------------------------------------------- List of search sites from properties local GetSearchSites = function() local sSites = props['Inet.Search.SearchOnSite.Sites'] if sSites == '' then return nil end local tSites = {} for entry in sSites:gmatch('([^|]+)|-') do for name, url in entry:gmatch('([^,]+),(.+)') do table.insert(tSites, {name, url}) end end return tSites end --> GetSearchSites ------------------------------------------------------------------------------------------------ -------------------------------------------------------------------------------- Get search item local GetSearchItem = function() local sSelect = editor:GetSelText() if sSelect ~= '' then return sSelect end local allowDots = false if props['Inet.Search.Allow.Punctuation'] == '1' then allowDots = true end local caret = editor.CurrentPos local iLine = editor:LineFromPosition(caret) local iZero = editor:PositionFromLine(iLine) editor:LineEnd() local iLineEnd = editor.CurrentPos editor.CurrentPos = caret editor:SetSelection(caret,caret) local iStart = editor:WordStartPosition(caret) if allowDots then while iStart > iZero and editor:textrange(iStart -1, iStart) == '.' do iStart = editor:WordStartPosition(iStart -1) end end local iEnd = editor:WordEndPosition(caret) if allowDots then while iEnd < iLineEnd and editor:textrange(iEnd, iEnd +1) == '.' do iEnd = editor:WordEndPosition(iEnd +1) end end sSelect = editor:textrange(iStart, iEnd):gsub('^([^%w]+)', ''):gsub('([^%w]+)$', '') return sSelect end --> GetSearchItem ------------------------------------------------------------------------------------------------ ------------------------------------------------------------------- Search with engine selection local SearchEngineBased = function() search_type = 'engine' search_item = GetSearchItem() if search_item == '' then return nil end tableSelection = GetEngines() -- only one entry: selection box will not shown if #tableSelection == 1 then RunSearch(search_item, tableSelection[1][2], nil) else ShowSelectionList() end end --> SearchEngineBased ------------------------------------------------------------------------------------------------ -------------------------------------------------------------- Search with search site selection local SearchSiteBased = function() search_type = 'site' search_item = GetSearchItem() if search_item == '' then return nil end -- get the default engine for site based searching for _, url in engineFallback:gmatch('([^,]+),(.+)') do engine_url = url end -- if is set, use search engine from properties local sEngine = props['Inet.Search.SearchOnSite.Engine'] if sEngine ~= '' then local tEngines = GetEngines() for i = 1, #tEngines do if tEngines[i][1] == sEngine then engine_url = tEngines[i][2] break end end end tableSelection = GetSearchSites() -- if none entries for search sites, use simple search if tableSelection == nil then RunSearch(search_item, engine_url, nil) else -- only one entry: selection box will not shown if #tableSelection == 1 then RunSearch(search_item, engine_url, tableSelection[1][2]) else ShowSelectionList() end end end --> SearchSiteBased ------------------------------------------------------------------------------------------------ ---------------------------------------------------------------------------- Publicate functions InetSearch.Engine = SearchEngineBased InetSearch.Site = SearchSiteBased ------------------------------------------------------------------------------------------------ end ----------------------------------------------------------------------------------------------------  
    • By jaberwacky
      When ever you hover your mouse over a native function, user defined function, or an AutoItObject method then you will see the calltip for that function. 
      Click "Like This" if you found this useful!

      To use this just place the following lua file in the "...AutoIt3SciTELUA" directory. 
      After you have done that then open SciTE and click 'Options' --> 'Open Lua Startup Script' and paste this line after the other lines (may require administrative rights):
      LoadLuaFile("MouseHoverCallTips.lua") Updates and changes:

  • Create New...