Difference between a const inside a proc vs outside - constants

This is probably a really dumb question, but other than visibility is there any real difference between a const inside a proc vs outside?
const foo = "FOO"
proc test() =
const bar = "BAR"
echo foo & bar
test()
Like when inside, does the stack grow and shrink for that const every time the proc is invoked, or because it's a const is it just held in a static memory location for the duration of the application?
I'm asking specifically about Nim but reflections on differences/similarities in other languages are welcome too.

If you look at the generated C code, you will see this line:
STRING_LITERAL(TMP139, "FOOBAR", 6);
What this tells us is foo & bar was evaluated at compile time.
nimbase.h has this:
#define STRING_LITERAL(name, str, length) \
static const struct { \
TGenericSeq Sup; \
NIM_CHAR data[(length) + 1]; \
} name = {{length, length}, str}
const in Nim is much more than a static memory location. But it does seem like in this case we get the string "FOOBAR" in a static memory location. However, if we replace these strings with numbers, for example, 1 and 3, the generated code just has a 4 literal without any storage.
Now, for the actual question. The only difference here is the scope in which the constants are seen.
If this wasn't simplified in such a way (e.g. if you wrote echo foo\\echo bar), we can consult the generated code again and see two identical (except for content) STRING_LITERAL declarations.

Related

C/C++ Is it possible to #undef a serial of macro starting by the same patern?

I'm writing a tool using macros to generate enum. When done, I want to undef all those macros, but I don't know all names yet. Somes will comes later in developement. So I want to make a generic undef like...
#undef ENUM_*
Is that possible ? The macros simplified looks like that:
First...
#define ENUM_VALUE(VALUE) VALUE,
#define ENUM_STRING(STRING) #STRING,
#define ENUM_GENERATE(NAME)\
namespace NAME {\
enum Enum: int { ENUM_##NAME(ENUM_VALUE) };\
const char *Names[] = { ENUM_##NAME(ENUM_STRING) };\
}\
Then for each enum I define...
#define ENUM_MyEnum(VALUE)\
VALUE(Value1)\
VALUE(Value2)\
VALUE(Value3)
ENUM_GENERATE(MyEnum)
It generate a synchronized enum and string table like if I had declared
namespace MyEnum {
enum Enum: int { Value1, Value2, Value3 };
const char *Names[] = { "Value1", "Value2", "Value3" };
}
The only problem is that I end with truck load of macros. Somes I don't know yet, because they will be define later when I new enums will be creted. But all start by ENUM_
Is there a simple way to undef them all ? Thanks
Here is a detailed proposal for the "base macro" idea from comment:
It leaves some defined macros behind, but guarantees that any use is blocked by a single macro not being defined.
I.e. you undef that single one and all attempts to use one of the macros from the group it represents result in a "undefined" error,
or maybe in some defined expansion, which is however sure to annoy the compiler.
// Infrastructure
#define BASE_BASE(ParWhich) BASED_##ParWhich
// Secondary infrastructure, needed for supporting parameterised macros.
#define BASE_NOPAR(ParWhich) BASE_BASE(ParWhich)
#define BASE_ONEPAR(ParWhich, ParOne) BASE_BASE(ParWhich)(ParOne)
// Potentially many macros being defined in a slightly "get-used-to" manner.
#define BASED_A Hello
#define BASED_B(ParWhat) ParWhat
#define BASED_C(ParWord) ParWord
// Example line, to be expanded by prepro with defined macro BASE_BASE.
BASE_NOPAR(A) BASE_ONEPAR(B,PreProcessor) BASE_NOPAR(B)(World.)
// The one line which should lead to compiler errors for any use of one of the macros.
#undef BASE_BASE
// Same example again.
BASE_NOPAR(A) BASE_ONEPAR(B,PreProcessor) BASE_NOPAR(B)(World.)
// Not necessary, just to make sure and to make readable prepro-output.
#define BASE_BASE(ParIgnore) Compiler, please fail here!
// Same example again.
BASE_NOPAR(A) BASE_ONEPAR(B,PreProcessor) BASE_NOPAR(B)(World.)
Using the parameter-free base macro with a parameter in a following pair braces, as done in the example BASE_NOPAR(C)(World.)
should not be done directly in code anywhere; because it would, in my opinion,
turn into maintenance nightmare soon.
I.e. it should be done in a central "core" place as demonstrated otherwise.
Wouldn't want any code written like that.
Output:
>gcc -E -P BaseMacro.c
Hello PreProcessor World.
BASE_BASE(A) BASE_BASE(B)(PreProcessor) BASE_BASE(B)(World.)
Compiler, please fail here! Compiler, please fail here!(PreProcessor) Compiler, please fail here!(World.) Compiler, please fail here!(World.)

Shared (or static) variable in Swift

I have a class with an array which values comes from a text file. I would like to read this values once and store them in a shared variable, making possible other classes access that values.
How can I do that in Swift?
UPDATE:
Suppose I have three classes of animals and which of them can be found in a set of places which is load from differents tables (each animal have yours and the structure is different for each one). I would like to be able to use them linking to specific class:
clBirds.Places
clDogs.Places
clCats.Places
Note that I need to load data once. If I dont´t have a shared variable and need to put it outside the class, I need to have different names to the methods, just like:
BirdsPlaces
DogsPlaces
CatsPlaces
And we don´t have heritage in this case
Declare the variable at the top level of a file (outside any classes).
NOTE: variables at the top level of a file are initialized lazily! So you can set the default value for your variable to be the result of reading the file, and the file won't actually be read until your code first asks for the variable's value. Cool!
Similarly, you can declare an enum or struct at the top level of a file (outside any classes), and now it is global. Here's an example from my own code:
struct Sizes {
static let Easy = "Easy"
static let Normal = "Normal"
static let Hard = "Hard"
static func sizes () -> String[] {
return [Easy, Normal, Hard]
}
static func boardSize (s:String) -> (Int,Int) {
let d = [
Easy:(12,7),
Normal:(14,8),
Hard:(16,9)
]
return d[s]!
}
}
Now any class can refer to Sizes.Easy or Sizes.boardSize(Sizes.Easy), and so on. Using this technique, I've removed all the "magic numbers" and "magic strings" (such as NSUserDefault keys) from my code. This is much easier than it was in Objective-C, and it is much cleaner because (as the example shows) the struct (or enum) gives you a kind of miniature namespace.

#function in CoffeeScript does not work as advertised

Rails 3.2.8. In converting some of my JS functions over to CoffeeScript, I have come across several questions that say declaring a function like so:
#foo = (bar) ->
puts foo in the global namespace. But it doesn't, because my function calls elsewhere in the application, especially ones that are in .js.erb files.
Here's what does work:
foo = (bar) ->
window.foo = foo
With that, all my calls in .js.erb files work fine.
What is the reason that the #foo = notation doesn't work as I am expecting it to? That would be a lot easier than having to remember to add an extra line to expose the function to the global namespace.
#foo translates to this.foo
foo translates to var foo
There is a big difference between the two of those.
For example:
bar = (baz) ->
#bar = 5
lemon = #bar + baz
#foo = (bar) ->
lemon
return #
Bar = new bar(12)
Translates to:
var Bar, bar;
bar = function(baz) {
var lemon;
this.bar = 5;
lemon = this.bar + baz;
this.foo = function(bar) {
return lemon;
};
return this;
};
Bar = new bar(12);
See fiddle demo of generated code: http://jsfiddle.net/maniator/rXWw2/
Here is a link showing you the CoffeeScript and it's generated code
I just wanted to add something that seems important to understanding why the initial
#foo = () -> "abc"
doesn't add to the global window object.
Coffeescript wraps - once compiled, it wraps all contents of every .coffee-file into a surrounding anonymous function that is immediately executed.
Thusly, and explicitely for that reason, the global namespace is not polluted, thereby implicitely protecting the dev from creating "evil" globals.
So, your foo becomes a member function of an anonymous wrapper function - how seriously useless gg ...
I guess what you want anyway is your global config object or something, to which you simply add your definitions --- you surely didn't mean to really create globals just for quick and easy access now, did you?? :)

How to dynamically create named classes in Coffeescript without using eval?

I want to be able to write:
generate 'Cat', 'meow'
and define the generate function in such a way that it produces:
class Cat
meow: ->
#.__proto__.constructor.name + ' says meow.'
so that I can write:
garfield = new Cat
garfield.meow() # "Cat says meow"
If you don't mind polluting your global namespace, I actually got this snippet running in the 'try coffeescript' runner at the CoffeeScript site:
root = exports ? window
alert = alert or console.log
gen = (clsname, val) ->
root[clsname] = class
meow: => "#{clsname} says #{val}"
gen 'Cat', 'meow'
g = new root.Cat
alert g.meow()
gen 'Dog', 'woff'
d = new root.Dog
alert d.meow()
Not 100% what you asked for, but it's almost what you wanted, isn't it?
Edit: Actually, the first script only worked in the browser, not the (Node.js-based) CLI, corrected the script.
If you know you'll only live in the browser, you can loose root.Cat and only say Cat, but if you want Node.js and browser compat, you'll have to live with root.*
Edit 2: It's generally a better idea to return the class from the generating function rather than magically putting it in a namespace. It's also possible to make the method names dynamic. With some inspiration from #Loren, the asker (notice how it doesn't need to refer the global object anymore):
alert = alert or console.log
gen = (clsname, val) ->
C = class
C.prototype[val] = -> "#{clsname} says #{val}"
C
Cat = gen 'Cat', 'meow'
console.log Cat
g = new Cat
alert g.meow()
Dog = gen 'Dog', 'woff'
d = new Dog
alert d.woff()
If by "named class" you mean "a class with a named function," what you're asking for isn't possible—in CoffeeScript or JavaScript. Without eval, there's no way to create the equivalent of function FuncName() {...}. You can only use the __proto__.constructor.name property on functions defined with that syntax.
The class syntax is the only way of creating named functions in CoffeeScript, for reasons explained in the FAQ.

How have you dealt with the lack of constructors in VB6?

VB6 classes have no parameterized constructors. What solution have you chosen for this? Using factory methods seems like the obvious choice, but surprise me!
I usually stick to factory methods, where I put the "constructors" for related classes in the same module (.BAS extension). Sadly, this is far from optimal since you can't really limit access to the normal object creation in VB6 - you just have to make a point of only creating your objects through the factory.
What makes it worse is having to jump between the actual object and your factory method, since organization in the IDE itself is cumbersome at best.
How about using the available class initializer? This behaves like a parameterless constructor:
Private Sub Class_Initialize()
' do initialization here
End Sub
I use a mix of factory functions (in parent classes) that then create an instance of the object and call a Friend Init() method.
Class CObjects:
Public Function Add(ByVal Param1 As String, ByVal Param2 As Long) As CObject
Dim Obj As CObject
Set Obj = New CObject
Obj.Init Param1, Param2
Set Add = Obj
End Function
Class CObject:
Friend Sub Init(ByVal Param1 As String, ByVal Param2 As Long)
If Param1 = "" Then Err.Raise 123, , "Param1 not set"
If Param2 < 0 Or Param2 > 15 Then Err.Raise 124, , "Param2 out of range"
'Init object state here
End Sub
I know the Friend scope won't have any effect in the project, but it acts as a warning that this is for internal use only.
If these objects are exposed via COM then the Init method can't be called, and setting the class to PublicNotCreatable stops it being created.
This solution is far from perfect, however, this is what I ended up doing for some of my legacy projects. It's somewhat memory-efficient for storage, but just looking up something definitely takes more time than otherwise required, especially for the huge structs.
Suppose you need to implement the following,
type user
id as long
name as String
desc as String
end type
But notice that VB6 natively supports Strings. So Instead of using structs, have "fake-struct" functions such as
Public Function user_raw(ByVal id as Long, ByRef name as String, ByRef desc as String) as String
Const RAW_DELIM as String = "|"
user_raw = cstr(id) & RAW_DELIM & name & RAW_DELIM & desc
End Function
So as a result, you will have passable-by-value (hence stackable into arrays, or multiline Strings), "fake-structs" made of strings such as
1|Foo|The boss of VB
2|Bar|Foo's apprentice
So the construct also counts as a crude way to perform to_string(). On the slightly good side, such storage is almost instantly convertible to the Markdown table syntax.
Later on, you can retrieve data from the struct by doing something like,
Public const RAW_DELIM as String = "|"
Public Const POS_USER_ID = 0
Public Const POS_USER_NAME = 1
Public Const POS_USER_DESC = 2
'...
public function get_raw_variable(byref user as String, byval var as integer) as String
dim buf() as String
buf = SPLIT(user, "|")
Assert ubound(buf) <= var
get_raw_variable = buf(var)
end function
The retrieval is sure inefficient, but is about the best you can have. Good luck