Jump to content

About LUA module variables


tipforeveryone
 Share

Recommended Posts

Here is my custom module:

local module = {}

module.SetValue = function(value)
  module.v = value
end

return module

and this is my code to call above module

local variable1 = require("mymodule")
variable1.SetValue(1)

local variable2 = require("mymodule")
variable2.SetValue(2)

System:Print(variable1.v)
System:Print(variable2.v)

As my expectation, the console should display

1
2

but it displays this instead

2
2

That means the value of variable1.v is overwriten by the value of variable2.v.
I used mymodule for 2 local variables, why dont they hold a independent value of module.v ?

Link to comment
Share on other sites

The second time you require('mymodule'), it sees that the variable 'module' already exists and will not create a new object for you. Meaning that variable2 is referencing to the same as variable1.

I think I posted the same answer in discord a while back. 

--my module
mymodule = {}

function mymodule:Create()
	local o = {}
	o.someValue = "1"
					
	function o:SetValue(value)
		o.someValue = value
	end	
	
	return o
end

 

usage:

import "path to mymodule"

local variable1 = mymodule:Create()
variable1.SetValue("test1")

local variable2 = require("mymodule")
variable2.SetValue("test2")

System:Print(variable1.v)
System:Print(variable2.v)

 

  • Thanks 1
  • Upvote 1
Link to comment
Share on other sites

Yes I remember that you explained this to me on discord months ago, I just totally forgot the answers and could not find it again on discord because Josh cancel discord once (I delayed my game development for almost 3 months and returned 1 weeks ago) Thank you again for a clear answer, and now I can bookmark it !

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...