Search code examples
luaworld-of-warcraft

How to call an anonymous function from a Frame in a WoW addon?


I'm using a code generator that emits many anonymous functions. I thought I'd try calling one from a Frame, but it doesn't seem to work; I get:

Date: 2020-09-18 18:42:27
ID: 1
Error occured in: Global
Count: 1
Message: [string "HelloWorldFrame:OnLoad"] line 1:
   attempt to call global 'HelloWorld' (a nil value)
Debug:
   [C]: HelloWorld()
   [string "*:OnLoad"]:1:
      [string "*:OnLoad"]:1

If I change the following:

local HelloWorld = function()
  print("Hello, World!");
end

to:

function HelloWorld() 
  print("Hello, World!"); 
end

it will work.

Here's my XML:

<Ui xmlns="http://www.blizzard.com/wow/ui/" 
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                   xsi:schemaLocation="http://www.blizzard.com/wow/ui/ 
                   ..\..\FrameXML\UI.xsd">
  <Frame name="HelloWorldFrame">
   <Scripts>
    <OnLoad>
     HelloWorld();
    </OnLoad>
   </Scripts>
  </Frame>
</Ui>

Is this possible?


Solution

  • The short answer is you need to use globals if you use XML. Something like this

    Lua

    MyUniqueAddon = {}
    
    function MyUniqueAddon:HelloWorld()
        print("Hello, World!"); 
    end
    

    XML

    <Frame name="HelloWorldFrame">
        <Scripts>
            <OnLoad>
                MyUniqueAddon:HelloWorld();
            </OnLoad>
        </Scripts>
    </Frame>
    

    You can also just do everything in Lua

    local function OnEvent(self, event)
        print("Hello, World!"); 
    end
    
    local f = CreateFrame("Frame")
    f:RegisterEvent("PLAYER_ENTERING_WORLD")
    f:SetScript("OnEvent", OnEvent)
    

    Or in this case not use a frame at all if you just want to print something as an exercise

    print("Hello, World!");