Skip to content

Feature request - new compiler option - noImplicitGlobalVariables #1119

@Zamiell

Description

@Zamiell

Edit - I renamed this issue; see discussion below.

In Lua land, regardless of what file you are working in, you always have to prepend your variables with local in order to avoid them from becoming a global variable. This is annoying, because you almost never want to create a global variable.

-- in file: foo.lua
local foo = "bar";

Most of the time, TSTL does not have this problem, which is great.
In TSTL land, you just declare normal variables, and they are almost always local.

// in file: foo.ts
const foo = "bar"; // Will transpile to the previous code snippet

However, there are two exceptions:

  1. when luaBundle mode is turned off, any variables/functions in a file called "main.ts" or "init.ts" will automatically get turned into globals
  2. when luaBundle mode is turned on, any variables/functions in the specified bundle entry point file will automatically get turned into globals

This is a hidden "gotcha" for TSTL users. I've been happily using TSTL for almost an entire year now, and only discovered this behavior recently. Unbeknownst to me, global variables were being created and causing run-time errors in production. ><

In a way, this behavior does make sense, because if I typed const foo = "bar"; into a <script> tag on a webpage, that would obviously create a global variable. So, I think that TSTL is trying to mimic that behavior.

With that said, I think there is room for improvement here. If TSTL only creates global variables in some situations, and doesn't create global variables in other situations, this is confusing for end users. A better default might be for TSTL to just always output local variables, even in the above two situations. This helps prevents users from shooting themselves in the foot.

Consider that if an end-user is in a file called "foo.ts" and they want to create a global variable, it would look like this:

declare let foo: string;
foo = "bar";

Essentially, I am requesting that this global-variable-declaration-format is necessary across the board, for all TSTL files.

I think it's a good default behavior to have because using a global variable is the exception, rather than the norm. One typically only creates a global variable if they are explicitly exposing functionality to the outside world. And any particular program will only need to have a few global variables in total.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions