This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
TYKUHN2's profile picture

Question about Variable Access

Started by TYKUHN2, 20 August 2015 - 11:49 PM
TYKUHN2 #1
Posted 21 August 2015 - 01: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 on 20 August 2015 - 11:50 PM
KingofGamesYami #2
Posted 21 August 2015 - 01: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 on 20 August 2015 - 11:57 PM
TYKUHN2 #3
Posted 21 August 2015 - 01: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.
KingofGamesYami #4
Posted 21 August 2015 - 02: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 on 21 August 2015 - 12:00 AM
TYKUHN2 #5
Posted 21 August 2015 - 02:02 AM
Thanks. Very useful for what I am trying to do. Makes my life much easier :)/>