Simplifying this code

Hi, so I’m wondering how should I simplify this code I have to add Data to a Table, I plan to add more to the functions, but i just want to get this out of the way if there is a better way to do this.

The first thing I did Simplify was with the if statements where you would check for a Condition and if true, it will return an error():

if Condition then error("error occurred!") end

But, this would be a bit unnecessary to do,
however this can be simplified with assert()

assert(Condition, "error occurred!")

But the issue is that I would have to use assert() everytime to check for a statement, if this there are way to simplify it so I don’t have to use that many?

I am wondering if there was a way to simplify all these assert() functions:

function string, Value: any) -- All these assert functions
	assert(Key ~= nil, "Key must have a Value!")
	assert(string.len(Key) > 0, "Key must not be empty!") -- I get you can use #Key but ¯\_(ツ)_/¯ 
	assert(type(Key) == "string", "Key has to be a string!") -- might not be necessary
	assert(DataKeys[Key] == nil, "Key Already exists.") -- maybe "not DataKeys[Key]?"
	assert(Value ~= nil, "Value Cannot be nil")
	DataKeys[Key] = Value -- I plan to add more than just this, I'm just Testing if this works
1 Like

Should already be simple enough, you have n amount of unique conditions and n amount of unique error messages to check, they match n = n.

One option I can think of is reducing the number of conditions using and. However you will lose the accurate description of the error so it is not recommended.

Second option is using another function to check perhaps with some looping but it will mame it hard to read.

1 Like

The first arguments of assert(), check if the boolean is false or nil. For example:

assert(false, "because it was a false") -- prints the error
assert(nil, "because it was a nil") -- prints the error
assert(true, "because it wasn't false") -- doesn't prints the error

So maybe the conditions that have this: (something) ~= nil

How does this help with what I’m asking?

its basically a faster way of saying if not condition then error end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.