Jump to content




Question about Variable Access


  • You cannot reply to this topic
4 replies to this topic

#1 TYKUHN2

  • Members
  • 210 posts
  • LocationSomewhere in this dimension... I think.

Posted 21 August 2015 - 12:49 AM

I am kinda derping and... well... kinda having a program derp.

I made 2 quick programs ot test variable access, I orignally intended to keep this off the forums.

File: variable
local id = idGet
function printID()
print(type(id).." "..type(idGet))
print(id)
end

File: variableTest
idGet = 5
os.loadAPI("variable")
idGet = 7
id = 6
variable.printID()
print(id)
returns "nil nil"
returns ""
returns "6" (as expected)

And if you wanna not debug this code just answer this question: Would it return 5 or 7 optimally?

Edited by TYKUHN2, 21 August 2015 - 12:50 AM.


#2 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 21 August 2015 - 12:56 AM

If you want to set a value in an API, make a function in the API do it.

local id
function printID()
  print( type( id ) )
  print( id )
end
function setID( n )
  if type( n ) == "number" then
    id = n
  else
    error( "Expected number, got " .. type( n ), 2 )
  end
end

os.loadAPI( "variable" )
variable.setID( 5 )
variable.printID()
variable.setID( "Hello!" ) --#error

Edit: Fixed derpy post (internet issues)

Edited by KingofGamesYami, 21 August 2015 - 12:57 AM.


#3 TYKUHN2

  • Members
  • 210 posts
  • LocationSomewhere in this dimension... I think.

Posted 21 August 2015 - 12:58 AM

That wasn't the intention. I wasn't 100% sure how variable accessing worked though you may have inadvertently failed to explain it and succeeded at the same time. I was trying to figure out if I localize the variable on load of the API I could lock it down preventing easy overwritting.

#4 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 21 August 2015 - 01:00 AM

If you make a variable local to the API, it cannot be changed afterward (by other programs). The only exception would be tables, because if you simply do
local my_tbl = tbl

my_tbl will contain the pointer that tbl did previously. Setting "tbl" in another program will not change my_tbl, but changing tbl[1] will change my_tbl[1].

Any questions?

Edited by KingofGamesYami, 21 August 2015 - 01:00 AM.


#5 TYKUHN2

  • Members
  • 210 posts
  • LocationSomewhere in this dimension... I think.

Posted 21 August 2015 - 01:02 AM

Thanks. Very useful for what I am trying to do. Makes my life much easier :)





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users