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

Attribute Detection

Started by cdel, 15 September 2014 - 09:59 AM
cdel #1
Posted 15 September 2014 - 11:59 AM
I am working on a very basic "physics engine" and it will work by the user creating objects and giving objects attributes. However in my 'run' function I am having trouble detecting if an object has a attribute. At the moment it says there are no attributes when there are attributes.


-- Physics Engine

local table = { }

new = function(object)
  table[object] = { }
end

attribute = function(object, type, value)
  if table[object] then
    table[object][type] = value
  else
    error("That Object doesn't Exist.")
  end
end

run = function(object)
  if table[object] then
    if table[object][1] then
  
    else
	  error("That Object has no Attributes.")
    end
  else
    error("That Object doesn't Exist.")
  end
end

new("obj")
attribute("obj", "velocity", 1)
print(textutils.serialize(table))
run("obj")
Bomb Bloke #2
Posted 15 September 2014 - 01:15 PM
You're checking to see if the table in table[object] has a key of 1 (type number). In the case of table["obj"], it doesn't; it only has a key called "velocity" (type string).

I'm not aware of an elegant method to determine whether there are any keys in a given table (assuming it may only contain non-numeric keys; it's easy if you happen to know the table will only contain numeric keys). This should "work", however:

local function containsSomething(someTable)
  for key,value in pairs(table[object]) do return true end
  return false
end

if containsSomething(table[object]) then ...
cdel #3
Posted 15 September 2014 - 01:24 PM
thank you :)/>, would it be possible to also compare the table to a pre-defined table of attributes?
Bomb Bloke #4
Posted 15 September 2014 - 02:30 PM
If you mean compare the "attributes" in one table to those in another, sure.
MKlegoman357 #5
Posted 15 September 2014 - 04:27 PM
Regarding to checking if a table is empty or not can be simply condensed into this:


local function containsSomething (tbl)
  return next(tbl) ~= nil
end

To check whether a table contains required keys can be achieved using one table which holds required keys as it's values and using a for-loop to check against the user defined table:


local keys = {"key1", "key2"} --// A table with a list of required keys

local tbl = {key1 = 1, key2 = 2} --// A user-created table

for _, key in ipairs(keys) do
  if tbl[key] == nil then --// If the key doesn't exist
    error("Key " .. tostring(key) .. " was not found")
  end
end
Edited on 15 September 2014 - 02:31 PM
cdel #6
Posted 16 September 2014 - 08:16 AM
thanks for the help :D/>