For a field inside a deeply nested table, for example, text.title.1.font. Even if you use
if text.title.1.font then ... end
it would result in an error like "attempt to index global 'text' (a nil value)" if any level of the table does not actually exists. Of course one may tried to check for the existence of each level of the table, but it seems rather cumbersome. I am wondering is there a safe and prettier way to handle this, such that when referencing such an object, nil would be the value instead of triggering an error?
The way to do this that doesn't invite lots of bugs is to explicitly tell Lua which fields of which tables should be tables by default. You can do this with metatables. The following is an example, but it should really be customized according to how you want your tables to be structured.
-- This metatable is intended to catch bugs by keeping default tables empty.
local default_mt = {
__newindex =
function()
error(
'This is a default table. You have to make nested tables the old-fashioned way.')
end
}
local number_mt = {
__index =
function(self, key)
if type(key) == 'number' then
return setmetatable({}, default_mt)
end
end
}
local default_number_mt = {
__index = number_mt.__index,
__newindex = default_mt.__newindex
}
local title_mt = {__index = {title = setmetatable({}, default_number_mt)}}
local text = setmetatable({}, title_mt)
print(text.title[1].font)
Egor's suggestion debug.setmetatable(nil, {__index = function()end}) is the easiest to apply. Keep in mind that it's not lexically scoped, so, once it's on, it will be "on" until turned off, which may have unintended consequences in other parts of your code. See this thread for the discussion and some alternatives.
Also note that text.title.1.font should probably be text.title[1].font or text.title['1'].font (and these two are not the same).
Another, a bit more verbose, but still usable alternative is:
if (((text or {}).title or {})[1] or {}).font then ... end
Related
I need to get some values for a hash but, I don't know how can I do it!
My data:
data = {
name: "Pedro Álvares",
age: 35,
sensitive_data: {
cpf_cnpj=>27046645678,
fantasy_name: "I have the power"
}
}
I search for ruby methods and find the method values_at, but this method gets only the first_data like name, age.
If I use:
name = data.values_at(:name)
the field returned is Pedro Álvares
but if I try use:
fantasy_name = data.values_at(:fantasy_name)
the data returned is nil.
How can I get the field without using data[:sensitive_data][:fantasy_name]?
Because you know the correct structure of the hash you should write:
data[:sensitive_data][:fantasy_name]
#=> "I have the power"
You should not use dig here. Why? Suppose you accidently wrote
data.dig(:sesnitive_data, :fantasy_name)
The would return nil (because data has no key :sesnitive). Depending on the context the error might not surface until sometime later, making debugging more difficult than is necessary.
By contrast, if you wrote
data[:sesnitive_data][:fantasy_name]
data[:sesnitive_data] would return nil (because data has no key :sesnitive_data) and then nil[:sesnitive_data] would raise an exception, informing you that nil has no method []. That is precisely what you want to happen: you want to be notified of the error immediately, and have the reason for it it pinpointed, so you can easily correct your code.
Hash#dig, Array#dig and Struct#dig (which call each other) have their uses (when you do not know the structures of objects in advance--a hash's keys, for example), but those methods should not be used when an object's structure is known.
You could get the nested value by dig method:
data.dig(:sensitive_data, :fantasy_name) # => "I have the power"
I have a list with special users and normal users. Special users have their own special func, while normal users use a standard func.
I came up with this code design, but I feel that this is not optimal (performance wise).
So my question is: How would I get the best performance when calling inner functions like the example below?
if something then
CallFunc(var)
end
Special/normal user logic
function CallFunc(var)
if table[name] then
table[name](var)
else
Standard_Func(var)
end
end
local table = {
["name1"] = function(var) Spec_Func1(var) end,
["name2"] = function(var) Spec_Func2(var) end,
["name3"] = function(var) Spec_Func3(var) end,
...
--40 more different names and different funcs
}
Special user funcs
function Spec_Func1(var)
--lots of code
end
function Spec_Func2(var)
--lots of code
end
...
--more funcs
EDIT:
see #hjpotter92's answer:
I cant find the user in the table.
local function_lookups = {
name1 = Spec_Func1, --this doesnt let me find the user
--name1 = 1 --this does let me find the user (test)
}
if function_lookups[name] then --this fails to find the user
--do something
end
You do not need another anonymous function. Simply use the lookup table as follows:
local function_lookups = {
name1 = Spec_Func1,
name2 = Spec_Func2,
name3 = Spec_Func3,
...
--40 more different names and different funcs
}
Do not use the variable name table. It is a library available in Lua itself, and you are overwriting it.
You don't need a special function at all! You can use a generic function that's behaviour depends on the caller! Lemme explain with a piece of code:
local Special = {Peter=function(caller)end} --Put the special users' functions in here
function Action(caller)
if Special[caller] then
Special[caller](caller)
else
print("Normal Action!")
end
end
So whenever a user does a certain action, you can fire this function and pass a caller argument, the function then does the work behind the scenes determining if the caller is special, and if so what to do.
This makes your code clean. It also makes it easier to add more than 2 user statuses!
I have seen when coding in LINQ that when a value is assigned to a field sometimes is in this way Table["Field"] and any others like this Table.Field but can somebody explain me what's the difference please?
For example when modifying a field:
var ttAbccode_xRow =
(from ttAbccode_Row in ds.ABCCode select ttAbccode_Row).FirstOrDefault();
if (ttAbccode_xRow != null) {
ttAbccode_xRow["PI"] = 3.1416;
}
or
if (ttAbccode_xRow != null) {
ttAbccode_xRow.PI = 3.1416;
}
Accessing field via indexer (square brackets) returns object data type. That means that your compiler cannot detect data types incompatibility. You could assing for example string value (eg. "abcd") and you won't get error at design time, but as late as at runtime.
Second method (if available in your result set) is much more safe. Your property will have proper data type hence compiler will detect data types incompatibility at design time.
If I had both access methods available I would always prefer second one. It is less error prone.
In the Lua language, I am able to define functions in a table with something such as
table = { myfunction = function(x) return x end }
I wondered if I can created methods this way, instead of having to do it like
function table:mymethod() ... end
I am fairly sure it is possible to add methods this way, but I am unsure of the proper name of this technique, and I cannot find it looking for "lua" and "methods" or such.
My intention is to pass a table to a function such as myfunction({data= stuff, name = returnedName, ?method?init() = stuff}).
Unfortunately I have tried several combinations with the colon method declaration but none of them is valid syntax.
So...anyone here happens to know?
Sure: table:method() is just syntactic sugar for table.method(self), but you have to take care of the self argument. If you do
tab={f=function(x)return x end }
then tab:f(x) won't work, as this actually is tab.f(tab,x) and thus will return tab instead of x.
You might take a look on the lua users wiki on object orientation or PiL chapter 16.
I've been doing a massive code review and one pattern I notice all over the place is this:
public bool MethodName()
{
bool returnValue = false;
if (expression)
{
// do something
returnValue = MethodCall();
}
else
{
// do something else
returnValue = Expression;
}
return returnValue;
}
This is not how I would have done this I would have just returned the value when I knew what it was. which of these two patterns is more correct?
I stress that the logic always seems to be structured such that the return value is assigned in one plave only and no code is executed after it's assigned.
A lot of people recommend having only one exit point from your methods. The pattern you describe above follows that recommendation.
The main gist of that recommendation is that if ou have to cleanup some memory or state before returning from the method, it's better to have that code in one place only. having multiple exit points leads to either duplication of cleanup code or potential problems due to missing cleanup code at one or more of the exit points.
Of course, if your method is couple of lines long, or doesn't need any cleanup, you could have multiple returns.
I would have used ternary, to reduce control structures...
return expression ? MethodCall() : Expression;
I suspect I will be in the minority but I like the style presented in the example. It is easy to add a log statement and set a breakpoint, IMO. Plus, when used in a consistent way, it seems easier to "pattern match" than having multiple returns.
I'm not sure there is a "correct" answer on this, however.
Some learning institutes and books advocate the single return practice.
Whether it's better or not is subjective.
That looks like a part of a bad OOP design. Perhaps it should be refactored on the higher level than inside of a single method.
Otherwise, I prefer using a ternary operator, like this:
return expression ? MethodCall() : Expression;
It is shorter and more readable.
Return from a method right away in any of these situations:
You've found a boundary condition and need to return a unique or sentinel value: if (node.next = null) return NO_VALUE_FOUND;
A required value/state is false, so the rest of the method does not apply (aka a guard clause). E.g.: if (listeners == null) return null;
The method's purpose is to find and return a specific value, e.g.: if (nodes[i].value == searchValue) return i;
You're in a clause which returns a unique value from the method not used elsewhere in the method: if (userNameFromDb.equals(SUPER_USER)) return getSuperUserAccount();
Otherwise, it is useful to have only one return statement so that it's easier to add debug logging, resource cleanup and follow the logic. I try to handle all the above 4 cases first, if they apply, then declare a variable named result(s) as late as possible and assign values to that as needed.
They both accomplish the same task. Some say that a method should only have one entry and one exit point.
I use this, too. The idea is that resources can be freed in the normal flow of the program. If you jump out of a method at 20 different places, and you need to call cleanUp() before, you'll have to add yet another cleanup method 20 times (or refactor everything)
I guess that the coder has taken the design of defining an object toReturn at the top of the method (e.g., List<Foo> toReturn = new ArrayList<Foo>();) and then populating it during the method call, and somehow decided to apply it to a boolean return type, which is odd.
Could also be a side effect of a coding standard that states that you can't return in the middle of a method body, only at the end.
Even if no code is executed after the return value is assigned now it does not mean that some code will not have to be added later.
It's not the smallest piece of code which could be used but it is very refactoring-friendly.
Delphi forces this pattern by automatically creating a variable called "Result" which will be of the function's return type. Whatever "Result" is when the function exits, is your return value. So there's no "return" keyword at all.
function MethodName : boolean;
begin
Result := False;
if Expression then begin
//do something
Result := MethodCall;
end
else begin
//do something else
Result := Expression;
end;
//possibly more code
end;
The pattern used is verbose - but it's also easier to debug if you want to know the return value without opening the Registers window and checking EAX.