Page 1 of 1

How to call a function from one script to main.lua

Posted: Sun Sep 09, 2018 9:28 am
by HarryCourt
Hello everyone! Sorry if I am repeating a question, but I couldn't find anything.

I have a function named item1 in a file named items.lua, and I want to get the item1 function from that script and run it in main.lua.

Here is items.lua:

Code: Select all

items = {}

centerX = love.graphics.getWidth() / 2
centerY = love.graphics.getHeight() / 2

function item1()
  sprite = love.graphics.newImage('sprites/stick.png') -- Image used for item
  health = 10 -- Health for item

  love.graphics.draw(sprite, centerX, centerY) -- Draw the sprite, and put it in the center
end

return items
Here is main.lua (Not all of it, just the important part):

Code: Select all

-- Other require parts here
items = require("items")

-- Load everything
function love.load()
  -- Load other scripts

  items.item1()
-- Continue loading everything
end
-- Continue other functions
I am terribly sorry if there is answer for this somewhere, or if this is a really simplistic question; I am learning the ropes still ^^

Re: How to call a function from one script to main.lua

Posted: Sun Sep 09, 2018 9:41 am
by grump
Remove the draw call from function item1. You need to call that from love.draw, not from love.load.

Also, you should put 'local' in front of all variable definitions, otherwise they're all global and you don't want that.

Re: How to call a function from one script to main.lua

Posted: Sun Sep 09, 2018 9:49 am
by zorg
To be a bit contrary to grump, let me give a different answer;

You can absolutely have love.graphics.draw and other stuff in functions other than love.draw; but grump is right in that you ultimately want to call your item1 function from love.load.

Now, to actually answer your question, you want to put the item1 function into the items table itself, that you're returning. There's actually two ways you can write the function's line like that: function items.item1() or items.item1 = function().

But apart from that, you should also separate the draw call out to a separate function, like items.draw or something; that would be the usual approach (which you'd then call from love.draw in your main.lua)

Re: How to call a function from one script to main.lua

Posted: Sun Sep 09, 2018 11:41 am
by grump
Ugh, yeah I did not realize that item1 is not a member of the items table. :oops:
zorg wrote: Sun Sep 09, 2018 9:49 am You can absolutely have love.graphics.draw and other stuff in functions other than love.draw
Sure can, but if you draw something to the screen from love.load you're not going to see it because the screen will be cleared before it shows up.